pickier 0.1.60 → 0.1.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 +1 -1
- package/dist/{chunk-6xy2rbcn.js → chunk-3j5z4940.js} +2 -2
- package/dist/{chunk-cfytsdab.js → chunk-awmb5sg5.js} +1 -1
- package/dist/{chunk-ha0tzyp8.js → chunk-b2q8x0sx.js} +1 -1
- package/dist/chunk-b369mtka.js +33 -0
- package/dist/{chunk-9vc029ds.js → chunk-hwa8gmzb.js} +1 -1
- package/dist/chunk-mat3gcn4.js +2 -0
- package/dist/chunk-n23710ya.js +2 -0
- package/dist/chunk-nh6zvh3d.js +2 -0
- package/dist/{chunk-0xebhmpv.js → chunk-xjc1fk5y.js} +152 -152
- package/dist/{chunk-k110gscx.js → chunk-z1nez1br.js} +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/utils.d.ts +35 -1
- package/package.json +1 -1
- package/dist/chunk-0whyx3r0.js +0 -2
- package/dist/chunk-av6brc0s.js +0 -2
- package/dist/chunk-j0sjsw8n.js +0 -33
- package/dist/chunk-ymb49mab.js +0 -2
package/dist/bin/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import{
|
|
3
|
+
import{Q as a}from"../chunk-awmb5sg5.js";async function v(){let n=process.argv.slice(2),p=n[0]==="run",k=p?1:0,c=p?"auto":"lint",u=!1,d=!1,g=!1,h=!1,x,l=[],w=!0;for(let t=k;t<n.length;t++){let e=n[t];if(e==="--mode")c=n[++t]||"auto";else if(e==="--format")g=!0,c="format";else if(e==="--check")u=!0;else if(e==="--write")d=!0;else if(e==="--config")x=n[++t];else if(e==="--verbose")h=!0;else if(e==="--ext"||e==="--ignore-path")t++;else if(e==="--fix"||e==="--dry-run"||e==="--reporter"||e==="--max-warnings"||e==="--cache"){w=!1,l.length=0;break}else if(e.startsWith("--"));else l.push(e)}if(w&&(c==="format"||c==="auto"||c==="lint")&&l.length>0){let{runUnified:t}=await import("../chunk-nh6zvh3d.js"),e=await t(l,{mode:c,check:u,write:d,verbose:h,config:x});process.exit(e)}let{CLI:b}=await import("../chunk-hwa8gmzb.js"),{version:y}=await import("../chunk-b2q8x0sx.js"),r=new b("pickier"),f=(t)=>{let[e,o]=t;return[Array.isArray(e)?e.filter((m)=>typeof m==="string"):[],o&&typeof o==="object"?o:{}]};r.command("[...globs]","Lint files (default)").option("--fix","Auto-fix lint problems").option("--format","Format files instead of linting").option("--dry-run","Simulate fixes without writing").option("--check","Check formatting without writing (CI-friendly)").option("--max-warnings <n>","Max warnings before non-zero exit",{default:-1}).option("--reporter <name>","stylish|json|compact",{default:"stylish"}).option("--config <path>","Path to pickier config").option("--ignore-path <file>","Ignore file (like .gitignore)").option("--ext <exts>","Comma-separated extensions").option("--cache","Enable cache").option("--verbose","Verbose output").example("pickier .").example("pickier . --fix").example("pickier . --format").example("pickier src --fix --verbose").action(async(...t)=>{let[e,o]=f(t);if(e.length===0){r.outputHelp();return}let{runUnified:s}=await import("../chunk-nh6zvh3d.js"),i;if(o.format){if(i="format",!o.check)o.write=!0}else i="lint";let m=await s(e,{...o,mode:i});process.exit(m)}),r.command("lint [...globs]","[DEPRECATION] Use `pickier [...globs]` instead. Lint files").option("--fix","Auto-fix problems").option("--dry-run","Simulate fixes without writing").option("--max-warnings <n>","Max warnings before non-zero exit",{default:-1}).option("--reporter <name>","stylish|json|compact",{default:"stylish"}).option("--config <path>","Path to pickier config").option("--ignore-path <file>","Ignore file (like .gitignore)").option("--ext <exts>","Comma-separated extensions").option("--cache","Enable cache").option("--verbose","Verbose output").example("pickier lint .").example("pickier lint src --fix").example('pickier lint "src/**/*.{ts,tsx}" --reporter json').action(async(...t)=>{let[e,o]=f(t),{runUnified:s}=await import("../chunk-nh6zvh3d.js"),i=await s(e,{...o,mode:"lint"});process.exit(i)}),r.command("format [...globs]","[DEPRECATION] Use `pickier [...globs] --format` instead. Format files").option("--write","Write changes to files").option("--check","Check without writing (CI-friendly)").option("--config <path>","Path to pickier config").option("--ignore-path <file>","Ignore file").option("--ext <exts>","Comma-separated extensions").option("--verbose","Verbose output").example("pickier format . --write").example("pickier format . --check").action(async(...t)=>{let[e,o]=f(t),{runUnified:s}=await import("../chunk-nh6zvh3d.js"),i=await s(e,{...o,mode:"format"});process.exit(i)}),r.command("run [...globs]","Unified mode (auto, lint, or format)").option("--mode <mode>","auto|lint|format",{default:"auto"}).option("--fix","Auto-fix problems (lint mode)").option("--dry-run","Simulate fixes without writing (lint mode)").option("--max-warnings <n>","Max warnings before non-zero exit (lint mode)",{default:-1}).option("--reporter <name>","stylish|json|compact (lint mode)",{default:"stylish"}).option("--write","Write changes to files (format mode)").option("--check","Check without writing (format mode)").option("--config <path>","Path to pickier config").option("--ignore-path <file>","Ignore file (like .gitignore)").option("--ext <exts>","Comma-separated extensions").option("--cache","Enable cache (lint mode)").option("--verbose","Verbose output").example("pickier run . --mode lint --fix").example("pickier run . --mode format --write").action(async(...t)=>{let[e,o]=f(t),{runUnified:s}=await import("../chunk-nh6zvh3d.js"),i=await s(e,o);process.exit(i)}),r.command("version","Show the version of the CLI").action(async()=>{let{version:t}=await import("../chunk-b2q8x0sx.js");process.stdout.write(`${t}
|
|
4
4
|
`)}),r.version(y),r.help(),r.parse()}v().catch((n)=>{let p=n instanceof Error?n.message:String(n);process.stderr.write(`pickier: ${p}
|
|
5
5
|
`),process.exit(1)});
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{N as q}from"./chunk-cfytsdab.js";import{existsSync as Gt,statSync as Yt}from"fs";import{existsSync as vn,mkdirSync as Oi,readdirSync as Ri,readFileSync as $n,writeFileSync as Ni}from"fs";import{homedir as ne}from"os";import{dirname as Mi,resolve as B}from"path";import et from"process";import{existsSync as Ht,statSync as Zt}from"fs";import{existsSync as xt,mkdirSync as bn,readdirSync as Cn,writeFileSync as En}from"fs";import{homedir as se}from"os";import{dirname as Xt,resolve as j}from"path";import re from"process";import{join as xn,relative as kn,resolve as Qt}from"path";import Ke from"process";import{existsSync as jr,mkdirSync as Ui,readdirSync as qi,writeFileSync as Ji}from"fs";import{homedir as st}from"os";import{dirname as Hi,resolve as M}from"path";import ye from"process";import{join as Sn,relative as Tn,resolve as er}from"path";import Ve from"process";import{existsSync as Lr,mkdirSync as to,readdirSync as ro,writeFileSync as no}from"fs";import{dirname as io,resolve as We}from"path";import kt from"process";import{Buffer as ee}from"buffer";import{createCipheriv as An,createDecipheriv as Fn,randomBytes as it}from"crypto";import{closeSync as ot,createReadStream as tr,createWriteStream as On,existsSync as at,fsyncSync as rr,openSync as nr,writeFileSync as Rn}from"fs";import{access as Nn,constants as sr,mkdir as Pn,readdir as be,rename as ir,stat as ie,unlink as Ce,writeFile as ct}from"fs/promises";import{join as oe}from"path";import O from"process";import{pipeline as Dn}from"stream/promises";import{createGzip as or}from"zlib";import ae from"process";import H from"process";import{Buffer as G}from"buffer";import{createCipheriv as Mn,createDecipheriv as jn,randomBytes as lt}from"crypto";import{closeSync as ft,createReadStream as ar,createWriteStream as Ln,existsSync as Ee,fsyncSync as cr,openSync as lr,writeFileSync as Bn}from"fs";import{access as In,constants as fr,mkdir as _n,readdir as xe,rename as ur,stat as ce,unlink as ke,writeFile as ut}from"fs/promises";import{isAbsolute as Kn,join as le,resolve as Vn}from"path";import d from"process";import{pipeline as Wn}from"stream/promises";import{createGzip as gr}from"zlib";import fe from"process";import Z from"process";import Se from"process";import{existsSync as Te}from"fs";import{resolve as gt}from"path";import{existsSync as zn}from"fs";import{existsSync as Un,readdirSync as qn}from"fs";import{extname as ht,resolve as hr}from"path";import Jn from"process";import{join as Gn,relative as Yn,resolve as mr}from"path";import ze from"process";import{Buffer as Y}from"buffer";import{createCipheriv as Hn,createDecipheriv as Zn,randomBytes as mt}from"crypto";import{closeSync as dt,createReadStream as dr,createWriteStream as Xn,existsSync as Ae,fsyncSync as pr,openSync as yr,writeFileSync as Qn}from"fs";import{access as es,constants as wr,mkdir as ts,readdir as Fe,rename as vr,stat as ue,unlink as Oe,writeFile as pt}from"fs/promises";import{isAbsolute as rs,join as ge,resolve as ns}from"path";import p from"process";import{pipeline as ss}from"stream/promises";import{createGzip as $r}from"zlib";import he from"process";import X from"process";import Ne from"process";import{existsSync as Pe}from"fs";import{resolve as Ct}from"path";import{existsSync as xi}from"fs";class Dr{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],[,n])=>r.timestamp.getTime()-n.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,n){if(!this.options.enabled)return;let s=this.generateKey(e,r),i=n??this.options.ttl,o=this.estimateSize(t);this.cache.set(s,{value:t,timestamp:new Date,ttl:i,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!Gt(e))return!0;return Yt(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,n){try{let s=Gt(r)?Yt(r):null,i=s?s.mtime:new Date;this.set(e,{value:t,fileTimestamp:i},r,n)}catch{this.set(e,t,r,n)}}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((n,s)=>n+s.size,0),r=e.map((n)=>n.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 n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Mr{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),s=new Date;try{let i=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:s,...r}),i}catch(i){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:s,...r}),i}}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((s)=>s.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((s)=>s.duration),n=r.reduce((s,i)=>s+i,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}var _e=new Dr,jt=new Mr;var is=Object.defineProperty,os=(e)=>e;function as(e,t){this[e]=os.bind(null,t)}var cs=(e,t)=>{for(var r in t)is(e,r,{get:t[r],enumerable:!0,configurable:!0,set:as.bind(t,r)})},ls=(e,t)=>()=>(e&&(t=e(e=0)),t),Br={};cs(Br,{withErrorRecovery:()=>Kr,tryLoadConfig:()=>Ns,loadConfigWithResult:()=>Os,loadConfig:()=>qr,isRetryableError:()=>xs,isConfigNotFoundError:()=>Es,isBunfigError:()=>Vr,globalPerformanceMonitor:()=>$e,globalCache:()=>me,getEnvOrDefault:()=>ks,generateConfigTypes:()=>Ps,defaultGeneratedDir:()=>en,defaultConfigDir:()=>Qr,deepMergeWithArrayStrategy:()=>Kt,deepMerge:()=>Wr,createLibraryConfig:()=>Ds,config:()=>Rs,bunfigPlugin:()=>Ms,applyEnvVarsToConfig:()=>pe,TypeGenerationError:()=>Nt,SchemaValidationError:()=>ve,PluginError:()=>Dt,PerformanceMonitor:()=>Bt,FileSystemError:()=>Rt,ErrorFactory:()=>te,EnvVarError:()=>He,EnvProcessor:()=>tt,ConfigValidator:()=>Vt,ConfigValidationError:()=>Ft,ConfigNotFoundError:()=>Ye,ConfigMergeError:()=>Ot,ConfigLoader:()=>Wt,ConfigLoadError:()=>we,ConfigFileLoader:()=>rt,ConfigCache:()=>Lt,CacheUtils:()=>Gr,BunfigError:()=>L,BrowserConfigError:()=>Pt,ArrayMergeStrategies:()=>Zr});class Lt{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],[,n])=>r.timestamp.getTime()-n.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,n){if(!this.options.enabled)return;let s=this.generateKey(e,r),i=n??this.options.ttl,o=this.estimateSize(t);this.cache.set(s,{value:t,timestamp:new Date,ttl:i,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!Ht(e))return!0;return Zt(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,n){try{let s=Ht(r)?Zt(r):null,i=s?s.mtime:new Date;this.set(e,{value:t,fileTimestamp:i},r,n)}catch{this.set(e,t,r,n)}}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((n,s)=>n+s.size,0),r=e.map((n)=>n.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 n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Bt{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),s=new Date;try{let i=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:s,...r}),i}catch(i){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:s,...r}),i}}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((s)=>s.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((s)=>s.duration),n=r.reduce((s,i)=>s+i,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function fs(e,t={}){let n=Object.keys(t).sort().map((s)=>`${s}:${t[s]}`).join("|");return n?`${e}:${n}`:e}function us(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function gs(e){return e.getStats().size*2}function It(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&x(t[0])&&"id"in t[0]&&t[0].id===3&&x(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(x(t)&&x(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(x(e)&&"arr"in e&&Array.isArray(e.arr)&&x(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&x(t[0])&&x(e[0])){let n=[...t];for(let s of e)if(x(s)&&"name"in s){if(!n.find((o)=>x(o)&&("name"in o)&&o.name===s.name))n.push(s)}else if(x(s)&&"path"in s){if(!n.find((o)=>x(o)&&("path"in o)&&o.path===s.path))n.push(s)}else if(!n.some((i)=>Ue(i,s)))n.push(s);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let s of e)if(!n.includes(s))n.push(s);return n}return t}if(!x(t)||!x(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let s=t[n];if(s===null||s===void 0)continue;else if(x(s)&&x(r[n]))r[n]=It(r[n],s);else if(Array.isArray(s)&&Array.isArray(r[n]))if(s.length>0&&r[n].length>0&&x(s[0])&&x(r[n][0])){let i=[...s];for(let o of r[n])if(x(o)&&"name"in o){if(!i.find((a)=>x(a)&&("name"in a)&&a.name===o.name))i.push(o)}else if(x(o)&&"path"in o){if(!i.find((a)=>x(a)&&("path"in a)&&a.path===o.path))i.push(o)}else if(!i.some((c)=>Ue(c,o)))i.push(o);r[n]=i}else if(s.every((i)=>typeof i==="string")&&r[n].every((i)=>typeof i==="string")){let i=[...s];for(let o of r[n])if(!i.includes(o))i.push(o);r[n]=i}else r[n]=s;else r[n]=s}return r}function Ue(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(!Ue(e[r],t[r]))return!1;return!0}if(x(e)&&x(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(t,s))return!1;if(!Ue(e[s],t[s]))return!1}return!0}return!1}function x(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function hs(e,t){if(!Lr(e))return null;try{let r=await import(e),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return It(t,n)}catch{return null}}catch{return null}}async function ms({name:e="",cwd:t,defaultConfig:r}){let n=t||kt.cwd(),s=[".ts",".js",".mjs",".cjs",".json"],i=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of i)for(let c of s){let a=We(n,`${o}${c}`),l=await hs(a,r);if(l!==null)return l}try{let o=We(n,"package.json");if(Lr(o)){let a=(await import(o))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return It(r,a)}catch{}}}catch{}return r}function ds(e,t={}){let r=Ve.cwd();while(r.includes("storage"))r=er(r,"..");let n=er(r,e||"");if(t?.relative)return Tn(Ve.cwd(),n);return n}async function ps(){try{let e=await ms({name:"clarity",defaultConfig:je,cwd:Ve.cwd(),endpoint:"",headers:{}});return{...je,...e}}catch{return je}}function k(){if(H.env.NODE_ENV==="test"||H.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ys(){if(H.env.NODE_ENV==="test"||H.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof H<"u"){let e=H.type;if(e==="renderer"||e==="worker")return!1;return!!(H.versions&&(H.versions.node||H.versions.bun))}return!1}class Ir{async format(e){let t=await ys(),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:ae.pid,hostname:t(),environment:ae.env.NODE_ENV||"development",platform:ae.platform,version:ae.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ae.env.NODE_ENV||ae.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class qe{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...Tt},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ir,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??O.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let s=this.generateKeyId(),i=this.generateKey();this.currentKeyId=s,this.keys.set(s,i),this.encryptionKeys.set(s,{key:i,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Le,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Le};return{...Le,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Tt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let s,i=0,o=3,c=1000;while(i<o)try{try{try{await Nn(this.config.logDirectory,sr.F_OK|sr.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Pn(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:ee.from(e);try{if(!at(this.currentLogFile))await ct(this.currentLogFile,"",{mode:420});if(s=nr(this.currentLogFile,"a",420),Rn(s,a,{flag:"a"}),rr(s),s!==void 0)ot(s),s=void 0;if((await ie(this.currentLogFile)).size===0){if(await ct(this.currentLogFile,a,{flag:"w",mode:420}),(await ie(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(i<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${o}:`,u);let h=c*2**i;await new Promise((g)=>setTimeout(g,h)),i++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(s!==void 0)try{ot(s)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(i===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}i++;let l=c*2**(i-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(s){throw console.error("Debug: [writeToFile] Error in operation:",s),s}finally{this.pendingOperations.splice(n,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 oe(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 oe(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return oe(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(k())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 t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((s)=>{console.error("Error rotating keys:",s)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let s=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),i=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,i);if(s.length>o)for(let[c]of s.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return it(16).toString("hex")}generateKey(){return it(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=it(16),n=An("aes-256-gcm",t,r),s=ee.concat([n.update(e,"utf8"),n.final()]),i=n.getAuthTag();return{encrypted:ee.concat([r,s,i]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=or(),s=[];n.on("data",(i)=>s.push(i)),n.on("end",()=>t(ee.from(ee.concat(s)))),n.on("error",r),n.write(e),n.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(k())return;let e=await ie(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,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let s=await be(this.config.logDirectory),i=s.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let f=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=i.length>0?Number.parseInt(i[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await ie(r).catch(()=>null))try{if(await ir(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Ce(c)}catch(a){console.error("Error compressing rotated file:",a)}if(i.length===0&&!s.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await ct(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let s=new Date().toISOString().replace(/[:.]/g,"-"),i=r.replace(/\.log$/,`-${s}.log`);if(await ie(r).catch(()=>null))await ir(r,i)}if(this.currentLogFile=n,t.maxFiles){let i=(await be(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of i.slice(t.maxFiles))await Ce(oe(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=tr(e),n=On(t),s=or();await Dn(r,s,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}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()})),at(this.currentLogFile))try{let e=nr(this.currentLogFile,"r+");rr(e),ot(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(!k()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await be(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Ce(oe(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}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.fancy?E.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:s,level:i,showTimestamp:o=!0}=e,c=(g)=>g.replace(this.ANSI_PATTERN,"");if(!this.fancy){let g=[];if(o)g.push(t);if(i==="warning")g.push("WARN");else if(i==="error")g.push("ERROR");else if(r)g.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)g.push(n.replace(/[[\]]/g,""));return g.push(s),g.join(" ")}let a=O.stdout.columns||120,l="";if(i==="warning"||i==="error")l=`${r} ${s}`;else if(i==="info"||i==="success")l=`${r} ${n} ${s}`;else l=`${r} ${n} ${E.cyan(s)}`;if(!o)return l.trim();let f=c(l).trim().length,u=c(t).length,h=Math.max(1,a-2-f-u);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(i,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):i});let r=/%([sdijfo%])/g,n=0,s=e.replace(r,(i,o)=>{if(o==="%")return"%";if(n>=t.length)return i;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return i}});if(n<t.length)s+=` ${t.slice(n).map((i)=>typeof i==="object"?JSON.stringify(i,null,2):String(i)).join(" ")}`;return s}async log(e,t,...r){let n=new Date,s=this.formatConsoleTimestamp(n),i=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!k()){let l=Yr[e],f=this.options.showTags!==!1&&this.name?E.gray(this.formatTag(this.name)):"",u;switch(e){case"debug":u=this.formatConsoleMessage({timestamp:s,icon:l,tag:f,message:E.gray(o),level:e}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:s,icon:l,tag:f,message:o,level:e}),console.error(u);break;case"success":u=this.formatConsoleMessage({timestamp:s,icon:l,tag:f,message:E.green(o),level:e}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:s,icon:l,tag:f,message:o,level:e}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:s,icon:l,tag:f,message:o,level:e}),console.error(u),c){let h=c.split(`
|
|
2
|
+
import{Q as q}from"./chunk-awmb5sg5.js";import{existsSync as Gt,statSync as Yt}from"fs";import{existsSync as vn,mkdirSync as Oi,readdirSync as Ri,readFileSync as $n,writeFileSync as Ni}from"fs";import{homedir as ne}from"os";import{dirname as Mi,resolve as B}from"path";import et from"process";import{existsSync as Ht,statSync as Zt}from"fs";import{existsSync as xt,mkdirSync as bn,readdirSync as Cn,writeFileSync as En}from"fs";import{homedir as se}from"os";import{dirname as Xt,resolve as j}from"path";import re from"process";import{join as xn,relative as kn,resolve as Qt}from"path";import Ke from"process";import{existsSync as jr,mkdirSync as Ui,readdirSync as qi,writeFileSync as Ji}from"fs";import{homedir as st}from"os";import{dirname as Hi,resolve as M}from"path";import ye from"process";import{join as Sn,relative as Tn,resolve as er}from"path";import Ve from"process";import{existsSync as Lr,mkdirSync as to,readdirSync as ro,writeFileSync as no}from"fs";import{dirname as io,resolve as We}from"path";import kt from"process";import{Buffer as ee}from"buffer";import{createCipheriv as An,createDecipheriv as Fn,randomBytes as it}from"crypto";import{closeSync as ot,createReadStream as tr,createWriteStream as On,existsSync as at,fsyncSync as rr,openSync as nr,writeFileSync as Rn}from"fs";import{access as Nn,constants as sr,mkdir as Pn,readdir as be,rename as ir,stat as ie,unlink as Ce,writeFile as ct}from"fs/promises";import{join as oe}from"path";import O from"process";import{pipeline as Dn}from"stream/promises";import{createGzip as or}from"zlib";import ae from"process";import H from"process";import{Buffer as G}from"buffer";import{createCipheriv as Mn,createDecipheriv as jn,randomBytes as lt}from"crypto";import{closeSync as ft,createReadStream as ar,createWriteStream as Ln,existsSync as Ee,fsyncSync as cr,openSync as lr,writeFileSync as Bn}from"fs";import{access as In,constants as fr,mkdir as _n,readdir as xe,rename as ur,stat as ce,unlink as ke,writeFile as ut}from"fs/promises";import{isAbsolute as Kn,join as le,resolve as Vn}from"path";import d from"process";import{pipeline as Wn}from"stream/promises";import{createGzip as gr}from"zlib";import fe from"process";import Z from"process";import Se from"process";import{existsSync as Te}from"fs";import{resolve as gt}from"path";import{existsSync as zn}from"fs";import{existsSync as Un,readdirSync as qn}from"fs";import{extname as ht,resolve as hr}from"path";import Jn from"process";import{join as Gn,relative as Yn,resolve as mr}from"path";import ze from"process";import{Buffer as Y}from"buffer";import{createCipheriv as Hn,createDecipheriv as Zn,randomBytes as mt}from"crypto";import{closeSync as dt,createReadStream as dr,createWriteStream as Xn,existsSync as Ae,fsyncSync as pr,openSync as yr,writeFileSync as Qn}from"fs";import{access as es,constants as wr,mkdir as ts,readdir as Fe,rename as vr,stat as ue,unlink as Oe,writeFile as pt}from"fs/promises";import{isAbsolute as rs,join as ge,resolve as ns}from"path";import p from"process";import{pipeline as ss}from"stream/promises";import{createGzip as $r}from"zlib";import he from"process";import X from"process";import Ne from"process";import{existsSync as Pe}from"fs";import{resolve as Ct}from"path";import{existsSync as xi}from"fs";class Dr{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],[,n])=>r.timestamp.getTime()-n.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,n){if(!this.options.enabled)return;let s=this.generateKey(e,r),i=n??this.options.ttl,o=this.estimateSize(t);this.cache.set(s,{value:t,timestamp:new Date,ttl:i,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!Gt(e))return!0;return Yt(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,n){try{let s=Gt(r)?Yt(r):null,i=s?s.mtime:new Date;this.set(e,{value:t,fileTimestamp:i},r,n)}catch{this.set(e,t,r,n)}}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((n,s)=>n+s.size,0),r=e.map((n)=>n.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 n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Mr{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),s=new Date;try{let i=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:s,...r}),i}catch(i){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:s,...r}),i}}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((s)=>s.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((s)=>s.duration),n=r.reduce((s,i)=>s+i,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}var _e=new Dr,jt=new Mr;var is=Object.defineProperty,os=(e)=>e;function as(e,t){this[e]=os.bind(null,t)}var cs=(e,t)=>{for(var r in t)is(e,r,{get:t[r],enumerable:!0,configurable:!0,set:as.bind(t,r)})},ls=(e,t)=>()=>(e&&(t=e(e=0)),t),Br={};cs(Br,{withErrorRecovery:()=>Kr,tryLoadConfig:()=>Ns,loadConfigWithResult:()=>Os,loadConfig:()=>qr,isRetryableError:()=>xs,isConfigNotFoundError:()=>Es,isBunfigError:()=>Vr,globalPerformanceMonitor:()=>$e,globalCache:()=>me,getEnvOrDefault:()=>ks,generateConfigTypes:()=>Ps,defaultGeneratedDir:()=>en,defaultConfigDir:()=>Qr,deepMergeWithArrayStrategy:()=>Kt,deepMerge:()=>Wr,createLibraryConfig:()=>Ds,config:()=>Rs,bunfigPlugin:()=>Ms,applyEnvVarsToConfig:()=>pe,TypeGenerationError:()=>Nt,SchemaValidationError:()=>ve,PluginError:()=>Dt,PerformanceMonitor:()=>Bt,FileSystemError:()=>Rt,ErrorFactory:()=>te,EnvVarError:()=>He,EnvProcessor:()=>tt,ConfigValidator:()=>Vt,ConfigValidationError:()=>Ft,ConfigNotFoundError:()=>Ye,ConfigMergeError:()=>Ot,ConfigLoader:()=>Wt,ConfigLoadError:()=>we,ConfigFileLoader:()=>rt,ConfigCache:()=>Lt,CacheUtils:()=>Gr,BunfigError:()=>L,BrowserConfigError:()=>Pt,ArrayMergeStrategies:()=>Zr});class Lt{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],[,n])=>r.timestamp.getTime()-n.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,n){if(!this.options.enabled)return;let s=this.generateKey(e,r),i=n??this.options.ttl,o=this.estimateSize(t);this.cache.set(s,{value:t,timestamp:new Date,ttl:i,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!Ht(e))return!0;return Zt(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,n){try{let s=Ht(r)?Zt(r):null,i=s?s.mtime:new Date;this.set(e,{value:t,fileTimestamp:i},r,n)}catch{this.set(e,t,r,n)}}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((n,s)=>n+s.size,0),r=e.map((n)=>n.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 n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Bt{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),s=new Date;try{let i=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:s,...r}),i}catch(i){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:s,...r}),i}}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((s)=>s.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((s)=>s.duration),n=r.reduce((s,i)=>s+i,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function fs(e,t={}){let n=Object.keys(t).sort().map((s)=>`${s}:${t[s]}`).join("|");return n?`${e}:${n}`:e}function us(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function gs(e){return e.getStats().size*2}function It(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&x(t[0])&&"id"in t[0]&&t[0].id===3&&x(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(x(t)&&x(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(x(e)&&"arr"in e&&Array.isArray(e.arr)&&x(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&x(t[0])&&x(e[0])){let n=[...t];for(let s of e)if(x(s)&&"name"in s){if(!n.find((o)=>x(o)&&("name"in o)&&o.name===s.name))n.push(s)}else if(x(s)&&"path"in s){if(!n.find((o)=>x(o)&&("path"in o)&&o.path===s.path))n.push(s)}else if(!n.some((i)=>Ue(i,s)))n.push(s);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let s of e)if(!n.includes(s))n.push(s);return n}return t}if(!x(t)||!x(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let s=t[n];if(s===null||s===void 0)continue;else if(x(s)&&x(r[n]))r[n]=It(r[n],s);else if(Array.isArray(s)&&Array.isArray(r[n]))if(s.length>0&&r[n].length>0&&x(s[0])&&x(r[n][0])){let i=[...s];for(let o of r[n])if(x(o)&&"name"in o){if(!i.find((a)=>x(a)&&("name"in a)&&a.name===o.name))i.push(o)}else if(x(o)&&"path"in o){if(!i.find((a)=>x(a)&&("path"in a)&&a.path===o.path))i.push(o)}else if(!i.some((c)=>Ue(c,o)))i.push(o);r[n]=i}else if(s.every((i)=>typeof i==="string")&&r[n].every((i)=>typeof i==="string")){let i=[...s];for(let o of r[n])if(!i.includes(o))i.push(o);r[n]=i}else r[n]=s;else r[n]=s}return r}function Ue(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(!Ue(e[r],t[r]))return!1;return!0}if(x(e)&&x(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(t,s))return!1;if(!Ue(e[s],t[s]))return!1}return!0}return!1}function x(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function hs(e,t){if(!Lr(e))return null;try{let r=await import(e),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return It(t,n)}catch{return null}}catch{return null}}async function ms({name:e="",cwd:t,defaultConfig:r}){let n=t||kt.cwd(),s=[".ts",".js",".mjs",".cjs",".json"],i=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of i)for(let c of s){let a=We(n,`${o}${c}`),l=await hs(a,r);if(l!==null)return l}try{let o=We(n,"package.json");if(Lr(o)){let a=(await import(o))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return It(r,a)}catch{}}}catch{}return r}function ds(e,t={}){let r=Ve.cwd();while(r.includes("storage"))r=er(r,"..");let n=er(r,e||"");if(t?.relative)return Tn(Ve.cwd(),n);return n}async function ps(){try{let e=await ms({name:"clarity",defaultConfig:je,cwd:Ve.cwd(),endpoint:"",headers:{}});return{...je,...e}}catch{return je}}function k(){if(H.env.NODE_ENV==="test"||H.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ys(){if(H.env.NODE_ENV==="test"||H.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof H<"u"){let e=H.type;if(e==="renderer"||e==="worker")return!1;return!!(H.versions&&(H.versions.node||H.versions.bun))}return!1}class Ir{async format(e){let t=await ys(),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:ae.pid,hostname:t(),environment:ae.env.NODE_ENV||"development",platform:ae.platform,version:ae.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ae.env.NODE_ENV||ae.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class qe{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...Tt},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ir,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??O.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let s=this.generateKeyId(),i=this.generateKey();this.currentKeyId=s,this.keys.set(s,i),this.encryptionKeys.set(s,{key:i,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Le,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Le};return{...Le,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Tt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let s,i=0,o=3,c=1000;while(i<o)try{try{try{await Nn(this.config.logDirectory,sr.F_OK|sr.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Pn(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:ee.from(e);try{if(!at(this.currentLogFile))await ct(this.currentLogFile,"",{mode:420});if(s=nr(this.currentLogFile,"a",420),Rn(s,a,{flag:"a"}),rr(s),s!==void 0)ot(s),s=void 0;if((await ie(this.currentLogFile)).size===0){if(await ct(this.currentLogFile,a,{flag:"w",mode:420}),(await ie(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(i<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${o}:`,u);let h=c*2**i;await new Promise((g)=>setTimeout(g,h)),i++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(s!==void 0)try{ot(s)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(i===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}i++;let l=c*2**(i-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(s){throw console.error("Debug: [writeToFile] Error in operation:",s),s}finally{this.pendingOperations.splice(n,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 oe(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 oe(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return oe(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(k())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 t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((s)=>{console.error("Error rotating keys:",s)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let s=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),i=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,i);if(s.length>o)for(let[c]of s.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return it(16).toString("hex")}generateKey(){return it(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=it(16),n=An("aes-256-gcm",t,r),s=ee.concat([n.update(e,"utf8"),n.final()]),i=n.getAuthTag();return{encrypted:ee.concat([r,s,i]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=or(),s=[];n.on("data",(i)=>s.push(i)),n.on("end",()=>t(ee.from(ee.concat(s)))),n.on("error",r),n.write(e),n.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(k())return;let e=await ie(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,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let s=await be(this.config.logDirectory),i=s.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let f=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=i.length>0?Number.parseInt(i[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await ie(r).catch(()=>null))try{if(await ir(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Ce(c)}catch(a){console.error("Error compressing rotated file:",a)}if(i.length===0&&!s.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await ct(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let s=new Date().toISOString().replace(/[:.]/g,"-"),i=r.replace(/\.log$/,`-${s}.log`);if(await ie(r).catch(()=>null))await ir(r,i)}if(this.currentLogFile=n,t.maxFiles){let i=(await be(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of i.slice(t.maxFiles))await Ce(oe(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=tr(e),n=On(t),s=or();await Dn(r,s,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}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()})),at(this.currentLogFile))try{let e=nr(this.currentLogFile,"r+");rr(e),ot(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(!k()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await be(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Ce(oe(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}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.fancy?E.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:s,level:i,showTimestamp:o=!0}=e,c=(g)=>g.replace(this.ANSI_PATTERN,"");if(!this.fancy){let g=[];if(o)g.push(t);if(i==="warning")g.push("WARN");else if(i==="error")g.push("ERROR");else if(r)g.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)g.push(n.replace(/[[\]]/g,""));return g.push(s),g.join(" ")}let a=O.stdout.columns||120,l="";if(i==="warning"||i==="error")l=`${r} ${s}`;else if(i==="info"||i==="success")l=`${r} ${n} ${s}`;else l=`${r} ${n} ${E.cyan(s)}`;if(!o)return l.trim();let f=c(l).trim().length,u=c(t).length,h=Math.max(1,a-2-f-u);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(i,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):i});let r=/%([sdijfo%])/g,n=0,s=e.replace(r,(i,o)=>{if(o==="%")return"%";if(n>=t.length)return i;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return i}});if(n<t.length)s+=` ${t.slice(n).map((i)=>typeof i==="object"?JSON.stringify(i,null,2):String(i)).join(" ")}`;return s}async log(e,t,...r){let n=new Date,s=this.formatConsoleTimestamp(n),i=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!k()){let l=Yr[e],f=this.options.showTags!==!1&&this.name?E.gray(this.formatTag(this.name)):"",u;switch(e){case"debug":u=this.formatConsoleMessage({timestamp:s,icon:l,tag:f,message:E.gray(o),level:e}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:s,icon:l,tag:f,message:o,level:e}),console.error(u);break;case"success":u=this.formatConsoleMessage({timestamp:s,icon:l,tag:f,message:E.green(o),level:e}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:s,icon:l,tag:f,message:o,level:e}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:s,icon:l,tag:f,message:o,level:e}),console.error(u),c){let h=c.split(`
|
|
3
3
|
`);for(let g of h)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:s,message:E.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!k()){if(console.error(`${i} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let a=`${i} ${this.environment}.${e.toUpperCase()}: ${o}
|
|
4
4
|
`;if(c)a+=`${c}
|
|
5
5
|
`;a=a.replace(this.ANSI_PATTERN,""),await this.writeToFile(a)}time(e){let t=performance.now();if(this.fancy&&!k()){let r=this.options.showTags!==!1&&this.name?E.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:E.blue("\u25D0"),tag:r,message:`${E.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),s=Math.round(n-t),i=`${e} completed in ${s}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${i}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
@@ -59,4 +59,4 @@ export type ConfigOf = Config
|
|
|
59
59
|
`,r+=`|----------|------|-------------|----------|
|
|
60
60
|
`;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
61
61
|
`;return r}}function vi(e,t,r={}){return un(e,t,r,new WeakMap)}function un(e,t,r,n){let{arrayMergeMode:s="replace",skipNullish:i=!1,customMerger:o}=r;if(t===null||t===void 0)return i?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return gn(e,t,s,n);if(!_(t)||!_(e))return t;return Ei(e,t,r,n)}function gn(e,t,r,n){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 $i(e,t);case"smart":return bi(e,t,n);default:return t}return t}function $i(e,t){let r=[...t];for(let n of e)if(!r.some((s)=>Mt(s,n)))r.push(n);return r}function bi(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(_(t[0])&&_(e[0]))return Ci(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let s of e)if(!n.includes(s))n.push(s);return n}return t}function Ci(e,t,r){let n=[...t];for(let s of e){if(!_(s)){n.push(s);continue}let i=["id","name","key","path","type"],o=!1;for(let c of i)if(c in s){if(n.find((l)=>_(l)&&(c in l)&&l[c]===s[c])){o=!0;break}}if(!o)n.push(s)}return n}function Ei(e,t,r,n){let s=t;if(_(s)&&n.has(s))return n.get(s);let i={...e};if(_(s))n.set(s,i);for(let o in s){if(!Object.prototype.hasOwnProperty.call(s,o))continue;let c=s[o],a=i[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){i[o]=c;continue}if(_(c)&&_(a))i[o]=un(a,c,r,n);else if(Array.isArray(c)||Array.isArray(a))i[o]=gn(a,c,r.arrayMergeMode||"smart",n);else i[o]=c}return i}function hn(e,t,r="replace"){return vi(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Mt(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(!Mt(e[r],t[r]))return!1;return!0}if(_(e)&&_(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(t,s))return!1;if(!Mt(e[s],t[s]))return!1}return!0}return!1}function _(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class mn{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:s=!0,cacheTtl:i,trackPerformance:o=!0,verbose:c=!1}=r;if(s){let l=_e.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!Pe(e))return null;try{let l=`?t=${Date.now()}`,f=await import(e+l),u=f.default||f,h="default"in f,g=Object.keys(f).length>0;if(!h&&!g)throw new Xe(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new Xe(e,Error("Configuration must export a valid object"),"unknown");let w={config:hn(t,u,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(s)_e.setWithFileCheck("file",w,e,i);return w}catch(l){throw l instanceof Error?de.configLoad(e,l):de.configLoad(e,Error(String(l)))}};if(o)return jt.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let s=await this.loadFromPath(n,t,r);if(s)return s}catch(s){if(s instanceof Error&&s.name==="ConfigLoadError")throw s;if(r.verbose)console.warn(`Failed to load config from ${n}:`,s)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),s=[];for(let i of n)for(let o of this.extensions)s.push(Ct(t,`${i}${o}`));return s}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let n=t===void 0?[]:Array.isArray(t)?t:[t];for(let i of n){if(!i)continue;if(r.push(i,`.${i}.config`,`${i}.config`,`.${i}`),e)r.push(`${e}.${i}.config`,`.${e}.${i}.config`)}let s=new Set;return r.filter((i)=>{if(!i||s.has(i))return!1;return s.add(i),!0})}checkFileAccess(e){return wi(async()=>Pe(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!Pe(e))return n;if(t||r){let s=this.generateNamePatterns(t||"",r);for(let i of s)for(let o of this.extensions){let c=Ct(e,`${i}${o}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:s}=await import("fs"),i=s(e);for(let o of i)if(this.looksLikeConfigFile(o)){let c=Ct(e,o);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}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((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!Pe(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:s}=await import("fs"),i=s(e,"utf8");JSON.parse(i)}catch(s){t.push(`Invalid JSON syntax: ${s}`)}}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(n)=>{try{let s=await this.loadFromPath(n,{},t);if(s)r.set(n,s.config)}catch(s){if(t.verbose)console.warn(`Failed to preload ${n}:`,s)}})),r}}var ki=/^https?:\/\//;class dn{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:s=!0,validateTypes:i=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let f=[],u=[],h={stopOnFirstError:n,validateRequired:s,validateTypes:i,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(g){return f.push({path:"",message:`Validation failed: ${g}`,rule:"system"}),{isValid:!1,errors:f,warnings:u}}};if(c)return await jt.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!xi(t))throw new Qe(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),s=n.default||n;if(Array.isArray(s))return this.validateWithRules(e,s,r);else return this.validateWithJSONSchema(e,s,r)}catch(n){throw new Qe(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],s=[];return this.validateObjectAgainstSchema(e,t,"",n,s,r),{isValid:n.length===0,errors:n,warnings:s}}validateObjectAgainstSchema(e,t,r,n,s,i){if(i.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),i.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),i.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.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)n.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))n.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)n.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)n.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 c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,n,s,i),i.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(i.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),i.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,n,s,i),i.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))s.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],s=[];for(let i of t)try{let o=this.getValueByPath(e,i.path),c=this.validateWithRule(o,i,i.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(o){n.push({path:i.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:s}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let s=Array.isArray(e)?"array":typeof e;if(s!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${s}`,expected:t.type,actual:s,rule:"type"})}if(t.min!==void 0){let s=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(s<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:s,rule:"min"})}if(t.max!==void 0){let s=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(s>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:s,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.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))n.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 s=t.validator(e);if(s)n.push({path:r,message:t.message||s,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let s of r)if(n&&typeof n==="object"&&s in n)n=n[s];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,s,i,o]=n;t.push({path:s,required:!i,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:ki},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var U=new nt("bunfig",{showTags:!0});function Si(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 pn{fileLoader=new mn;envProcessor=new Ut;validator=new dn;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:s,validate:i,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...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(a instanceof Error&&a.name==="ConfigLoadError"){let f=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),u=!f&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(h||f))throw a;if(u&&(!l||!h))c={...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(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(s||i)await this.validateConfiguration(c.config,s,i,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(n?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(a);if(n.slowThreshold&&a.duration>n.slowThreshold)U.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let a=Date.now()-t;throw U.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:s,cwd:i,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:f=!1}=e,u=i||et.cwd(),h=[],g=await this.loadLocalConfiguration(n,s,u,o,c,l,f,a,r);if(g)return h.push(...this.getLocalSearchPaths(n,s,u,o)),this.finalizeResult(g,h,a,n,f);let b=await this.loadHomeConfiguration(n,s,c,l,f,a);if(b)return h.push(...this.getHomeSearchPaths(n,s)),this.finalizeResult(b,h,a,n,f);let m=await this.loadPackageJsonConfiguration(n,s,u,c,l,f,a);if(m)return h.push(B(u,"package.json")),this.finalizeResult(m,h,a,n,f);if(h.push(...this.getAllSearchPaths(n,s,u,o)),t)throw de.configNotFound(n,h,s);return{...await this.applyEnvironmentVariables(n,c,a,f),warnings:[`No configuration file found for "${n}"${Si(s)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,s,i,o,c,a){let l=c?De(e,s,o):s,f=this.getLocalDirectories(r,n);for(let u of f){if(o)U.info(`Searching for configuration in: ${u}`);let h=this.fileLoader.generateConfigPaths(e,u,t),g=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:i,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(g){if(o)U.success(`Configuration loaded from: ${g.source.path}`);return g}}return null}async loadHomeConfiguration(e,t,r,n,s,i){if(!e)return null;let o=i?De(e,r,s):r,c=[B(ne(),".config",e),B(ne(),".config"),ne()];for(let a of c){if(s)U.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),f=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:n,verbose:s});if(f){if(s)U.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(e,t,r,n,s,i,o){let c=o?De(e,n,i):n;try{let a=B(r,"package.json");if(!vn(a))return null;let l={};try{l=JSON.parse($n(a,"utf8"))}catch(h){if(i)U.warn("Failed to parse package.json:",[h instanceof Error?h:Error(String(h))]);return null}let f=l[e],u=e;if(!f&&t){let h=Array.isArray(t)?t:[t];for(let g of h){if(!g)continue;if(l[g]){f=l[g],u=g;break}}}if(f&&typeof f==="object"&&!Array.isArray(f)){if(i)U.success(`Configuration loaded from package.json: ${u}`);return{config:hn(c,f,s),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(i)U.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:De(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,s){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let s=[];if(r){let i=r(e);if(i)s.push(...i)}if(t){let i=await this.validator.validateConfiguration(e,t);if(!i.isValid)s.push(...i.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(s.length>0)throw de.configValidation(n||"unknown",s,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return _e.get(r)||null}cacheResult(e,t,r,n){let s=this.generateCacheKey(e,n);_e.set(s,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}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,B(e,"config"),B(e,".config"),t?B(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let s=[];return s.push(...this.getLocalSearchPaths(e,t,r,n)),s.push(...this.getHomeSearchPaths(e,t)),s.push(B(r,"package.json")),s}getLocalSearchPaths(e,t,r,n){let s=this.getLocalDirectories(r,n),i=[];for(let o of s)i.push(...this.fileLoader.generateConfigPaths(e,o,t));return i}getHomeSearchPaths(e,t){if(!e)return[];let r=[B(ne(),".config",e),B(ne(),".config"),ne()],n=[];for(let s of r)n.push(...this.fileLoader.generateConfigPaths(e,s,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}var Et=new pn;async function yn(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 n;if(r)n=await Et.loadConfig(e);else n=await Et.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let s=n instanceof Error?n.name:"UnknownError",i=n instanceof Error?n.message:String(n);if(!(s==="ConfigNotFoundError"||s==="ConfigLoadError"||s==="ConfigValidationError"||i.includes("config"))&&e.verbose)U.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await Et.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}function De(e,t,r=!1){let n=new Ut,s=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function i(o,c=[]){let a={...o};for(let[l,f]of Object.entries(o)){let u=[...c,l],h=[`${s}_${u.join("_").toUpperCase()}`,`${s}_${u.map((m)=>m.toUpperCase()).join("")}`,`${s}_${u.map((m)=>m.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],g,b;for(let m of h)if(g=et.env[m],g!==void 0){b=m;break}if(g!==void 0&&b)if(typeof f==="boolean")a[l]=["true","1","yes"].includes(g.toLowerCase());else if(typeof f==="number"){let m=Number(g);if(!Number.isNaN(m))a[l]=m}else if(Array.isArray(f))try{a[l]=JSON.parse(g)}catch{a[l]=g.split(",").map((m)=>m.trim())}else a[l]=g;else if(f&&typeof f==="object"&&!Array.isArray(f))a[l]=i(f,u)}return a}return i(t)}var fa=B(et.cwd(),"config"),ua=B(et.cwd(),"src/generated");var Ti=["code-style","lint"],wn={ignores:["**/node_modules/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/.output/**","**/.next/**","**/.nuxt/**","**/.vite/**","**/.turbo/**","**/.cache/**","**/coverage/**","**/vendor/**","**/pantry/**","**/tmp/**","**/.git/**","**/.idea/**","**/.vscode/**","**/.zed/**","**/.cursor/**","**/.claude/**","**/.github/**","**/*.test.ts","**/*.spec.ts","**/.bunpress/**","**/.vitepress/cache/**","**/storage/framework/stx/**","**/storage/framework/runtime/**","**/storage/cloud/**","**/*.lock","**/package-lock.json","**/pnpm-lock.yaml"],lint:{extensions:["ts","js","html","css","json","jsonc","md","yaml","yml","stx","sh","bash","zsh"],reporter:"stylish",cache:!1,maxWarnings:-1},format:{extensions:["ts","js","html","css","json","jsonc","md","yaml","yml","stx","sh","bash","zsh"],trimTrailingWhitespace:!0,maxConsecutiveBlankLines:1,finalNewline:"one",indent:2,indentStyle:"spaces",preserveCodeIndentation:!1,quotes:"single",semi:!1},rules:{noDebugger:"error",noConsole:"warn"},pluginRules:{"style/brace-style":"warn","style/curly":"off","style/if-newline":"off","style/max-statements-per-line":"warn","pickier/import-dedupe":"warn","pickier/no-import-node-modules-by-path":"error","pickier/no-import-dist":"error","pickier/prefer-const":"error","pickier/prefer-template":"warn","pickier/no-unused-vars":"error","pickier/sort-tailwind-classes":"warn","regexp/no-unused-capturing-group":"error","regexp/no-super-linear-backtracking":"error","regexp/no-useless-lazy":"error","ts/no-top-level-await":"error","ts/member-delimiter-style":"off","ts/type-annotation-spacing":"off","style/comma-dangle":"off","style/keyword-spacing":"off","style/arrow-spacing":"off","style/space-infix-ops":"off","style/object-curly-spacing":"off","style/spaced-comment":"off","style/block-spacing":"off","style/space-before-blocks":"off","style/comma-spacing":"off","style/semi-spacing":"off","style/rest-spread-spacing":"off","style/key-spacing":"off","style/computed-property-spacing":"off","style/array-bracket-spacing":"off","style/space-in-parens":"off","style/template-curly-spacing":"off","style/space-unary-ops":"off","style/switch-colon-spacing":"off","style/arrow-parens":"off","style/space-before-function-paren":"off","style/quote-props":"off","style/no-floating-decimal":"off","style/new-parens":"off","style/no-extra-parens":"off","style/wrap-iife":"off","style/comma-style":"off","style/dot-location":"off","style/operator-linebreak":"off","style/multiline-ternary":"off","style/padded-blocks":"off","style/lines-between-class-members":"off","style/no-tabs":"off","style/no-mixed-spaces-and-tabs":"off","style/generator-star-spacing":"off","style/yield-star-spacing":"off","style/function-call-spacing":"off","style/template-tag-spacing":"off","style/no-whitespace-before-property":"off","style/no-mixed-operators":"off","style/indent-binary-ops":"off","ts/type-generic-spacing":"off","ts/type-named-tuple-spacing":"off","markdown/heading-increment":"warn","markdown/heading-style":"warn","markdown/no-missing-space-atx":"error","markdown/no-multiple-space-atx":"error","markdown/no-missing-space-closed-atx":"error","markdown/no-multiple-space-closed-atx":"error","markdown/blanks-around-headings":"warn","markdown/heading-start-left":"warn","markdown/no-duplicate-heading":"warn","markdown/single-title":"warn","markdown/no-trailing-punctuation":"warn","markdown/ul-style":"warn","markdown/list-indent":"error","markdown/ul-indent":"warn","markdown/ol-prefix":"warn","markdown/list-marker-space":"error","markdown/blanks-around-lists":"warn","markdown/no-trailing-spaces":"error","markdown/no-hard-tabs":"error","markdown/no-multiple-blanks":"warn","markdown/no-multiple-space-blockquote":"error","markdown/no-blanks-blockquote":"warn","markdown/blanks-around-fences":"warn","markdown/single-trailing-newline":"error","markdown/blanks-around-tables":"warn","markdown/no-reversed-links":"error","markdown/no-bare-urls":"warn","markdown/no-space-in-links":"error","markdown/no-empty-links":"error","markdown/link-fragments":"warn","markdown/reference-links-images":"warn","markdown/link-image-reference-definitions":"warn","markdown/link-image-style":"warn","markdown/descriptive-link-text":"warn","markdown/line-length":"off","markdown/commands-show-output":"warn","markdown/fenced-code-language":"warn","markdown/code-block-style":"off","markdown/code-fence-style":"warn","markdown/no-emphasis-as-heading":"warn","markdown/no-space-in-emphasis":"warn","markdown/no-space-in-code":"warn","markdown/emphasis-style":"warn","markdown/strong-style":"warn","markdown/no-inline-html":"off","markdown/hr-style":"warn","markdown/first-line-heading":"off","markdown/required-headings":"off","markdown/proper-names":"off","markdown/no-alt-text":"warn","markdown/table-pipe-style":"warn","markdown/table-column-count":"warn","markdown/table-column-style":"warn","lockfile/validate-host":["warn",{allowedHosts:["npm","yarn"]}],"lockfile/validate-https":"error","lockfile/validate-integrity":["warn",{requiredAlgorithm:"sha512"}],"lockfile/validate-package-names":"error","lockfile/validate-scheme":["error",{allowedSchemes:["https:","git+https:","git+ssh:"]}],"publint/exports-types-should-be-first":"error","publint/exports-default-should-be-last":"error","publint/exports-module-should-precede-require":"error","publint/exports-value-invalid":"error","publint/imports-key-invalid":"error","publint/imports-value-invalid":"error","publint/imports-default-should-be-last":"error","publint/imports-module-should-precede-require":"error","publint/use-type":"warn","publint/deprecated-field-jsnext":"warn","publint/field-invalid-value-type":"error","publint/local-dependency":"error","publint/has-module-but-no-exports":"warn","publint/exports-missing-root-entrypoint":"warn","publint/exports-fallback-array-use":"warn","publint/file-does-not-exist":"warn","publint/file-invalid-format":"warn","publint/module-should-be-esm":"error","publint/bin-file-not-executable":"error","publint/exports-module-should-be-esm":"error","shell/command-substitution":"error","shell/quote-variables":"warn","shell/no-cd-without-check":"warn","shell/no-eval":"error","shell/no-useless-cat":"warn","shell/shebang":"warn","shell/indent":"warn","shell/function-style":"warn","shell/operator-spacing":"warn","shell/keyword-spacing":"warn","shell/no-trailing-semicolons":"warn","shell/no-trailing-whitespace":"error","shell/prefer-double-brackets":"warn","shell/set-options":"off","shell/prefer-printf":"warn","shell/consistent-case-terminators":"warn","shell/no-broken-redirect":"error","shell/heredoc-indent":"warn","shell/no-ls-parsing":"warn","shell/no-variable-in-single-quotes":"warn","shell/no-exit-in-subshell":"warn","spell/check":"off","spell/check-comments":"off","spell/check-markdown":"off"},verbose:!0},qt=null;async function ma(){if(!qt)qt=await yn({name:"pickier",alias:[...Ti],defaultConfig:wn});return qt}var da=wn;
|
|
62
|
-
export{wn as
|
|
62
|
+
export{wn as N,ma as O,da as P};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./chunk-
|
|
2
|
+
import"./chunk-awmb5sg5.js";var e="pickier",u="module",t="0.1.61",r="Format, lint and more in a fraction of seconds.",s="Chris Breuer <chris@stacksjs.org>",l="MIT",p="https://github.com/pickier/pickier#readme",b={type:"git",url:"git+https://github.com/pickier/pickier.git"},c={url:"https://github.com/pickier/pickier/issues"},m=["pickier","linter","formatter","bun","fast"],o={".":{types:"./dist/src/index.d.ts",import:"./dist/src/index.js"},"./*":{import:"./dist/*"}},a="./dist/src/index.js",x="./dist/src/index.d.ts",d={pickier:"./dist/bin/cli.js"},w=["README.md","dist"],k={build:"bun --bun build.ts","build:bin":"bun --bun build.ts && bun run compile",compile:"bun build ./bin/cli.ts --compile --minify --outfile bin/pickier","compile:all":"bun run compile:linux-x64 && bun run compile:linux-arm64 && bun run compile:linux-x64-musl && bun run compile:linux-arm64-musl && bun run compile:windows-x64 && bun run compile:windows-arm64 && bun run compile:darwin-x64 && bun run compile:darwin-arm64","compile:linux-x64":"bun build ./bin/cli.ts --compile --minify --target=bun-linux-x64 --outfile bin/pickier-linux-x64","compile:linux-arm64":"bun build ./bin/cli.ts --compile --minify --target=bun-linux-arm64 --outfile bin/pickier-linux-arm64","compile:linux-x64-musl":"bun build ./bin/cli.ts --compile --minify --target=bun-linux-x64-musl --outfile bin/pickier-linux-x64-musl","compile:linux-arm64-musl":"bun build ./bin/cli.ts --compile --minify --target=bun-linux-arm64-musl --outfile bin/pickier-linux-arm64-musl","compile:windows-x64":"bun build ./bin/cli.ts --compile --minify --target=bun-windows-x64 --outfile bin/pickier-windows-x64.exe","compile:windows-arm64":"bun build ./bin/cli.ts --compile --minify --target=bun-windows-arm64 --outfile bin/pickier-windows-arm64.exe","compile:darwin-x64":"bun build ./bin/cli.ts --compile --minify --target=bun-darwin-x64 --outfile bin/pickier-darwin-x64","compile:darwin-arm64":"bun build ./bin/cli.ts --compile --minify --target=bun-darwin-arm64 --outfile bin/pickier-darwin-arm64",zip:"bun run zip:all","zip:all":"bun run zip:linux-x64 && bun run zip:linux-arm64 && bun run zip:linux-x64-musl && bun run zip:linux-arm64-musl && bun run zip:windows-x64 && bun run zip:windows-arm64 && bun run zip:darwin-x64 && bun run zip:darwin-arm64","zip:linux-x64":"zip -j bin/pickier-linux-x64.zip bin/pickier-linux-x64","zip:linux-arm64":"zip -j bin/pickier-linux-arm64.zip bin/pickier-linux-arm64","zip:linux-x64-musl":"zip -j bin/pickier-linux-x64-musl.zip bin/pickier-linux-x64-musl","zip:linux-arm64-musl":"zip -j bin/pickier-linux-arm64-musl.zip bin/pickier-linux-arm64-musl","zip:windows-x64":"zip -j bin/pickier-windows-x64.zip bin/pickier-windows-x64.exe","zip:windows-arm64":"zip -j bin/pickier-windows-arm64.zip bin/pickier-windows-arm64.exe","zip:darwin-x64":"zip -j bin/pickier-darwin-x64.zip bin/pickier-darwin-x64","zip:darwin-arm64":"zip -j bin/pickier-darwin-arm64.zip bin/pickier-darwin-arm64",prepublishOnly:"bun --bun run build && bun run compile:all && bun run zip",test:"PICKIER_NO_AUTO_CONFIG=1 bun test --coverage","test:core":"PICKIER_NO_AUTO_CONFIG=1 bun test test/core","test:format":"PICKIER_NO_AUTO_CONFIG=1 bun test test/format","test:lint":"PICKIER_NO_AUTO_CONFIG=1 bun test test/lint","test:rules":"PICKIER_NO_AUTO_CONFIG=1 bun test test/rules","test:rules:sort":"PICKIER_NO_AUTO_CONFIG=1 bun test test/rules/sort","test:rules:style":"PICKIER_NO_AUTO_CONFIG=1 bun test test/rules/style","test:rules:quality":"PICKIER_NO_AUTO_CONFIG=1 bun test test/rules/quality","test:rules:imports":"PICKIER_NO_AUTO_CONFIG=1 bun test test/rules/imports","test:rules:typescript":"PICKIER_NO_AUTO_CONFIG=1 bun test test/rules/typescript","test:rules:regexp":"PICKIER_NO_AUTO_CONFIG=1 bun test test/rules/regexp","test:plugin":"PICKIER_NO_AUTO_CONFIG=1 bun test test/plugin","test:watch":"PICKIER_NO_AUTO_CONFIG=1 bun test --watch"},I={"@stacksjs/clarity":"^0.3.24","@stacksjs/clapp":"^0.2.3"},O={"@stacksjs/ts-spell-check":"^0.1.0"},_={bunfig:"^0.15.13"},z={name:e,type:u,version:t,description:r,author:s,license:l,homepage:p,repository:b,bugs:c,keywords:m,exports:o,module:a,types:x,bin:d,files:w,scripts:k,dependencies:I,optionalDependencies:O,devDependencies:_};export{s as author,d as bin,c as bugs,z as default,I as dependencies,r as description,_ as devDependencies,o as exports,w as files,p as homepage,m as keywords,l as license,a as module,e as name,O as optionalDependencies,b as repository,k as scripts,u as type,x as types,t as version};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{N as I}from"./chunk-3j5z4940.js";import{Q as dt}from"./chunk-awmb5sg5.js";function ue(e){let s=e.length,n=Array.from({length:s},(r,i)=>e[i]),t=0;while(t<s){let r=e[t];if(r==="#"&&(t===0||/\s/.test(e[t-1]))){while(t<s)n[t]=" ",t++;break}if(r==="$"&&e[t+1]==="'"){t+=2;while(t<s){if(e[t]==="\\"&&t+1<s){n[t]=" ",n[t+1]=" ",t+=2;continue}if(e[t]==="'"){t++;break}n[t]=" ",t++}continue}if(r==="$"&&e[t+1]==='"'){t++,t=A(e,t,n);continue}if(r==="$"&&e[t+1]==="{"){t+=2;let i=1;while(t<s&&i>0){let o=e[t];if(o==="\\"&&t+1<s){n[t]=" ",n[t+1]=" ",t+=2;continue}if(o==="'"){t++;while(t<s&&e[t]!=="'")n[t]=" ",t++;if(t<s)t++;continue}if(o==='"'){t=A(e,t,n);continue}if(o==="{"){i++,t++;continue}if(o==="}"){i--,t++;continue}n[t]=" ",t++}continue}if(r==="$"&&e[t+1]==="("&&e[t+2]==="("){t+=3;let i=2;while(t<s&&i>0){let o=e[t];if(o==="("){i++,t++;continue}if(o===")"){i--,t++;continue}n[t]=" ",t++}continue}if(r==="$"&&e[t+1]==="("){t+=2;let i=1;while(t<s&&i>0){let o=e[t];if(o==="\\"&&t+1<s){n[t]=" ",n[t+1]=" ",t+=2;continue}if(o==="'"){t++;while(t<s&&e[t]!=="'")n[t]=" ",t++;if(t<s)t++;continue}if(o==='"'){t=A(e,t,n);continue}if(o==="("){i++,t++;continue}if(o===")"){i--,t++;continue}n[t]=" ",t++}continue}if(r==="'"){t++;while(t<s&&e[t]!=="'")n[t]=" ",t++;if(t<s)t++;continue}if(r==='"'){t=A(e,t,n);continue}if(r==="`"){t++;while(t<s&&e[t]!=="`"){if(e[t]==="\\"&&t+1<s){n[t]=" ",n[t+1]=" ",t+=2;continue}n[t]=" ",t++}if(t<s)t++;continue}t++}return n.join("")}function A(e,s,n){let t=e.length,r=s+1;while(r<t){let i=e[r];if(i==="\\"&&r+1<t){n[r]=" ",n[r+1]=" ",r+=2;continue}if(i==='"')return r+1;if(i==="$"&&e[r+1]==="("&&e[r+2]==="("){r+=3;let o=2;while(r<t&&o>0){let c=e[r];if(c==="("){o++,r++;continue}if(c===")"){o--,r++;continue}n[r]=" ",r++}continue}if(i==="$"&&e[r+1]==="("){r+=2;let o=1;while(r<t&&o>0){let c=e[r];if(c==="\\"&&r+1<t){n[r]=" ",n[r+1]=" ",r+=2;continue}if(c==="'"){r++;while(r<t&&e[r]!=="'")n[r]=" ",r++;if(r<t)r++;continue}if(c==='"'){r=A(e,r,n);continue}if(c==="("){o++,r++;continue}if(c===")"){o--,r++;continue}n[r]=" ",r++}continue}if(i==="$"&&e[r+1]==="{"){r+=2;let o=1;while(r<t&&o>0){let c=e[r];if(c==="{"){o++,r++;continue}if(c==="}"){o--,r++;continue}n[r]=" ",r++}continue}n[r]=" ",r++}return r}function Y(e){let n=ue(e).match(/<<-?/);if(!n||n.index===void 0)return null;let r=e.slice(n.index+n[0].length).match(/^\s*(['"]?)(\w+)\1/);if(!r)return null;return r[2]}var ge=new Set([".ts",".js"]),pe=new Set([".json",".jsonc"]),de=new Set([".yaml",".yml"]),me=new Set([".sh",".bash",".zsh",".ksh",".dash"]),he=/^#!\s*(?:\/usr\/bin\/env\s+)?(?:ba|z|k|da)?sh\b/;var ye=/^[}\])]/,be=/[{[(]\s*$/,we=/\s*\/\/.*$/,Se=/^(?:if|else\s+if|for|while)\s*\(/,xe=/^(?:\.[\w$[]|\?[\s.:]|:\s|&&|\|\|)/;function Ce(e){let s=Se.exec(e);if(!s)return/^(?:else|do)\s*$/.test(e);let n=0,t=null;for(let r=s[0].length-1;r<e.length;r++){let i=e[r];if(t){if(i==="\\"){r++;continue}if(i===t)t=null;continue}if(i==="'"||i==='"'||i==="`"){t=i;continue}if(i==="(")n++;else if(i===")"){if(n--,n===0)return e.slice(r+1).trim().length===0}}return!1}var Ee=/^\s*for\s*\(/,ke=new RegExp("^\\s*;\\s*$"),$e=new RegExp(";{2,}\\s*$"),Re=/([\w)])\{/g,_e=/\{(return|if|for|while|switch|const|let|var|function)\b/g,Ie=/,(\S)/g,Oe=/(?<![=!<>+\-*/%&|^?])=(?![=><])/g,Te=/(\w)\+(\w)/g,Ne=/(\w)-(\w)/g,ve=/(\w)\*(\w)/g,Ae=/(\w)\/(\w)/g,Pe=new RegExp("(?<=\\S);([^\\s;])","g"),Me=/([\w)\]])<(\d)/g,Le=/([\w)\]])>(\d)/g,H=/\s{2,}/g,Q=/^\s*$/,je=/^\s*\/\//,X=/^\s*\/\*/,De=/^\s*import\b/,V=/\bfrom\s*['"][^'"]+['"]|^\s*import\s+['"][^'"]+['"]/,Fe=/package\.json$/i,Ue=/[jt]sconfig(?:\..+)?\.json$/i,D=/[ \t]+$/,Ge=/^\n+/;function L(e){let s=e.lastIndexOf(".");return s>=0?e.slice(s):""}function F(e){return ge.has(L(e))}function We(e){return pe.has(L(e))}function Be(e){return de.has(L(e))}function Je(e){return me.has(L(e))}function Ke(e,s){return Je(e)||he.test(s)}function ze(e,s){let n=e.split(`
|
|
3
|
+
`),t=n.length,r=Array(t),i=s.format.indent,o=s.format.indentStyle==="tabs",c=0,f=!1,g="",p=!1,m=0;for(let a=0;a<t;a++){let h=n[a];if(h.length===0||/^\s*$/.test(h)){r[a]="";continue}if(f){if(r[a]=h,h.trim()===g)f=!1,g="";continue}let b=Y(h);if(b)f=!0,g=b;let w=0;while(w<h.length&&(h.charCodeAt(w)===32||h.charCodeAt(w)===9))w++;let d=h.slice(w).trimEnd();if(d.startsWith("#")&&a>0){let v=o?"\t".repeat(c):" ".repeat(c*i);r[a]=v+d;continue}if(/^case\b/.test(d)&&/\bin\s*$/.test(d))m++,p=!0;if(/^esac\b/.test(d)){if(m=Math.max(0,m-1),m===0)p=!1}let C=p&&/\)\s*$/.test(d)&&!/\$\(/.test(d)&&!/^\s*\(/.test(d)&&!d.startsWith("#"),E=/^;[;&]\s*$/.test(d);if(/^(?:fi|done|esac|elif|else)\b/.test(d)||/^\}/.test(d))c=Math.max(0,c-1);if(E)c=Math.max(0,c-1);let N=o?"\t".repeat(c):" ".repeat(c*i);if(r[a]=N+d,/^then\b/.test(d)||/^do\b/.test(d)||/^else\b/.test(d))c++;else if(/^if\b/.test(d)&&/\bthen\s*$/.test(d))c++;else if(/^elif\b/.test(d)&&/\bthen\s*$/.test(d))c++;else if(/^(?:while|for|until)\b/.test(d)&&/\bdo\s*$/.test(d))c++;else if(/^case\b/.test(d)&&/\bin\s*$/.test(d))c++;else if(C)c++;else if(/\{\s*$/.test(d)&&!d.startsWith("#"))c++}return r.join(`
|
|
4
|
+
`)}function Ye(e,s){try{let n=Bun.YAML.parse(e),t=s.format.indentStyle==="tabs"?"\t":s.format.indent;return Bun.YAML.stringify(n,null,t).split(`
|
|
5
|
+
`).map((i)=>i.replace(/[ \t]+$/,"")).join(`
|
|
6
|
+
`)}catch{return e}}function He(e){return" ".repeat(Math.max(0,e))}function Qe(e,s){if((s.format.indentStyle||"spaces")==="tabs")return"\t".repeat(Math.max(0,e));return He(Math.max(0,e*s.format.indent))}function Xe(e){return`'${e.slice(1,-1).replace(/\\"/g,'"')}'`}function Ve(e){return`"${e.slice(1,-1).replace(/\\'/g,"'")}"`}function Ze(e,s){for(let n=0;n<e.length;n++){if(e[n]==="\\"){n++;continue}if(e[n]===s)return!0}return!1}function qe(e,s,n){if(!F(n))return e;let t=e.split(`
|
|
7
|
+
`);for(let r=0;r<t.length;r++)t[r]=te(t[r],s);return t.join(`
|
|
8
|
+
`)}function te(e,s){let n=s==="single";if(n?!e.includes('"'):!e.includes("'"))return e;let t=[],r=0,i=0,o=0,c=0;while(r<e.length){let f=e[r];if(o===0){if(f==="/"){let g=e[r+1];if(g==="/")break;if(g==="*"){let p=e.indexOf("*/",r+2);r=p===-1?e.length:p+2;continue}if(re(e,r)){let p=ie(e,r);if(p!==-1){r=p;continue}}r++;continue}if(f==='"'){o=2,c=r,r++;continue}if(f==="'"){o=1,c=r,r++;continue}if(f==="`"){o=3,r++;continue}r++}else if(o===3){if(f==="\\"){r+=2;continue}if(f==="`")o=0;r++}else{if(f==="\\"){r+=2;continue}if(f===(o===1?"'":'"')){let p=e.slice(c+1,r);if((o===2&&n||o===1&&!n)&&!Ze(p,n?"'":'"')){if(c>i)t.push(e.slice(i,c));if(o===2)t.push(Xe(`"${p}"`));else t.push(Ve(`'${p}'`));i=r+1}o=0,r++;continue}r++}}if(t.length===0)return e;if(i<e.length)t.push(e.slice(i));return t.join("")}var et=new Set(["{",",","=","+","-","*","/",";","<",">"]);function tt(e){if(e.length<4)return e;let s=0;while(s<e.length&&(e[s]===" "||e[s]==="\t"))s++;if(s<e.length){let o=e[s];if(o==="/"&&(e[s+1]==="/"||e[s+1]==="*"))return e;if(o==="*")return e}let n=!1;for(let o=s;o<e.length;o++)if(et.has(e[o])){n=!0;break}if(!n)return e;let{text:t,strings:r}=it(e),i=t;if(i=i.replace(Re,"$1 {"),i=i.replace(_e,"{ $1"),i=i.replace(Ie,", $1"),i=i.replace(Oe," = "),i=i.replace(Te,"$1 + $2"),i=i.replace(Ne,"$1 - $2"),i=i.replace(ve,"$1 * $2"),i=i.replace(Ae,"$1 / $2"),i=i.replace(Pe,"; $1"),i=i.replace(Me,"$1 < $2"),i=i.replace(Le,"$1 > $2"),s>0){let o=i.slice(s);i=i.slice(0,s)+o.replace(H," ")}else i=i.replace(H," ");return r.length>0?ot(i,r):i}function j(e){let s=e[e.length-1];return s!==void 0&&s.t==="tmpl"}function ne(e,s,n){s++;while(s<e.length){let t=e[s];if(t==="\\"){s+=2;continue}if(t===n)return s+1;s++}return s}function U(e,s){for(let t of s)if(t.t==="tmpl")t.start=-1;let n=0;while(n<e.length){let t=s[s.length-1],r=e[n];if(t===void 0||t.t==="interp"){if(r==="`"){s.push({t:"tmpl",start:n}),n++;continue}if(r==="'"||r==='"'){n=ne(e,n,r);continue}if(r==="/"&&e[n+1]==="/")break;if(t!==void 0){if(r==="{"){t.braces++,n++;continue}if(r==="}"){if(t.braces===0)s.pop();else t.braces--;n++;continue}}n++}else{if(r==="\\"){n+=2;continue}if(r==="`"){s.pop(),n++;continue}if(r==="$"&&e[n+1]==="{"){s.push({t:"interp",braces:0}),n+=2;continue}n++}}if(j(s)){for(let t of s)if(t.t==="tmpl"&&t.start>=0)return t.start}return-1}function Z(e,s){let n=s,t=null,r=0;while(r<e.length){let i=e[r];if(n){if(i==="*"&&e[r+1]==="/"){n=!1,r+=2;continue}r++;continue}if(t){if(i==="\\"){r+=2;continue}if(i===t)t=null;r++;continue}if(i==="'"||i==='"'||i==="`"){t=i,r++;continue}if(i==="/"){if(e[r+1]==="/")break;if(e[r+1]==="*"){n=!0,r+=2;continue}}r++}return n}function nt(e,s){let n=e.split(`
|
|
9
|
+
`),t=n.length,r=Array(t),i=s.format.quotes,o=s.format.semi===!0,c=0,f=0,g=!1,p=[];for(let m=0;m<t;m++){let a=n[m];if(g){g=Z(a,!0),r[m]=a;continue}let h=j(p),b=-1;if(p.length>0||a.indexOf("`")!==-1)b=U(a,p);if(h){r[m]=a;continue}if(b<0&&p.length===0)g=Z(a,!1);let w="",d=!1,C="";if(b>=0){w=a.slice(b);let _=a.slice(0,b);if(_.length===0){r[m]=w;continue}if(d=D.test(_),_.trim().length===0)C=_;a=_}if(a.length===0){r[m]="";continue}a=te(a,i);let E=0;while(E<a.length&&(a.charCodeAt(E)===32||a.charCodeAt(E)===9))E++;let k=a.slice(E).trimEnd();if(ye.test(k))c=Math.max(0,c-1);let N=xe.test(k)?1:0,v=a.slice(0,E);if(a=s.format.preserveCodeIndentation?v+k:Qe(c+f+N,s)+k,be.test(k))c+=1,f=0;else if(!k.startsWith("//")&&!k.startsWith("*")&&!k.startsWith("/*")){let _=k.replace(we,"");f=Ce(_)?f+1:0}if(a=tt(a),o){if(!Ee.test(a))if(ke.test(a))a="";else a=a.replace($e,";")}if(s.format.trimTrailingWhitespace)a=a.trimEnd();if(b>=0){if(C)a=C;else if(d&&!D.test(a))a+=" ";a+=w}r[m]=a}return r.join(`
|
|
10
|
+
`)}function st(e,s){let n=[],t=0,r=[];for(let i of e){let o=j(r);if(r.length>0||i.indexOf("`")!==-1)U(i,r);if(o){n.push(i),t=0;continue}if(i===""){if(t++,t<=s)n.push("")}else t=0,n.push(i)}return n}function Nt(e,s,n){if(e.length===0)return"";let r=(e.includes("\r")?e.replace(/\r\n/g,`
|
|
11
|
+
`):e).split(`
|
|
12
|
+
`),i;if(s.format.trimTrailingWhitespace){i=[];let g=0,p=Math.max(0,s.format.maxConsecutiveBlankLines),m=[];for(let a of r){let h=j(m),b=!1;if(m.length>0||a.indexOf("`")!==-1)b=U(a,m)>=0;if(h||b){i.push(a),g=0;continue}let w=a[a.length-1],d=w===" "||w==="\t"?a.replace(D,""):a;if(d===""){if(g++,g<=p)i.push("")}else g=0,i.push(d)}}else i=st(r,Math.max(0,s.format.maxConsecutiveBlankLines));let o=i.join(`
|
|
13
|
+
`);if(o=o.replace(Ge,""),F(n))o=at(o);if(Be(n)){let g=Ye(o,s);if(g!==o)o=g}if(We(n)){let g=ut(o,n);if(g!=null)o=g}if(Ke(n,o))o=ze(o,s);else if(F(n))o=nt(o,s);else o=qe(o,s.format.quotes,n);if(s.format.finalNewline==="none")return o.replace(/\n+$/g,"");let c=/[^\n]\n$/.test(o)||o===`
|
|
14
|
+
`,f=/\n\n$/.test(o);if(s.format.finalNewline==="two"){if(f)return o;if(c)return`${o}
|
|
15
|
+
`;return`${o}
|
|
16
|
+
|
|
17
|
+
`}if(f)return o.replace(/\n\n$/,`
|
|
18
|
+
`);if(c)return o;return`${o}
|
|
19
|
+
`}function q(e,s,n,t){for(let r=s+1;r<e.length;r++){let i=e[r];if(i==="\\"){r++;continue}if(i===n)return!0;if(i===t)return!1}return!0}function vt(e,s){if(/^\s*\/\/\/\s*<reference/.test(e))return[];let n=[],t=null,r=!1;for(let i=0;i<e.length;i++){let o=e[i];if(r){r=!1;continue}if(o==="\\"){r=!0;continue}if(!t){if(o==="/"&&e[i+1]==="/")break;if(o==="'"){if(s==="double"&&q(e,i,"'",'"'))n.push(i);t="single";continue}else if(o==='"'){if(s==="single"&&q(e,i,'"',"'"))n.push(i);t="double";continue}else if(o==="`"){t="template";continue}}else if(t==="single"&&o==="'"||t==="double"&&o==='"'||t==="template"&&o==="`"){t=null;continue}}return n}function At(e,s,n="spaces",t){if(n==="tabs")return/[^\t]/.test(e);if(/\t/.test(e))return!0;let r=e.length;if(t&&r%s===1){let i=t.trimStart();if(i.startsWith("* ")||i.startsWith("*/")||i==="*")return!1}return r%s!==0}function se(e,s){let n=s+1;while(n<e.length){let t=e[n];if(t==="\\"){n+=2;continue}if(t==="`")return n+1;if(t==="$"&&e[n+1]==="{"){n+=2;let r=1;while(n<e.length&&r>0){let i=e[n];if(i==="\\"){n+=2;continue}if(i==="`"){n=se(e,n);continue}if(i==="'"||i==='"'){n=ne(e,n,i);continue}if(i==="{")r++;else if(i==="}")r--;n++}continue}n++}return n}var rt=new Set(["return","typeof","instanceof","in","of","new","delete","void","do","else","case","yield","await"]);function re(e,s){let n=s-1;while(n>=0&&(e[n]===" "||e[n]==="\t"))n--;if(n<0)return!0;let t=e[n];if("(,=:[!&|?;{}<>+-*%^~".includes(t))return!0;if(/[\w$]/.test(t)){let r=n;while(r>=0&&/[\w$]/.test(e[r]))r--;return rt.has(e.slice(r+1,n+1))}return!1}function ie(e,s){let n=s+1,t=!1,r=-1;while(n<e.length){let i=e[n];if(i==="\\"){n+=2;continue}if(i==="["&&!t)t=!0,r=n;else if(i==="]"&&t){let o=e[r+1]==="^"?r+2:r+1;if(n!==o)t=!1}else if(i==="/"&&!t){n++;while(n<e.length&&/[a-z]/i.test(e[n]))n++;return n}n++}return-1}function it(e){if(!e.includes("'")&&!e.includes('"')&&!e.includes("`")&&!e.includes("/"))return{text:e,strings:[]};let s=[],n=[],t=0,r=0;while(t<e.length){let i=e[t];if(i==="/"){let o=e[t+1];if(o==="/"){if(t>r)n.push(e.slice(r,t));s.push(e.slice(t)),n.push(`@@S${s.length-1}@@`),r=e.length;break}if(o==="*"){let c=e.indexOf("*/",t+2),f=c===-1?e.length:c+2;if(t>r)n.push(e.slice(r,t));s.push(e.slice(t,f)),n.push(`@@S${s.length-1}@@`),t=f,r=t;continue}if(re(e,t)){let c=ie(e,t);if(c!==-1){if(t>r)n.push(e.slice(r,t));s.push(e.slice(t,c)),n.push(`@@S${s.length-1}@@`),t=c,r=t;continue}}t++;continue}if(i==="'"||i==='"'||i==="`"){if(t>r)n.push(e.slice(r,t));let o=t;if(i==="`")t=se(e,t);else{let c=i;t++;while(t<e.length){if(e[t]==="\\"){t+=2;continue}if(e[t]===c){t++;break}t++}}s.push(e.slice(o,t)),n.push(`@@S${s.length-1}@@`),r=t;continue}t++}if(r<e.length)n.push(e.slice(r));return{text:n.join(""),strings:s}}function ot(e,s){if(s.length===0)return e;return e.replace(/@@S(\d+)@@/g,(n,t)=>s[Number(t)]??"")}function ct(e){let s=new Set,n=/[$A-Z_][\w$]*/gi,t=n.exec(e);while(t!==null)s.add(t[0]),t=n.exec(e);return s}function at(e){let s=e[0];if(s!=="i"&&s!==" "&&s!=="\t"&&s!=="/"&&s!==`
|
|
20
|
+
`)return e;let n=e.split(`
|
|
21
|
+
`),t=[],r=[],i=[],o=0,c=0,f=-1,g=!1;while(o<n.length){let l=n[o];if(Q.test(l)){o++;continue}if(je.test(l)||X.test(l)){let y=o;if(X.test(l)){while(o<n.length&&!n[o].includes("*/"))o++;o++}else o++;if(!g){for(let R=y;R<o&&R<n.length;R++)r.push(n[R]);c=o}else if(f<0)f=y;continue}if(!De.test(l))break;let u=l.trim(),x=o+1;while(!V.test(u)&&x<n.length&&x-o<50)u+=` ${n[x].trim()}`,x++;if(!V.test(u))return e;let S=ft(u);if(!S)return e;if(f>=0){for(let y=f;y<o;y++)if(!Q.test(n[y]))i.push(n[y]);f=-1}t.push(S),o=x,c=o,g=!0}if(t.length===0)return e;let p=f>=0?f:c,m=n.slice(p).join(`
|
|
22
|
+
`),a=ct(m),h=(l)=>a.has(l);for(let l of t){if(l.kind!=="value")continue;l.named=l.named.filter((u)=>{if(u.alias)return!0;return h(u.name)})}let b=t.filter((l)=>{if(l.kind==="side-effect")return!0;if(l.kind==="type")return l.namedTypes.length>0;return Boolean(l.defaultName||l.namespaceName||l.named.length>0)}),w=new Map;for(let l of b){let u=w.get(l.source)||{};if(l.kind==="side-effect")u.side=u.side||[],u.side.push(l);else if(l.kind==="type"){if(!u.type)u.type={kind:"type",source:l.source,named:[],namedTypes:[],original:""};u.type.namedTypes=(u.type.namedTypes||[]).concat(l.namedTypes)}else{if(!u.value)u.value={kind:"value",source:l.source,named:[],namedTypes:[],original:""};if(l.defaultName)u.value.defaultName=l.defaultName;if(l.namespaceName)u.value.namespaceName=l.namespaceName;if(u.value.named=(u.value.named||[]).concat(l.named),l.namedTypes.length>0){if(!u.type)u.type={kind:"type",source:l.source,named:[],namedTypes:[],original:""};u.type.namedTypes=u.type.namedTypes.concat(l.namedTypes)}}w.set(l.source,u)}let d=[];for(let[l,u]of w){if(u.side)d.push(...u.side);if(u.value){let x=(S)=>{if(!S.alias)return S;return/^[A-Z]$/i.test(S.name)&&/^[A-Z]$/i.test(S.alias)?{name:S.alias,alias:S.name}:S};u.value.named=u.value.named.map(x),u.value.named.sort((S,y)=>S.name.localeCompare(y.name)),d.push(u.value)}if(u.type&&u.type.namedTypes.length>0){let x=new Set,S=(y)=>{if(!y.alias)return y;return/^[A-Z]$/i.test(y.name)&&/^[A-Z]$/i.test(y.alias)?{name:y.alias,alias:y.name}:y};u.type.namedTypes=u.type.namedTypes.map(S).filter((y)=>{let R=`${y.name}|${y.alias||""}`;if(x.has(R))return!1;return x.add(R),!0}),u.type.namedTypes.sort((y,R)=>y.name.localeCompare(R.name)),d.push(u.type)}}let C=(l)=>l.startsWith(".")?2:l.startsWith("node:")?0:1,E=(l)=>{if(l.kind!=="value")return 99;if(l.defaultName)return 0;if(l.namespaceName)return 1;return 2};d.sort((l,u)=>{if(l.kind!==u.kind){if(l.kind==="type")return-1;if(u.kind==="type")return 1;if(l.kind==="side-effect")return-1;if(u.kind==="side-effect")return 1}if(l.kind==="type"&&u.kind==="type"){let x=C(l.source),S=C(u.source);if(x!==S)return x-S;return l.source.localeCompare(u.source)}if(l.kind==="value"&&u.kind==="value"){let x=C(l.source),S=C(u.source);if(x!==S)return x-S;let y=E(l),R=E(u);if(y!==R)return y-R;return l.source.localeCompare(u.source)}return l.source.localeCompare(u.source)});let k=r.length>0?`${r.join(`
|
|
23
|
+
`)}
|
|
24
|
+
`:"";if(d.length===0){let l=m.replace(/^\n+/,""),u=[...i];if(k||u.length>0)return`${k}${u.length>0?`${u.join(`
|
|
25
|
+
`)}
|
|
26
|
+
`:""}${l}`;return l}let N=d.map(lt).join(`
|
|
27
|
+
`),v=i.length>0?`
|
|
28
|
+
${i.join(`
|
|
29
|
+
`)}`:"",_=m.replace(/^\n+/,""),fe=_.length>0?`
|
|
30
|
+
|
|
31
|
+
`:`
|
|
32
|
+
`;return`${k}${N}${v}${fe}${_}`}function lt(e){if(e.kind==="side-effect")return`import '${e.source}'`;if(e.kind==="type")return`import type { ${e.namedTypes.map((r)=>r.alias?`${r.name} as ${r.alias}`:r.name).join(", ")} } from '${e.source}'`;let s=[];if(e.defaultName)s.push(e.defaultName);if(e.namespaceName)s.push(`* as ${e.namespaceName}`);if(e.named.length>0){let t=e.named.map((r)=>r.alias?`${r.name} as ${r.alias}`:r.name).join(", ");s.push(`{ ${t} }`)}return`import ${s.join(", ")} from '${e.source}'`}function ft(e){let s=e.match(/^\s*import\s+['"]([^'"]+)['"]/);if(s)return{kind:"side-effect",source:s[1],named:[],namedTypes:[],original:e};if(s=e.match(/^\s*import\s+type\s+\{([^}]*)\}\s+from\s+['"]([^'"]+)['"]/),s){let a=s[1],h=s[2],b=a.split(",").map((w)=>w.trim()).filter(Boolean).map((w)=>{let d=w.match(/^(\w+)(?:\s+as\s+(\w+))?$/);return{name:d?.[1]||w,alias:d?.[2]}});return{kind:"type",source:h,named:[],namedTypes:b,original:e}}let n=e.match(/^\s*import\s+/),t=new RegExp(`\\sfrom\\s+['"]([^'"]+)['"]\\s*;?$`),r=e.match(t);if(!n||!r)return;let i=r[1],o=e.slice(n[0].length,r.index).trim(),c,f,g=[],p=[],m=o.match(/\{([^}]*)\}/);if(m){let h=m[1].split(",").map((b)=>b.trim()).filter(Boolean);for(let b of h){let w=/^type\s+/.test(b),C=b.replace(/^type\s+/,"").match(/^(\w+)(?:\s+as\s+(\w+))?$/);if(!C)continue;let E={name:C[1],alias:C[2]};if(w)p.push(E);else g.push(E)}o=o.replace(/\{[\s\S]*?\}/,"").trim()}if(o.length>0){let a=o.split(",").map((h)=>h.trim()).filter(Boolean);for(let h of a)if(h.startsWith("* as "))f=h.slice(5).trim();else if(/^\w+$/.test(h))c=h}return{kind:"value",source:i,defaultName:c,namespaceName:f,named:g,namedTypes:p,original:e}}function ut(e,s){if(Fe.test(s))return gt(e);if(Ue.test(s))return pt(e);return null}function oe(e){try{return JSON.parse(e)}catch{return null}}function P(e,s,n=[]){let t={};for(let i of s)if(Object.prototype.hasOwnProperty.call(e,i))t[i]=e[i];for(let i of n){let o=Object.keys(e).filter((c)=>i.test(c)&&!(c in t)).sort();for(let c of o)t[c]=e[c]}let r=Object.keys(e).filter((i)=>!(i in t)).sort();for(let i of r)t[i]=e[i];return t}function ee(e){let s={};for(let n of Object.keys(e).sort())s[n]=e[n];return s}function gt(e){let s=oe(e);if(!s||typeof s!=="object")return e;let t=P(s,["publisher","name","displayName","type","version","private","packageManager","description","author","contributors","license","funding","homepage","repository","bugs","keywords","categories","sideEffects","imports","exports","main","module","unpkg","jsdelivr","types","typesVersions","bin","icon","files","engines","activationEvents","contributes","scripts","peerDependencies","peerDependenciesMeta","dependencies","optionalDependencies","devDependencies","pnpm","overrides","resolutions","husky","simple-git-hooks","lint-staged","eslintConfig"]);if(Array.isArray(t.files)){if(t.files.every((o)=>typeof o==="string"))t.files=[...t.files].sort()}for(let i of Object.keys(t))if(/^(?:dev|peer|optional|bundled)?[Dd]ependencies(?:Meta)?$/.test(i)||/^(?:resolutions|overrides|pnpm\.overrides)$/.test(i)){if(t[i]&&typeof t[i]==="object")t[i]=ee(t[i])}if(t.pnpm&&typeof t.pnpm==="object"&&t.pnpm.overrides&&typeof t.pnpm.overrides==="object")t.pnpm.overrides=ee(t.pnpm.overrides);if(t.exports&&typeof t.exports==="object"){let i=t.exports,o=["types","import","require","default"];if(!Array.isArray(i)){let c={};for(let f of Object.keys(i)){let g=i[f];if(g&&typeof g==="object"&&!Array.isArray(g))c[f]=P(g,o);else c[f]=g}t.exports=c}}let r=["pre-commit","prepare-commit-msg","commit-msg","post-commit","pre-rebase","post-rewrite","post-checkout","post-merge","pre-push","pre-auto-gc"];for(let i of["gitHooks","husky","simple-git-hooks"])if(t[i]&&typeof t[i]==="object")t[i]=P(t[i],r);return JSON.stringify(t,null,2)}function pt(e){let s=oe(e);if(!s||typeof s!=="object")return e;let t=P(s,["extends","compilerOptions","references","files","include","exclude"]);if(t.compilerOptions&&typeof t.compilerOptions==="object"){let r=["incremental","composite","tsBuildInfoFile","disableSourceOfProjectReferenceRedirect","disableSolutionSearching","disableReferencedProjectLoad","target","jsx","jsxFactory","jsxFragmentFactory","jsxImportSource","lib","moduleDetection","noLib","reactNamespace","useDefineForClassFields","emitDecoratorMetadata","experimentalDecorators","libReplacement","baseUrl","rootDir","rootDirs","customConditions","module","moduleResolution","moduleSuffixes","noResolve","paths","resolveJsonModule","resolvePackageJsonExports","resolvePackageJsonImports","typeRoots","types","allowArbitraryExtensions","allowImportingTsExtensions","allowUmdGlobalAccess","allowJs","checkJs","maxNodeModuleJsDepth","strict","strictBindCallApply","strictFunctionTypes","strictNullChecks","strictPropertyInitialization","allowUnreachableCode","allowUnusedLabels","alwaysStrict","exactOptionalPropertyTypes","noFallthroughCasesInSwitch","noImplicitAny","noImplicitOverride","noImplicitReturns","noImplicitThis","noPropertyAccessFromIndexSignature","noUncheckedIndexedAccess","noUnusedLocals","noUnusedParameters","useUnknownInCatchVariables","declaration","declarationDir","declarationMap","downlevelIteration","emitBOM","emitDeclarationOnly","importHelpers","importsNotUsedAsValues","inlineSourceMap","inlineSources","mapRoot","newLine","noEmit","noEmitHelpers","noEmitOnError","outDir","outFile","preserveConstEnums","preserveValueImports","removeComments","sourceMap","sourceRoot","stripInternal","allowSyntheticDefaultImports","esModuleInterop","forceConsistentCasingInFileNames","isolatedDeclarations","isolatedModules","preserveSymlinks","verbatimModuleSyntax","erasableSyntaxOnly","skipDefaultLibCheck","skipLibCheck"];t.compilerOptions=P(t.compilerOptions,r)}return JSON.stringify(t,null,2)}import{readdirSync as mt,readFileSync as ht,statSync as ae}from"fs";import{extname as yt,isAbsolute as W,join as B,resolve as bt}from"path";var Dt=5;function wt(e){let s="",n=0;while(n<e.length){let t=e[n];if(t==="*")if(e[n+1]==="*"){if(s+=".*",n+=2,e[n]==="/")n++}else s+="[^/]*",n++;else if(t==="?")s+="[^/]",n++;else if(t==="["){let r=e.indexOf("]",n);if(r===-1)s+="\\[",n++;else s+=e.slice(n,r+1),n=r+1}else if(".+^${}()|\\".includes(t))s+=`\\${t}`,n++;else s+=t,n++}return new RegExp(`^${s}$`)}function*le(e,s,n){let t;try{t=mt(e)}catch{return}for(let r of t){if(!n&&r.startsWith("."))continue;let i=B(e,r);if(s(i))continue;let o;try{o=ae(i)}catch{continue}if(o.isDirectory())yield*le(i,s,n);else yield i}}function*ce(e,s,n,t){yield*le(e,z(s,t),n)}async function Ft(e,s={}){let n=s.cwd??process.cwd(),t=s.ignore??[],r=s.dot??!1,i=s.absolute??!0,o=z(t,n);if(typeof globalThis.Bun?.Glob<"u"){let f=globalThis.Bun.Glob,g=[];for(let p of e){let m=new f(p);for await(let a of m.scan({cwd:n,dot:r,onlyFiles:s.onlyFiles??!0,followSymlinks:!1})){let h=W(a)?a:B(n,a),b=h.startsWith(`${n}/`)?h.slice(n.length+1):h;if(o(h))continue;g.push(i?h:b)}}return g}let c=[];for(let f of e){if(!/[*?[{]/.test(f)){let p=W(f)?f:B(n,f);try{if(!ae(p).isDirectory()){let a=p.startsWith(`${n}/`)?p.slice(n.length+1):p;if(!o(p))c.push(i?p:a)}else for(let a of ce(p,t,r,n))c.push(i?a:a.startsWith(`${n}/`)?a.slice(n.length+1):a)}catch{}continue}let g=wt(f);for(let p of ce(n,t,r,n)){let m=p.startsWith(`${n}/`)?p.slice(n.length+1):p;if(g.test(m)||g.test(m.replace(/\\/g,"/")))c.push(i?p:m)}}return c}function Ut(e){let s=0,n=[],t=()=>{if(n.length>0&&s<e)s++,n.shift()()};return(r)=>new Promise((i,o)=>{let c=()=>{r().then((f)=>{s--,i(f),t()},(f)=>{s--,o(f),t()})};if(s<e)s++,c();else n.push(c)})}var St={get TRACE(){return process.env.PICKIER_TRACE==="1"},get TIMEOUT_MS(){return Number(process.env.PICKIER_TIMEOUT_MS||"8000")},get RULE_TIMEOUT_MS(){return Number(process.env.PICKIER_RULE_TIMEOUT_MS||"5000")},get CONCURRENCY(){return Number(process.env.PICKIER_CONCURRENCY)||8},get DIAGNOSTICS(){return process.env.PICKIER_DIAGNOSTICS==="1"},get FAIL_ON_WARNINGS(){return process.env.PICKIER_FAIL_ON_WARNINGS==="1"},get NO_AUTO_CONFIG(){return process.env.PICKIER_NO_AUTO_CONFIG==="1"}},J=["**/node_modules/**","**/.git/**"],xt=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/.next/**","**/.nuxt/**","**/.output/**","**/.vercel/**","**/.netlify/**","**/.cache/**","**/.turbo/**","**/.vscode/**","**/.idea/**","**/.zed/**","**/.cursor/**","**/.claude/**","**/.github/**","**/coverage/**","**/.nyc_output/**","**/.tmp/**","**/.temp/**","**/vendor/**","**/pantry/**","**/target/**","**/zig-cache/**","**/zig-out/**","**/.zig-cache/**","**/__pycache__/**","**/.pytest_cache/**","**/venv/**","**/.venv/**","**/out/**","**/.DS_Store","**/Thumbs.db"];function Gt(e,s){let n=e[s];if(n===void 0){let i=s.indexOf("/");if(i>0){let o=s.slice(0,i),c=s.slice(i+1),f=o==="general"?"pickier":o==="pickier"?"general":null;if(f)n=e[`${f}/${c}`];if(n===void 0)n=e[c]}}let t,r;if(typeof n==="string"){if(n==="error")t="error";else if(n==="warn"||n==="warning")t="warning"}else if(Array.isArray(n)&&typeof n[0]==="string"){let i=n[0];if(i==="error")t="error";else if(i==="warn"||i==="warning")t="warning";r=n[1]}return{enabled:!!t,severity:t,options:r}}function M(e){let s=Array.isArray(e)?e[0]:e;if(typeof s!=="string")return;if(s==="off")return"off";if(s==="error")return"error";if(s==="warn"||s==="warning")return"warning";return}function Wt(e,s,n=[],t){for(let i of[s,...n]){let o=M(e.rules?.[i])??M(e.pluginRules?.[i]);if(o)return o==="off"?void 0:o}let r=M(t);return r==="off"?void 0:r}function Bt(e,s){return M(e.rules?.[s])==="off"||M(e.pluginRules?.[s])==="off"}function T(e,s){return`\x1B[${e}m${s}\x1B[0m`}function Ct(e){return T("32",e)}function Et(e){return T("31",e)}function kt(e){return T("33",e)}function $t(e){return T("34",e)}function Rt(e){return T("90",e)}function _t(e){return T("1",e)}var Jt={green:Ct,red:Et,yellow:kt,blue:$t,gray:Rt,bold:_t};function O(e,s){let n=s.ignores?[...new Set([...e.ignores||[],...s.ignores])]:e.ignores,t={...e.pluginRules||{},...s.pluginRules||{}};if((s.tailwind??e.tailwind)?.enabled&&!Object.prototype.hasOwnProperty.call(t,"pickier/sort-tailwind-classes"))t["pickier/sort-tailwind-classes"]="warn";return{...e,...s,verbose:s.verbose??e.verbose,ignores:n,lint:{...e.lint,...s.lint||{}},format:{...e.format,...s.format||{}},rules:{...e.rules,...s.rules||{}},pluginRules:t}}var G=null;async function Kt(e){if(!e){if(St.NO_AUTO_CONFIG){if(!G)G=O(I,{});return G}try{let{getConfig:t}=await import("./chunk-mat3gcn4.js"),r=await t();return O(I,r)}catch{}return O(I,{})}let s=W(e)?e:bt(process.cwd(),e);if(yt(s).toLowerCase()===".json")try{let t=ht(s,"utf8");return O(I,JSON.parse(t))}catch{return console.warn(`[pickier:warn] Config file not found: ${s}. Using default config values.`),O(I,{})}try{let t=await import(s);return O(I,t.default||t)}catch{return console.warn(`[pickier:warn] Config file not found: ${s}. Using default config values.`),O(I,{})}}function zt(e){return e.map((s)=>{if(/[*?[\]{}()!]/.test(s))return s;if(/\.[A-Z0-9]+$/i.test(s))return s;return`${s.replace(/\/$/,"")}/**/*`})}function Yt(e,s){let n=e.lastIndexOf(".");if(n<0)return!1;let t=e.slice(n);return s.has(t)}function K(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/")}function It(e){let s=[];for(let n of e){let t=K(n.trim());if(!t)continue;let r=t.match(/\*\*\/\*\.(.+)$/);if(r){s.push({raw:t,kind:"extension",value:r[1]});continue}let i=t.match(/\*\*\/(.+?)\/\*\*$/);if(i){s.push({raw:t,kind:"segment",value:i[1]});continue}let o=t.match(/\*\*\/(.+)$/);if(o)s.push({raw:t,kind:"suffix",value:o[1].replace(/\/$/,"")})}return s}function Ht(e){return[...new Set([...J,...e])]}function z(e,s=process.cwd()){let n=It([...J,...e]);if(n.length===0)return()=>!1;let t=new Set([...xt,...J]);return(r)=>{let i=K(r),o=K(s).replace(/\/$/,""),c=i!==o&&!i.startsWith(`${o}/`),f=c?i:i.slice(o.length);for(let g of n){if(c&&!t.has(g.raw))continue;if(g.kind==="extension"){if(f.endsWith(`.${g.value}`))return!0;continue}if(g.kind==="segment"||g.kind==="suffix"){let p=g.value;if(f.includes(`/${p}/`)||f.endsWith(`/${p}`))return!0}}return!1}}function Qt(e,s){return z(s)(e)}
|
|
33
|
+
export{ue as i,Y as j,Nt as k,vt as l,At as m,at as n,Dt as o,Ft as p,Ut as q,St as r,J as s,xt as t,Gt as u,M as v,Wt as w,Bt as x,T as y,Ct as z,Et as A,kt as B,$t as C,Rt as D,_t as E,Jt as F,O as G,Kt as H,zt as I,Yt as J,Ht as K,z as L,Qt as M};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./chunk-
|
|
2
|
+
import"./chunk-awmb5sg5.js";import{existsSync as It}from"fs";import de from"fs/promises";import ke from"os";import fe from"path";import G from"process";import{EventEmitter as Ot}from"events";import P from"process";import Ve from"process";import we from"process";import ae from"process";import Ne from"process";import Z from"process";import Re from"tty";import rt,{stdin as hs,stdout as ms}from"process";import*as U from"readline";import{ReadStream as je,WriteStream as ds}from"tty";import Le,{stdin as ys,stdout as bs}from"process";import xs from"readline";import Es from"process";import Rs from"process";import{WriteStream as js}from"tty";import Ws from"process";import Te from"process";import Fs from"process";import{stripVTControlCharacters as ge}from"util";import{existsSync as Us,lstatSync as Fe,readdirSync as Gs}from"fs";import{dirname as He,join as Ks}from"path";import qs from"process";import A from"process";import ee from"process";import{stripVTControlCharacters as $e}from"util";import Ys from"process";import{Buffer as Ke}from"buffer";import j from"fs/promises";import Js from"os";import le from"path";import x from"process";import{Readable as Qs,Writable as Xs}from"stream";class qe{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let e=ke.homedir(),t=fe.join(e,".config","clapp");this.configPath=fe.join(t,"telemetry.json")}async isEnabled(){if(G.env.DO_NOT_TRACK==="1"||G.env.DO_NOT_TRACK==="true")return!1;if(G.env.NO_TELEMETRY==="1"||G.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let e=await this.loadConfig();if(e.enabled=!0,!e.userId)e.userId=this.generateUserId();await this.saveConfig(e)}async disable(){let e=await this.loadConfig();e.enabled=!1,await this.saveConfig(e)}async track(e,t){if(!await this.isEnabled())return;let i={event:e,...t,timestamp:Date.now(),platform:ke.platform(),nodeVersion:G.version};if(this.events.push(i),this.events.length>=10)await this.send()}async trackCommand(e,t){await this.track("command",{command:e,duration:t})}async trackError(e,t){await this.track("error",{error:e,command:t})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let t=await this.loadConfig();return t.lastSent=Date.now(),await this.saveConfig(t),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let t=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(t),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(e){return new Promise((t)=>setTimeout(t,e))}async status(){let e=await this.loadConfig();return{enabled:e.enabled,doNotTrack:G.env.DO_NOT_TRACK==="1"||G.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:e.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(It(this.configPath)){let e=await de.readFile(this.configPath,"utf-8");return this.config=JSON.parse(e),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(e){this.config=e;try{let t=fe.dirname(this.configPath);await de.mkdir(t,{recursive:!0}),await de.writeFile(this.configPath,JSON.stringify(e,null,2),"utf-8")}catch{}}generateUserId(){let e=Math.random().toString(36).substring(2,15),t=Date.now().toString(36);return`${e}-${t}`}}var oi=new qe;function Et(e,t={}){let s={_:[]},i=t.alias||{},r=new Set(t.boolean||[]),o={};for(let u of Object.keys(i))for(let a of i[u])o[a]=u;for(let u of r)if(i[u])for(let a of i[u])r.add(a);function l(u,a){let c=o[u]||u;if(s[c]=a,i[c])for(let h of i[c])s[h]=a;if(o[u]&&i[o[u]])for(let h of i[o[u]])s[h]=a;s[u]=a}for(let u=0;u<e.length;u++){let a=e[u];if(a==="--"){s._.push(...e.slice(u+1));break}if(a.startsWith("--")){let c=a.indexOf("=");if(c!==-1){let h=a.slice(2,c),f=a.slice(c+1);l(h,f)}else{let h=a.slice(2);if(h.startsWith("no-")){let p=h.slice(3);l(p,!1);continue}let f=o[h]||h;if(r.has(f)||r.has(h))l(h,!0);else{let p=e[u+1];if(p!==void 0&&!p.startsWith("-"))l(h,p),u++;else l(h,!0)}}}else if(a.startsWith("-")&&a.length>1){let c=a.slice(1);for(let h=0;h<c.length;h++){let f=c[h],p=o[f]||f;if(h===c.length-1&&!r.has(p)&&!r.has(f)){let d=e[u+1];if(d!==void 0&&!d.startsWith("-"))l(f,d),u++;else l(f,!0)}else l(f,!0)}}else s._.push(a)}return s}function ve(e){return e.replace(/[<[].+/,"").trim()}function Bt(e){let t=/<([^>]+)>/g,s=/\[([^\]]+)\]/g,i=[],r=(u)=>{let a=!1,c=u[1];if(c.startsWith("..."))c=c.slice(3),a=!0;return{required:u[0].startsWith("<"),value:c,variadic:a}},o;while(o=t.exec(e))i.push(r(o));let l;while(l=s.exec(e))i.push(r(l));return i}function Tt(e){let t={alias:{},boolean:[]};for(let[s,i]of e.entries()){if(i.names.length>1)t.alias[i.names[0]]=i.names.slice(1);if(i.isBoolean)if(i.negated){if(!e.some((o,l)=>l!==s&&o.names.some((u)=>i.names.includes(u))&&typeof o.required==="boolean"))t.boolean.push(i.names[0])}else t.boolean.push(i.names[0])}return t}function Me(e){return e.reduce((t,s)=>t.length>=s.length?t:s,"")}function pe(e,t){return e.length>=t?e:`${e}${" ".repeat(t-e.length)}`}function kt(e){return e.replace(/([a-z])-([a-z])/g,(t,s,i)=>s+i.toUpperCase())}function Vt(e,t,s){let i=0,r=t.length,o=e,l;for(;i<r;++i)l=o[t[i]],o=o[t[i]]=i===r-1?s:l!=null?l:!!~t[i+1].indexOf(".")||!(+t[i+1]>-1)?{}:[]}function Mt(e,t){for(let s of Object.keys(t)){let i=t[s];if(i.shouldTransform){if(e[s]=Array.prototype.concat.call([],e[s]),typeof i.transformFunction==="function")e[s]=e[s].map(i.transformFunction)}}}function At(e){let t=/([^\\/]+)$/.exec(e);return t?t[1]:""}function ze(e){return e.split(".").map((t,s)=>s===0?kt(t):t).join(".")}class oe extends Error{exitCode=2;isUsageError=!0;constructor(e){super(e);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(e).stack}format(e=!1){if(e&&this.stack)return`${this.message}
|
|
3
3
|
|
|
4
4
|
Stack trace:
|
|
5
5
|
${this.stack}`;return this.message}}function Nt(){let{env:e}=Ve,{TERM:t,TERM_PROGRAM:s}=e;if(Ve.platform!=="win32")return t!=="linux";return Boolean(e.WT_SESSION)||Boolean(e.TERMINUS_SUBLIME)||e.ConEmuTask==="{cmd::Cmder}"||s==="Terminus-Sublime"||s==="vscode"||t==="xterm-256color"||t==="alacritty"||t==="rxvt-unicode"||t==="rxvt-unicode-256color"||e.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var ue="\x1B",S=`${ue}[`,ci="\x07",k={to(e,t){if(!t)return`${S}${e+1}G`;return`${S}${t+1};${e+1}H`},move(e,t){let s="";if(e<0)s+=`${S}${-e}D`;else if(e>0)s+=`${S}${e}C`;if(t<0)s+=`${S}${-t}A`;else if(t>0)s+=`${S}${t}B`;return s},up:(e=1)=>`${S}${e}A`,down:(e=1)=>`${S}${e}B`,forward:(e=1)=>`${S}${e}C`,backward:(e=1)=>`${S}${e}D`,nextLine:(e=1)=>`${S}E`.repeat(e),prevLine:(e=1)=>`${S}F`.repeat(e),left:`${S}G`,hide:`${S}?25l`,show:`${S}?25h`,save:`${ue}7`,restore:`${ue}8`},hi={up:(e=1)=>`${S}S`.repeat(e),down:(e=1)=>`${S}T`.repeat(e)},te={screen:`${S}2J`,up:(e=1)=>`${S}1J`.repeat(e),down:(e=1)=>`${S}J`.repeat(e),line:`${S}2K`,lineEnd:`${S}K`,lineStart:`${S}1K`,lines(e){let t="";for(let s=0;s<e;s++)t+=this.line+(s<e-1?k.up():"");if(e)t+=k.left;return t}},mi={screen:`${ue}c`};function Rt(e,t){let s=[];for(let i=0;i<=t.length;i++)s[i]=[i];for(let i=0;i<=e.length;i++)s[0][i]=i;for(let i=1;i<=t.length;i++)for(let r=1;r<=e.length;r++)if(t.charAt(i-1)===e.charAt(r-1))s[i][r]=s[i-1][r-1];else s[i][r]=Math.min(s[i-1][r-1]+1,s[i][r-1]+1,s[i-1][r]+1);return s[t.length][e.length]}function Ye(e,t,s=2,i=3){return t.map((r)=>({cmd:r,distance:Rt(e,r)})).filter(({distance:r})=>r<=s).sort((r,o)=>r.distance-o.distance).slice(0,i).map(({cmd:r})=>r)}class Je{rawName;description;name;names;isBoolean;required;config;negated;constructor(e,t,s){if(this.rawName=e,this.description=t,this.config=Object.assign({},s),e=e.replace(/\.\*/g,""),this.negated=!1,this.names=ve(e).split(",").map((i)=>{let r=i.trim().replace(/^-{1,2}/,"");if(r.startsWith("no-"))this.negated=!0,r=r.replace(/^no-/,"");return ze(r)}).sort((i,r)=>i.length>r.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(e.includes("<"))this.required=!0;else if(e.includes("["))this.required=!1;else this.isBoolean=!0}}var fi=we.argv,jt=`${we.platform}-${we.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,Ae=ae.argv,Lt=`${ae.platform}-${ae.arch} node-${ae.version}`;class _e{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor(e,t,s,i){this.rawName=e,this.description=t,this.config=s,this.cli=i,this.options=[],this.aliasNames=[],this.name=ve(e);let r=ve(e),o=r.indexOf(":");if(o>0)this.namespace=r.substring(0,o),this.name=r.substring(o+1);if(this.args=Bt(e),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!s)this.config={}}usage(e){return this.usageText=e,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(e,t="-v, --version"){return this.versionNumber=e,this.option(t,"Display version number"),this}example(e){return this.examples.push(e),this}option(e,t,s){let i=new Je(e,t,s);return this.options.push(i),this}alias(e){return this.aliasNames.push(e),this}action(e){return this.commandAction=e,this}before(e){return this.beforeHooks.push(e),this}after(e){return this.afterHooks.push(e),this}use(e){return this.middleware.push(e),this}isMatched(e){if(this.aliasNames.includes(e))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===e;return this.name===e}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof Ie}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(e){return e=e.split(".")[0],!!this.options.find((t)=>t.names.includes(e))}outputHelp(){let{name:e,commands:t}=this.cli,{versionNumber:s,options:i,helpCallback:r}=this.cli.globalCommand,o=[{body:`${e}${s?`/${s}`:""}`}];if(o.push({title:"Usage",body:` $ ${e} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&t.length>0){let a=Me(t.map((d)=>d.rawName)),c=new Map,h=[];for(let d of t)if(d.namespace){if(!c.has(d.namespace))c.set(d.namespace,[]);c.get(d.namespace).push(d)}else h.push(d);let f="";if(h.length>0)f+=h.map((d)=>` ${pe(d.rawName,a.length)} ${d.description}`).join(`
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{b as a,c as b,d as c,e as d,f as e,g as f}from"./chunk-xjc1fk5y.js";import"./chunk-b369mtka.js";import"./chunk-3j5z4940.js";import"./chunk-awmb5sg5.js";export{c as applyPlugins,a as lintText,f as runLint,b as runLintProgrammatic,e as scanContent,d as scanContentOptimized};
|