@stacksjs/bun-router 0.1.0 → 0.1.2
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/chunk-03m2j6h7.js +2 -0
- package/dist/chunk-08cw7ejr.js +3 -0
- package/dist/chunk-0e4g0fyv.js +62 -0
- package/dist/chunk-0mmn02yw.js +2 -0
- package/dist/chunk-126c9qm3.js +2 -0
- package/dist/chunk-12p13817.js +2 -0
- package/dist/chunk-14v65c37.js +4 -0
- package/dist/{chunk-s3dn1kwx.js → chunk-1b6a7t3v.js} +2 -2
- package/dist/chunk-1wenkmk0.js +2 -0
- package/dist/chunk-2152npfd.js +2 -0
- package/dist/chunk-26w23krx.js +2 -0
- package/dist/chunk-2g8m379z.js +10 -0
- package/dist/{chunk-5mxby3fd.js → chunk-2rr178et.js} +2 -2
- package/dist/chunk-2w8f3swz.js +29 -0
- package/dist/chunk-3y4gaz7v.js +82 -0
- package/dist/chunk-4r1x4afz.js +12 -0
- package/dist/chunk-4wyw66zk.js +2 -0
- package/dist/chunk-4z5sf8ag.js +2 -0
- package/dist/{chunk-krkchy8v.js → chunk-58tfvayh.js} +3 -3
- package/dist/{chunk-ex5fkjah.js → chunk-5dp83qcx.js} +43 -43
- package/dist/chunk-5f0d9j9a.js +2 -0
- package/dist/{chunk-zhx0hxdd.js → chunk-5z52b0fc.js} +7 -7
- package/dist/{chunk-kc659vhx.js → chunk-5zrnk2kq.js} +3 -3
- package/dist/chunk-6dmqtdnq.js +2 -0
- package/dist/{chunk-5s1pr62n.js → chunk-6e91956t.js} +2 -2
- package/dist/{chunk-jrf5a2ap.js → chunk-6rv8w5jk.js} +1 -1
- package/dist/{chunk-5n0ckcmc.js → chunk-6x1feysm.js} +2 -2
- package/dist/chunk-7y72hm1x.js +2 -0
- package/dist/{chunk-zetqzgf3.js → chunk-8hbhfh6b.js} +6 -6
- package/dist/{chunk-5ncn73tp.js → chunk-8kfzygg5.js} +2 -2
- package/dist/chunk-8wydx2we.js +2 -0
- package/dist/chunk-8zjnjvv7.js +2 -0
- package/dist/chunk-988h4bzr.js +2 -0
- package/dist/chunk-9b6a58ac.js +2 -0
- package/dist/chunk-a8fcaywb.js +2 -0
- package/dist/chunk-bfjwn7yg.js +2 -0
- package/dist/chunk-bp2522mm.js +2 -0
- package/dist/chunk-bswe62q4.js +48 -0
- package/dist/chunk-c3v796c8.js +943 -0
- package/dist/chunk-ccqmwdry.js +2 -0
- package/dist/chunk-ck0crwnx.js +2 -0
- package/dist/chunk-cqgkxcb4.js +2 -0
- package/dist/chunk-dntnakjy.js +2 -0
- package/dist/{chunk-67wgad4f.js → chunk-ettdpnrw.js} +2 -2
- package/dist/{chunk-csfrpsp7.js → chunk-ezqwq17j.js} +10 -10
- package/dist/chunk-ezx3qsez.js +2 -0
- package/dist/{chunk-73k79n7q.js → chunk-f72nnjy4.js} +360 -360
- package/dist/chunk-fna5n0ey.js +246 -0
- package/dist/chunk-fqhckdt8.js +2 -0
- package/dist/chunk-fr6hbx25.js +2 -0
- package/dist/{chunk-vr10sbbh.js → chunk-g9cwng6w.js} +1 -1
- package/dist/chunk-gd3za5x0.js +2 -0
- package/dist/chunk-gf28608k.js +2 -0
- package/dist/chunk-h1dj6v8q.js +3 -0
- package/dist/chunk-hjxe7k2g.js +2 -0
- package/dist/chunk-hrkgznbn.js +2 -0
- package/dist/chunk-j6h5v0br.js +2 -0
- package/dist/{chunk-0gjq8ttx.js → chunk-mgb01qdv.js} +2 -2
- package/dist/chunk-n24c9whp.js +2 -0
- package/dist/{chunk-kxp888dn.js → chunk-n2j24b0h.js} +244 -244
- package/dist/{chunk-vv3gb1m5.js → chunk-nhmtg01n.js} +2 -2
- package/dist/chunk-p0qhpnqh.js +70 -0
- package/dist/chunk-p0w1x8y2.js +3 -0
- package/dist/{chunk-9ght4n4r.js → chunk-p3dk1w2w.js} +11 -11
- package/dist/{chunk-6sjvhy5f.js → chunk-q4e9pxs7.js} +2 -2
- package/dist/chunk-q5dv1kyy.js +2 -0
- package/dist/chunk-qnqgf9tq.js +2 -0
- package/dist/chunk-qvwy1808.js +898 -0
- package/dist/{chunk-5s0pnsd6.js → chunk-r18f77vc.js} +4 -4
- package/dist/chunk-r63za1mr.js +2 -0
- package/dist/{chunk-6s1kbajm.js → chunk-rft8gw92.js} +1 -1
- package/dist/chunk-ryvmyskt.js +4211 -0
- package/dist/chunk-sa6mx308.js +2 -0
- package/dist/chunk-va0pc7hx.js +2 -0
- package/dist/chunk-vcp8dnjq.js +412 -0
- package/dist/chunk-vg1erq1q.js +2 -0
- package/dist/{chunk-hmgedrmr.js → chunk-w0jv49ch.js} +3 -3
- package/dist/{chunk-0t5vz87j.js → chunk-wm805tte.js} +19 -19
- package/dist/chunk-xj9h6mc9.js +2 -0
- package/dist/chunk-ytvzwrq3.js +51 -0
- package/dist/{chunk-w4r464v5.js → chunk-zde7ebc4.js} +2 -2
- package/dist/chunk-zmqsv2xy.js +2 -0
- package/dist/cli.js +57 -66
- package/dist/container/index.js +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +29 -29
- package/dist/typed/client.d.ts +89 -0
- package/dist/typed/contract.d.ts +34 -0
- package/dist/typed/endpoint.d.ts +90 -0
- package/dist/typed/index.d.ts +14 -0
- package/dist/typed/router.d.ts +141 -0
- package/package.json +1 -1
- package/dist/chunk-30rkn2ym.js +0 -2
- package/dist/chunk-38cmrard.js +0 -2
- package/dist/chunk-3qna6dwd.js +0 -2
- package/dist/chunk-4d5fmta0.js +0 -2
- package/dist/chunk-4x3b4b4q.js +0 -2
- package/dist/chunk-6xed4va1.js +0 -2
- package/dist/chunk-748n6ydj.js +0 -2
- package/dist/chunk-7rsf8tes.js +0 -898
- package/dist/chunk-8aspmtf1.js +0 -2
- package/dist/chunk-8yfdg595.js +0 -2
- package/dist/chunk-90eze7av.js +0 -3
- package/dist/chunk-9dvwyej7.js +0 -2
- package/dist/chunk-a2w45krb.js +0 -2
- package/dist/chunk-a547f2ab.js +0 -48
- package/dist/chunk-bqdycvtc.js +0 -2
- package/dist/chunk-cd03rk3x.js +0 -2
- package/dist/chunk-ct0m17q5.js +0 -2
- package/dist/chunk-dhbvvr5h.js +0 -2
- package/dist/chunk-dhptcsya.js +0 -943
- package/dist/chunk-dq93zag9.js +0 -2
- package/dist/chunk-edrtesh7.js +0 -2
- package/dist/chunk-ejcws37w.js +0 -2
- package/dist/chunk-ex890p45.js +0 -51
- package/dist/chunk-f69cpnhw.js +0 -2
- package/dist/chunk-fjf53b44.js +0 -2
- package/dist/chunk-fjzye4qj.js +0 -2
- package/dist/chunk-gfd23b6t.js +0 -2
- package/dist/chunk-habv0vef.js +0 -12
- package/dist/chunk-hz6fc788.js +0 -2
- package/dist/chunk-jff6j9y3.js +0 -10
- package/dist/chunk-jmeb7n8k.js +0 -70
- package/dist/chunk-jy2jhcpy.js +0 -246
- package/dist/chunk-m249t3je.js +0 -3
- package/dist/chunk-m9yabnjx.js +0 -2
- package/dist/chunk-mekrq9wd.js +0 -2
- package/dist/chunk-mmxv535f.js +0 -82
- package/dist/chunk-mypn7jss.js +0 -2
- package/dist/chunk-n18x1k3c.js +0 -2
- package/dist/chunk-nkddjzsa.js +0 -2
- package/dist/chunk-pjmhqmr9.js +0 -2
- package/dist/chunk-qyrnsaq1.js +0 -2
- package/dist/chunk-r19ff2qm.js +0 -62
- package/dist/chunk-r338fssq.js +0 -2
- package/dist/chunk-s36z58x2.js +0 -29
- package/dist/chunk-s79dd325.js +0 -471
- package/dist/chunk-ta38j9em.js +0 -2
- package/dist/chunk-tpfgntwj.js +0 -4211
- package/dist/chunk-vw8rwv6e.js +0 -2
- package/dist/chunk-wcrqs5z9.js +0 -2
- package/dist/chunk-x6d1rmwa.js +0 -2
- package/dist/chunk-x7ft15zz.js +0 -2
- package/dist/chunk-x8trwn7j.js +0 -3
- package/dist/chunk-xhepdj1f.js +0 -2
- package/dist/chunk-xv2em0q4.js +0 -4
- package/dist/chunk-ypw6g0te.js +0 -2
- package/dist/chunk-z8szsm21.js +0 -2
- package/dist/chunk-zfbh14qe.js +0 -2
- /package/dist/{chunk-a3wahyg7.js → chunk-nf3kv7kv.js} +0 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Af as k,qf as a,rf as b,sf as c,tf as d,uf as e,vf as f,wf as g,xf as h,yf as i,zf as j}from"./chunk-q4e9pxs7.js";import"./chunk-ryvmyskt.js";import"./chunk-2g8m379z.js";import"./chunk-ezqwq17j.js";import"./chunk-wm805tte.js";import"./chunk-58tfvayh.js";import"./chunk-brpgjyqg.js";import"./chunk-2rr178et.js";import"./chunk-5be9x5cq.js";import"./chunk-5zrnk2kq.js";import"./chunk-p0qhpnqh.js";import"./chunk-nf3kv7kv.js";export{e as __setSignalsGeneratorsForTest,j as cacheTemplate,i as checkCache,h as clearDevCaches,g as getCachedRouterScript,f as getCachedSignalsRuntime,k as hashFilePath,c as invalidateFileCache,d as invalidateFileCacheByDir,b as readFileCached,a as templateCache};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ff as
|
|
2
|
+
import{Ff as v,Gf as _,Hf as i}from"./chunk-e3qej0jr.js";import{fj as x,og as w,pg as g}from"./chunk-ryvmyskt.js";import{Un as S}from"./chunk-brpgjyqg.js";import{Mo as b}from"./chunk-5be9x5cq.js";import l from"path";var c=new Map;function N(a,s){for(let n of a.matchAll(/\b(?:const|let|var|function|class)\s+([A-Z_a-z$][\w$]*)/g))if(n[1])s.add(n[1]);for(let n of a.matchAll(/\b(?:const|let|var)\s*\{([^{}]*)\}\s*=/g))for(let o of(n[1]??"").split(",")){let r=((o.includes(":")?o.split(":").pop():o)??"").replace(/=.*$/s,"").replace(/^\s*\.\.\./,"").trim();if(/^[A-Z_a-z$][\w$]*$/.test(r))s.add(r)}for(let n of a.matchAll(/\b(?:const|let|var)\s*\[([^\]]*)\]\s*=/g))for(let o of(n[1]??"").split(",")){let r=o.replace(/=.*$/s,"").replace(/^\s*\.\.\./,"").trim();if(/^[A-Z_a-z$][\w$]*$/.test(r))s.add(r)}}async function F(a){let s;if(a)s=l.resolve(a);else{let t=await x();s=l.resolve(t.root||process.cwd(),t.storesDir||"stores")}let n=new Bun.Glob("*.ts"),o=[];try{for await(let t of n.scan({cwd:s,absolute:!0})){let e=l.basename(t,".ts");if(["index","types"].includes(e))continue;if(t.includes(".d.ts"))continue;o.push(t)}}catch{return i(c,s,"",""),null}let r=v(o),u=_(c,s,r);if(u!==void 0)return u||null;if(o.length===0)return i(c,s,r,""),null;let f=[];for(let t of o){let e=await Bun.file(t).text();f.push({file:t,hasUseStore:/useStore\s*\(/.test(e)})}f.sort((t,e)=>{if(t.hasUseStore===e.hasUseStore)return 0;return t.hasUseStore?1:-1});let A=f.map((t)=>t.file),p=[],m=new Set,y=new Bun.Transpiler({loader:"ts",target:"browser",define:b()});for(let t of A)try{let e=await Bun.file(t).text(),B=l.basename(t,".ts");N(e,m),e=w(e),e=g(e),e=e.replace(/^export\s+(default\s+)?/gm,""),e=y.transformSync(e),p.push(`// Store: ${B}
|
|
3
3
|
${e.trim()}`)}catch(e){console.warn(`[stx] Failed to load store ${t}:`,e)}if(p.length===0)return i(c,s,r,""),null;let d=p.join(`
|
|
4
4
|
|
|
5
5
|
`),h=`;(function(){
|
|
@@ -7,5 +7,5 @@ var __stx = window.stx || {};
|
|
|
7
7
|
${S.filter((t)=>!m.has(t)&&new RegExp(`\\b${t}\\b`).test(d)).map((t)=>`var ${t} = __stx[${JSON.stringify(t)}];`).join(`
|
|
8
8
|
`)}
|
|
9
9
|
${d}
|
|
10
|
-
})();`;return i(c,s,r,h),h}function
|
|
11
|
-
export{
|
|
10
|
+
})();`;return i(c,s,r,h),h}function I(){c.clear()}
|
|
11
|
+
export{F as Bf,I as Cf};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{In as
|
|
2
|
+
import{In as ue,Kn as fe}from"./chunk-58tfvayh.js";import{Mo as le}from"./chunk-5be9x5cq.js";import T from"path";import W from"process";class Le{source;pos=0;line=1;column=0;tokens=[];constructor(n){this.source=n}tokenize(){this.tokens=[],this.pos=0,this.line=1,this.column=0;while(this.pos<this.source.length){let n=this.nextToken();if(n)this.tokens.push(n)}return this.tokens.push({type:"EOF",value:"",start:this.pos,end:this.pos,line:this.line,column:this.column}),this.tokens}nextToken(){if(this.pos>=this.source.length)return null;let n=this.pos,e=this.line,t=this.column,o=this.source[this.pos];if(/\s/.test(o))return this.readWhitespace(n,e,t);if(o==="/"&&this.peek(1)==="/")return this.readLineComment(n,e,t);if(o==="/"&&this.peek(1)==="*")return this.readBlockComment(n,e,t);if(o==='"'||o==="'")return this.readString(o,n,e,t);if(o==="`")return this.readTemplateString(n,e,t);if(/\d/.test(o)||o==="."&&/\d/.test(this.peek(1)||""))return this.readNumber(n,e,t);if(/[a-z_$]/i.test(o))return this.readIdentifier(n,e,t);if(o==="{"){if(this.peek(1)==="{"&&this.peek(2)==="{")return this.advance(3),{type:"RAW_START",value:"{{{",start:n,end:this.pos,line:e,column:t};if(this.peek(1)==="{")return this.advance(2),{type:"EXPRESSION_START",value:"{{",start:n,end:this.pos,line:e,column:t};if(this.peek(1)==="!"&&this.peek(2)==="!")return this.advance(3),{type:"RAW_START",value:"{!!",start:n,end:this.pos,line:e,column:t}}if(o==="}"){if(this.peek(1)==="}"&&this.peek(2)==="}")return this.advance(3),{type:"RAW_END",value:"}}}",start:n,end:this.pos,line:e,column:t};if(this.peek(1)==="}")return this.advance(2),{type:"EXPRESSION_END",value:"}}",start:n,end:this.pos,line:e,column:t}}if(o==="!"&&this.peek(1)==="!"&&this.peek(2)==="}")return this.advance(3),{type:"RAW_END",value:"!!}",start:n,end:this.pos,line:e,column:t};if(o==="@"&&/[a-z]/i.test(this.peek(1)||""))return this.readDirective(n,e,t);let i=["===","!==","==","!=","<=",">=","&&","||","??","++","--","+=","-=","*=","/=","%=","**","=>","?.","...","<<",">>",">>>","&=","|=","^="];for(let s of i)if(this.source.slice(this.pos,this.pos+s.length)===s)return this.advance(s.length),{type:"OPERATOR",value:s,start:n,end:this.pos,line:e,column:t};if(/[+\-*/%<>=!&|^~?:]/.test(o))return this.advance(),{type:"OPERATOR",value:o,start:n,end:this.pos,line:e,column:t};if(/[()[\]{},;.]/.test(o))return this.advance(),{type:"PUNCTUATION",value:o,start:n,end:this.pos,line:e,column:t};return this.advance(),{type:"PUNCTUATION",value:o,start:n,end:this.pos,line:e,column:t}}readWhitespace(n,e,t){while(this.pos<this.source.length&&/\s/.test(this.source[this.pos]))this.advance();return{type:"WHITESPACE",value:this.source.slice(n,this.pos),start:n,end:this.pos,line:e,column:t}}readLineComment(n,e,t){this.advance(2);while(this.pos<this.source.length&&this.source[this.pos]!==`
|
|
3
3
|
`)this.advance();return{type:"COMMENT",value:this.source.slice(n,this.pos),start:n,end:this.pos,line:e,column:t}}readBlockComment(n,e,t){this.advance(2);while(this.pos<this.source.length-1){if(this.source[this.pos]==="*"&&this.source[this.pos+1]==="/"){this.advance(2);break}this.advance()}return{type:"COMMENT",value:this.source.slice(n,this.pos),start:n,end:this.pos,line:e,column:t}}readString(n,e,t,o){this.advance();while(this.pos<this.source.length){let i=this.source[this.pos];if(i==="\\"){this.advance(2);continue}if(i===n){this.advance();break}this.advance()}return{type:"STRING",value:this.source.slice(e,this.pos),start:e,end:this.pos,line:t,column:o}}readTemplateString(n,e,t){this.advance();let o=0,i=256;while(this.pos<this.source.length){let s=this.source[this.pos];if(s==="\\"){this.advance(2);continue}if(s==="$"&&this.peek(1)==="{"){if(o>=i){this.pos=this.source.length;break}this.advance(2),o++;continue}if(s==="{"&&o>0){o++,this.advance();continue}if(s==="}"&&o>0){o--,this.advance();continue}if(s==="`"&&o===0){this.advance();break}this.advance()}return{type:"TEMPLATE_STRING",value:this.source.slice(n,this.pos),start:n,end:this.pos,line:e,column:t}}readNumber(n,e,t){if(this.source[this.pos]==="0"){let o=this.peek(1)?.toLowerCase();if(o==="x"||o==="o"||o==="b"){this.advance(2);while(this.pos<this.source.length&&/[\da-f_]/i.test(this.source[this.pos]))this.advance();return{type:"NUMBER",value:this.source.slice(n,this.pos),start:n,end:this.pos,line:e,column:t}}}while(this.pos<this.source.length&&/[\d_]/.test(this.source[this.pos]))this.advance();if(this.source[this.pos]==="."&&/\d/.test(this.peek(1)||"")){this.advance();while(this.pos<this.source.length&&/[\d_]/.test(this.source[this.pos]))this.advance()}if(/e/i.test(this.source[this.pos]||"")){if(this.advance(),/[+-]/.test(this.source[this.pos]||""))this.advance();while(this.pos<this.source.length&&/[\d_]/.test(this.source[this.pos]))this.advance()}if(this.source[this.pos]==="n")this.advance();return{type:"NUMBER",value:this.source.slice(n,this.pos),start:n,end:this.pos,line:e,column:t}}readIdentifier(n,e,t){while(this.pos<this.source.length&&/[\w$]/.test(this.source[this.pos]))this.advance();return{type:"IDENTIFIER",value:this.source.slice(n,this.pos),start:n,end:this.pos,line:e,column:t}}readDirective(n,e,t){this.advance();while(this.pos<this.source.length&&/[a-z]/i.test(this.source[this.pos]))this.advance();return{type:"DIRECTIVE",value:this.source.slice(n,this.pos),start:n,end:this.pos,line:e,column:t}}advance(n=1){for(let e=0;e<n&&this.pos<this.source.length;e++){if(this.source[this.pos]===`
|
|
4
|
-
`)this.line++,this.column=0;else this.column++;this.pos++}}peek(n){return this.source[this.pos+n]}saveState(){return{pos:this.pos,line:this.line,column:this.column}}restoreState(n){this.pos=n.pos,this.line=n.line,this.column=n.column}}function
|
|
4
|
+
`)this.line++,this.column=0;else this.column++;this.pos++}}peek(n){return this.source[this.pos+n]}saveState(){return{pos:this.pos,line:this.line,column:this.column}}restoreState(n){this.pos=n.pos,this.line=n.line,this.column=n.column}}function P(n,e,t,o=0){let i=0,s=o,r=null,a=0,c=!1;while(s<n.length){let l=n[s];if(r&&c){c=!1,s++;continue}if(r&&l==="\\"){c=!0,s++;continue}if(c=!1,(l==='"'||l==="'"||l==="`")&&!r){r=l,s++;continue}if(l===r&&r!=="`"){r=null,s++;continue}if(r==="`"&&l==="$"&&n[s+1]==="{"){a++,s+=2;continue}if(a>0&&l==="}"){a--,s++;continue}if(l==="`"&&r==="`"&&a===0){r=null,s++;continue}if(r){s++;continue}if(l===e)i++;else if(l===t){if(i--,i===0)return s}s++}return-1}function lt(n,e){let t=e,o={paren:0,bracket:0,brace:0},i=null,s=0;while(t<n.length){let r=n[t];if((t>0?n[t-1]:"")==="\\"&&i){t++;continue}if((r==='"'||r==="'")&&!i){i=r,t++;continue}if(r===i&&i!=="`"){i=null,t++;continue}if(r==="`"&&!i){i="`",t++;continue}if(r==="`"&&i==="`"&&s===0){i=null,t++;continue}if(i==="`"&&r==="$"&&n[t+1]==="{"){s++,t+=2;continue}if(s>0){if(r==="{")s++;else if(r==="}")s--;t++;continue}if(i){t++;continue}if(o.paren===0&&o.bracket===0&&o.brace===0){if(n.slice(t,t+2)==="}}"||n.slice(t,t+3)==="!!}")break;if(r===","||r===";")break}if(r==="(")o.paren++;else if(r===")"){if(o.paren--,o.paren<0)break}else if(r==="[")o.bracket++;else if(r==="]"){if(o.bracket--,o.bracket<0)break}else if(r==="{")o.brace++;else if(r==="}"){if(o.brace--,o.brace<0)break}t++}return{expression:n.slice(e,t),endPos:t}}function ut(n){let e=[],t="",o={paren:0,bracket:0,brace:0},i=null,s=0;for(let r=0;r<n.length;r++){let a=n[r];if((r>0?n[r-1]:"")==="\\"&&i){t+=a;continue}if((a==='"'||a==="'")&&!i){i=a,t+=a;continue}if(a===i&&i!=="`"){i=null,t+=a;continue}if(a==="`"&&!i){i="`",t+=a;continue}if(a==="`"&&i==="`"&&s===0){i=null,t+=a;continue}if(i==="`"&&a==="$"&&n[r+1]==="{"){s++,t+=a+n[r+1],r++;continue}if(s>0&&a==="{"){s++,t+=a;continue}if(s>0&&a==="}"){s--,t+=a;continue}if(i){t+=a;continue}if(a==="(")o.paren++;else if(a===")")o.paren--;else if(a==="[")o.bracket++;else if(a==="]")o.bracket--;else if(a==="{")o.brace++;else if(a==="}")o.brace--;if(a==="|"&&n[r+1]!=="|"&&(r===0||n[r-1]!=="|")&&n[r-1]!=="\\"&&o.paren===0&&o.bracket===0&&o.brace===0){e.push(t.trim()),t="";continue}if(a==="|"&&n[r-1]==="\\"&&!i){t=t.slice(0,-1)+a;continue}t+=a}if(t.trim())e.push(t.trim());return e}var Be={maxSanitizeDepth:10,allowBracketNotation:!1},K={...Be};var Q=[/\b(eval|Function|setTimeout|setInterval|setImmediate)\b/,/\b(process|require|import|exports|module)\b/,/\b(window|document|global|globalThis)\b/,/\b(constructor|prototype|__proto__)\b/,/\b(Reflect|Proxy)\b/,/\bSymbol\b/,/\b(WeakMap|WeakSet|WeakRef|FinalizationRegistry)\b/,/\b(Generator|AsyncGenerator)\b/,/__\w+__/,/\.(bind|call|apply)\s*\(/,/\bnew\s+/,/\bdelete\s+/,/\bthis\b/],qe=new Set(["eval","Function","setTimeout","setInterval","setImmediate","process","require","import","exports","module","window","document","global","globalThis","constructor","prototype","Reflect","Proxy","Symbol","WeakMap","WeakSet","WeakRef","FinalizationRegistry","Generator","AsyncGenerator","delete","this"]),Y=new Set(["__proto__","constructor","prototype"]),Ue=/[\w)\]]\s*\[\s*['"]/;function ze(n){let e="",t=null,o=!1;for(let i=0;i<n.length;i++){let s=n[i];if(o){o=!1;continue}if(s==="\\"&&t){o=!0;continue}if(t){if(t==="`"&&s==="$"&&i+1<n.length&&n[i+1]==="{"){let r=1;i+=2;while(i<n.length&&r>0){if(n[i]==="{")r++;else if(n[i]==="}")r--;if(r>0)e+=n[i],i++}continue}if(s===t)t=null;continue}if(s==='"'||s==="'"||s==="`"){t=s;continue}e+=s}return e}function Ve(n,e){let t=/[$A-Z_a-z][$\w]*/g,o;while((o=t.exec(n))!==null){let i=o[0],s=n[o.index-1];if(qe.has(i))throw Error(`Potentially unsafe expression (matched /\\b${i}\\b/; identifier ${i}): ${e}`);if(s==="."&&Y.has(i))throw Error(`Potentially unsafe expression (matched /.${i}/; property ${i}): ${e}`)}}function Ge(n){let e=/\[\s*(['"])(.*?)\1\s*\]/g,t;while((t=e.exec(n))!==null){let o=t[2];if(!Y.has(o))continue;let i=n.slice(0,t.index).match(/\S(?=\s*$)/)?.[0],s=n.slice(t.index+t[0].length).match(/^\s*(\S)/)?.[1];if(!((i==="{"||i===",")&&s===":"))throw Error(`Potentially unsafe expression (bracket key ${t[2]}): ${n}`)}}function ee(n){let e=n.trim(),t=ze(e);Ve(t,e),Ge(e);for(let o of Q)if(o.test(t))throw Error(`Potentially unsafe expression (matched /${o.source}/): ${e}`);if(!K.allowBracketNotation&&Ue.test(e))throw Error(`Bracket notation with strings not allowed: ${e}. Enable with configureSafeEvaluator({ allowBracketNotation: true })`);return e}function Ze(n){let e={};e.Math=Math,e.JSON=JSON,e.Date=Date,e.String=String,e.Number=Number,e.Boolean=Boolean,e.Array=Array,e.parseInt=Number.parseInt,e.parseFloat=Number.parseFloat,e.isNaN=Number.isNaN,e.isFinite=Number.isFinite,e.encodeURIComponent=encodeURIComponent,e.decodeURIComponent=decodeURIComponent;for(let[t,o]of Object.entries(n)){if(t.startsWith("__")||Q.some((i)=>i.test(t)))continue;if(o&&typeof o==="object"&&!Array.isArray(o))e[t]=q(o);else e[t]=o}return e}function q(n,e=0){if(e>=K.maxSanitizeDepth)return"[Object too deep]";if(n===null||typeof n!=="object")return n;if(Array.isArray(n))return n.map((o)=>q(o,e+1));if(n instanceof Date||n instanceof RegExp||n instanceof Map||n instanceof Set||n instanceof Error)return n;let t={};for(let[o,i]of Object.entries(n)){if(o.startsWith("__")||o==="constructor"||o==="prototype")continue;if(i&&typeof i==="object")t[o]=q(i,e+1);else t[o]=i}return t}function B(n,e){try{let t=Ze(e),o=Object.keys(t),i=Object.values(t);return Xe(n,o)(...i)}catch{return}}function ht(n){try{return ee(n),!0}catch{return!1}}function pt(n,e){try{let t=B(n,e);if(t&&typeof t==="object"&&!Array.isArray(t))return t;return{}}catch{return{}}}var te=new Set(["break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","import","in","instanceof","new","null","return","super","switch","this","throw","true","try","typeof","var","void","while","with","yield","let","static","implements","interface","package","private","protected","public","arguments","eval","await"]);function Xe(n,e){let t=ee(n),o=/^[A-Za-z_$][\w$]*$/,i=[],s=[];for(let c=0;c<e.length;c++){let l=e[c];if(!o.test(l))continue;if(te.has(l))continue;i.push(c),s.push(l)}let r=(c)=>Function(...s,...c,`
|
|
5
5
|
'use strict';
|
|
6
6
|
try {
|
|
7
7
|
return ${t};
|
|
@@ -12,24 +12,24 @@ catch (e) {
|
|
|
12
12
|
}
|
|
13
13
|
throw e;
|
|
14
14
|
}
|
|
15
|
-
`),a=r([]);if(s.length===e.length)return
|
|
16
|
-
`);for(let i of o){let s=t,r=null,a=!1;for(let c=0;c<i.length;c++){let l=i[c];if(a){a=!1;continue}if(l==="\\"){a=!0;continue}if(r){if(l===r)r=null;continue}if(l==="'"||l==='"'||l==="`"){r=l;continue}if(l==="/"&&c+1<i.length&&i[c+1]==="/")break;if(l==="{")t++;else if(l==="}")t--}if(s===0){let c=i.match(/(?:const|let|var)\s+(\w+)\s*=/);if(c)e.push(c[1]);else if(/^\s*(?:const|let|var)\s+\w+\s*;?\s*$/.test(i)){let l=i.match(/(?:const|let|var)\s+(\w+)/);if(l)e.push(l[1])}else{let l=i.match(/(?:const|let|var)\s+(\{[^}]+\}|\[[^\]]+\])\s*=/);if(l){let u=l[1].slice(1,-1).split(",").map((p)=>{let d=p.split(":");return(d.length>1?d[1]:d[0]).trim()}).filter((p)=>/^\w+$/.test(p));e.push(...u)}}}}return[...new Set(e)]}function
|
|
15
|
+
`),a=r([]);if(s.length===e.length)return H(a,s,r);return H((...c)=>{let l=Array(i.length);for(let u=0;u<i.length;u++)l[u]=c[i[u]];return a(...l)},s,r,(c)=>{a=r(c)})}function H(n,e,t,o){let s=/^(\w+) is not defined$/,r=n,a=[],c=new Set(e);return(...l)=>{for(let u=0;u<=8;u++)try{return r(...l)}catch(p){let d=p instanceof Error?p.message:"",m=s.exec(d);if(!(p instanceof ReferenceError)||!m)return;let g=m[1];if(c.has(g)||te.has(g))return;c.add(g),a.push(g),r=t(a),o?.(a)}return}}function dt(n){let e=n.trim(),t=[/\beval\s*\(/i,/\bFunction\s*\(/i,/\bimport\s*\(/i,/\brequire\s*\(/i,/\bprocess\b/i,/\b__proto__\b/i,/\bconstructor\s*[.(]/i,/\bglobalThis\b/i,/\bwindow\b/i,/\bdocument\b/i,/\bfetch\s*\(/i,/\bBun\b/i,/\bDeno\b/i,/\bconsole\b/i,/\bthis\b/i,/\bReflect\b/i,/\bProxy\b/i,/\bprototype\b/i,/\.(bind|call|apply)\s*\(/i];for(let o of t)if(o.test(e))return!1;return!0}var{require:ne}=import.meta,he=["module","exports","require","props","$props","defineProps","withDefaults","defineClientPayload","state","derived","effect","batch","onMount","onDestroy","definePageMeta","useRoute","useRouter","useHead","useSeoMeta","ref","reactive","computed","watch","onMounted","onUnmounted","nextTick","defineEmits","defineExpose","defineSlots","provide","inject","useColorMode","useDark","useMediaQuery","useScrollLock","usePreferredDark","usePreferredLight","usePreferredReducedMotion","usePreferredContrast","window","document","console","confirm","alert","fetch","params"],ie=new Set(he),Je=new Set(["stx","@stacksjs/stx"]);function He(n){let e=[],t=0,o=n.split(`
|
|
16
|
+
`);for(let i of o){let s=t,r=null,a=!1;for(let c=0;c<i.length;c++){let l=i[c];if(a){a=!1;continue}if(l==="\\"){a=!0;continue}if(r){if(l===r)r=null;continue}if(l==="'"||l==='"'||l==="`"){r=l;continue}if(l==="/"&&c+1<i.length&&i[c+1]==="/")break;if(l==="{")t++;else if(l==="}")t--}if(s===0){let c=i.match(/(?:const|let|var)\s+(\w+)\s*=/);if(c)e.push(c[1]);else if(/^\s*(?:const|let|var)\s+\w+\s*;?\s*$/.test(i)){let l=i.match(/(?:const|let|var)\s+(\w+)/);if(l)e.push(l[1])}else{let l=i.match(/(?:const|let|var)\s+(\{[^}]+\}|\[[^\]]+\])\s*=/);if(l){let u=l[1].slice(1,-1).split(",").map((p)=>{let d=p.split(":");return(d.length>1?d[1]:d[0]).trim()}).filter((p)=>/^\w+$/.test(p));e.push(...u)}}}}return[...new Set(e)]}function Ke(n){let e=n;e=e.replace(/^\s*import\s+.*?from\s+['"][^'"]+['"]\s*;?\s*$/gm,""),e=e.replace(/^\s*import\s+['"][^'"]+['"]\s*;?\s*$/gm,""),e=e.replace(/^\s*interface\s+\w+\s*\{[\s\S]*?\n\}\s*$/gm,""),e=e.replace(/^\s*type\s+\w+\s*=[\s\S]*?(?=\n(?:const|let|var|function|export|interface|type|$))/gm,""),e=e.replace(/^(\s*(?:export\s+)?(?:const|let|var)\s+)(\w+|\{[^}]+\}|\[[^\]]+\])\s*:\s*[^=]+(\s*=)/gm,"$1$2$3");function t(o){if(!o.includes(":"))return o;let i=[],s="",r=0,a=0,c=null;for(let l=0;l<o.length;l++){let u=o[l];if(c){if(s+=u,u===c)c=null;continue}if(u==='"'||u==="'"||u==="`"){c=u,s+=u;continue}if(u==="<")r++;else if(u===">"&&r>0)r--;else if(u==="(")a++;else if(u===")")a--;if(u===","&&r===0&&a===0){i.push(s),s="";continue}s+=u}if(s)i.push(s);return i.map((l)=>{let u=l.trim(),p=u.startsWith("..."),d=p?u.slice(3):u,m=-1,g=0;for(let E=0;E<d.length;E++)if(d[E]==="<")g++;else if(d[E]===">")g--;else if(d[E]===":"&&g===0){m=E;break}if(m===-1)return l;let v=d.substring(0,m).trim().replace(/\?$/,""),S=d.substring(m+1),_=-1,x=0;for(let E=0;E<S.length;E++)if(S[E]==="<")x++;else if(S[E]===">")x--;else if(S[E]==="="&&x===0){_=E;break}let I=p?"...":"";if(_!==-1)return`${I}${v} = ${S.substring(_+1).trim()}`;return`${I}${v}`}).join(", ")}e=e.replace(/\b(function\s+\w*\s*)\(([^)]*)\)/g,(o,i,s)=>{if(!s.includes(":"))return o;return`${i}(${t(s)})`});{let o=/\b(function\s+\w*\s*)\(/g,i,s=[];while((i=o.exec(e))!==null){let r=i.index+i[0].length-1,a=1,c=r+1,l=0,u=null;while(c<e.length&&a>0){let m=e[c];if(u){if(m===u)u=null;c++;continue}if(m==='"'||m==="'"||m==="`"){u=m,c++;continue}if(m==="<")l++;else if(m===">"&&l>0)l--;else if(l===0){if(m==="(")a++;else if(m===")")a--}if(a>0)c++}if(a!==0)continue;let p=e.substring(r+1,c);if(!p.includes(":"))continue;let d=t(p);s.push({start:r+1,end:c,replacement:d})}for(let r=s.length-1;r>=0;r--){let{start:a,end:c,replacement:l}=s[r];e=e.substring(0,a)+l+e.substring(c)}}return e=e.replace(/\(([^)]*)\)\s*(?::\s*[^=]+)?\s*=>/g,(o,i)=>{if(!i.includes(":"))return o;if(i.includes("{")||i.includes("}"))return o;return`(${i.split(",").map((s)=>{let[r,...a]=s.split("="),c=r.split(":")[0].trim();if(a.length>0)return`${c} = ${a.join("=").trim()}`;return c}).join(", ")}) =>`}),e=e.replace(/(\))\s*:\s*([A-Z]\w*|void|string|number|boolean|any|unknown|never|null|undefined)(?:<[^>]+>)?(?:\s*\|\s*(?:[A-Z]\w*|void|string|number|boolean|any|unknown|never|null|undefined))*\s*(\{)/g,"$1$3"),e=e.replace(/(\b(?:function|class|interface|type|extends|implements)\s+\w+)\s*<[^<>()]*>/g,"$1"),e=e.replace(/(\b(?:defineProps|withDefaults|defineEmits|defineSlots|Array|Promise|Map|Set|Record|Partial|Required|Readonly|Pick|Omit|Exclude|Extract))\s*<[^<>()]*>/g,"$1"),e=e.replace(/(\w+)\s*<[A-Z][^<>()]*>\s*(?=\()/g,"$1"),e=e.replace(/\s+as\s+(?:const|[A-Za-z]\w*(?:\[\])?(?:\s*\|\s*\w+(?:\[\])?)*)/g,""),e=e.replace(/\s+satisfies\s+\w+(?:<[^>]*>)?/g,""),e=e.replace(/(\w|\)|\])\s*!(?!=)/g,"$1"),e=e.replace(/^\s*(?:export\s+)?(?:const\s+)?enum\s+\w+\s*\{[^}]*\}\s*$/gm,""),e=e.replace(/(?<=[\s=,(])<[A-Z]\w*(?:\[\])?>/g,""),e=e.replace(/\n\s*\n\s*\n/g,`
|
|
17
17
|
|
|
18
|
-
`),e}function
|
|
19
|
-
`),
|
|
18
|
+
`),e}function Qe(n){return/cannot find module|could not resolve|module not found|failed to resolve/i.test(n)}function Ye(n){if(!/is not defined|can't find variable/i.test(n))return!1;return!/\b(document|window|navigator|localStorage|sessionStorage|self)\b/.test(n)}async function $t(n,e,t,o={}){if(!n.trim())return;let i;try{let f=new Bun.Transpiler({loader:"ts",target:"browser",define:le()}),h=n.replace(/^\s*import\s+\w+\s+from\s+['"][^'"]*\.stx['"]\s*;?\s*$/gm,"");h=h.replace(/^\s*import\s+['"][^'"]*\.stx['"]\s*;?\s*$/gm,""),i=f.transformSync(h)}catch{i=Ke(n)}let s={exports:{}},r=s.exports,a=W.cwd(),c={},l=[...i.matchAll(/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g)||[]].map((f)=>f[1]).filter((f)=>!f.startsWith("node:")&&!f.startsWith(".")&&!["fs","path","os","child_process","crypto","http","https","url","util","stream","events","buffer","net","querystring","zlib","tls"].includes(f));for(let f of l)try{let h=T.resolve(a,"node_modules",f),b=T.join(h,"package.json"),y=JSON.parse(ne("fs").readFileSync(b,"utf8")),k=y.main||"index.js";if(y.exports){let A=typeof y.exports==="string"?y.exports:y.exports["."];if(typeof A==="string")k=A;else if(A?.bun)k=A.bun;else if(A?.import)k=A.import;else if(A?.default)k=A.default}c[f]=await import(T.resolve(h,k))}catch{}let u=(f)=>{if(c[f])return c[f];return ne(f)},p=e.props||{},d=(f)=>{if(!f)return p;let h={};for(let[b,y]of Object.entries(f)){let k=p[b];if(k!==void 0)h[b]=k;else if(typeof y==="function")h[b]=y();else h[b]=y}return h};for(let[f,h]of Object.entries(p))Object.defineProperty(d,f,{value:h,enumerable:!0,configurable:!0,writable:!0});for(let f of["name","length","caller","arguments"]){if(Object.prototype.hasOwnProperty.call(p,f))continue;try{Object.defineProperty(d,f,{value:void 0,enumerable:!1,configurable:!0,writable:!0})}catch{}}let m=(f)=>{if(!f)return p;let h={...p};for(let[b,y]of Object.entries(f)){let k=y&&typeof y==="object"&&!Array.isArray(y)?y:{type:y};if(h[b]===void 0&&k.default!==void 0)h[b]=typeof k.default==="function"?k.default():k.default}return h},g=()=>e.slots||{},v=(f,h)=>{let b={...f};for(let[y,k]of Object.entries(h))if(b[y]===void 0)if(typeof k==="function")b[y]=k();else b[y]=k;return b},S=(f)=>{let h=()=>f;return h.set=(b)=>{},h.update=(b)=>{},h},_=(f)=>{let h,b=!1;return()=>{if(!b)try{h=f(),b=!0}catch{h=void 0}return h}},x=(f)=>{},I=(f)=>f(),E=(f)=>{},C=(f)=>{};function R(f){let h=f||{};if(h.title!==void 0||h.description!==void 0)V({title:h.title,description:h.description})}function N(f){if(!f||typeof f!=="object")return;let h=e.__stxClientPayload??{};Object.assign(h,f),e.__stxClientPayload=h}let D=()=>{let f=e.__stxServeContext,h=e.__stxServeSearch??f?.search??"",b=f?.path??"",y=Object.fromEntries(new URLSearchParams(h)),k=e.query,A=Object.keys(y).length>0?y:k??{},L=h||(Object.keys(A).length>0?`?${new URLSearchParams(A).toString()}`:"");return{params:e.params??{},query:A,path:b,name:"",fullPath:b+L,hash:"",matched:[]}},O=()=>({push:(f)=>{},replace:(f)=>{},back:()=>{},forward:()=>{},go:(f)=>{}}),z=(f)=>{let h=e.__stx_runtime_head||{};e.__stx_runtime_head=ue(h,f||{})},V=(f)=>{z(fe(f||{}))},ve=(f)=>({value:f}),be=(f)=>f,ye=(f)=>({value:typeof f==="function"?f():f}),xe=(f,h)=>{},we=(f)=>{},$e=(f)=>{},Se=(f)=>f?f():Promise.resolve(),ke=(f)=>(h,...b)=>{},_e=(f)=>{},Ee=(f,h)=>{},Ie=(f,h)=>h,Ae=()=>({value:"light"}),Ne=()=>S(!1),M=(f)=>S(!1),Re=()=>S(!1),Ce=()=>M("(prefers-color-scheme: dark)"),Te=()=>M("(prefers-color-scheme: light)"),Pe=()=>M("(prefers-reduced-motion: reduce)"),Oe=()=>M("(prefers-contrast: more)"),F={siteId:void 0,API_ENDPOINT:"",ANALYTICS_SITE_ID:void 0,location:{href:"",pathname:"",search:"",hash:"",origin:"",host:"",hostname:"",protocol:"https:",assign:()=>{},replace:()=>{},reload:()=>{}},localStorage:{getItem:()=>null,setItem:()=>{},removeItem:()=>{},clear:()=>{}},sessionStorage:{getItem:()=>null,setItem:()=>{},removeItem:()=>{},clear:()=>{}},fetch:globalThis.fetch,addEventListener:()=>{},removeEventListener:()=>{},setTimeout:()=>0,clearTimeout:()=>{},setInterval:()=>0,clearInterval:()=>{},requestAnimationFrame:()=>0,cancelAnimationFrame:()=>{},alert:()=>{},confirm:()=>!1,prompt:()=>null,getComputedStyle:()=>({}),matchMedia:()=>({matches:!1,addListener:()=>{},removeListener:()=>{}}),getDateRangeParams:()=>"",stx:{}},We=new Proxy(F,{get(f,h){if(h in f)return f[h];return},set(f,h,b){return f[h]=b,!0}}),De={getElementById:()=>null,querySelector:()=>null,querySelectorAll:()=>[],createElement:()=>({}),createTextNode:()=>({}),body:{},head:{},documentElement:{},addEventListener:()=>{},removeEventListener:()=>{}},Me=console;try{let f=nt(i,t),h=new Set(Object.keys(p)),b=(w)=>/^[a-z_$][\w$]*$/i.test(w),y=Object.keys(e).filter((w)=>!h.has(w)&&w!=="props"&&b(w)),k=y.map((w)=>e[w]);if(!y.includes("__stxServeContext"))y.push("__stxServeContext"),k.push(void 0);let A=new Set(["break","case","catch","class","const","continue","debugger","default","delete","do","else","export","extends","finally","for","function","if","import","in","instanceof","let","new","return","super","switch","this","throw","try","typeof","var","void","while","with","yield","enum","await","async","module","exports","require","params","window","document","console","state","derived","effect"]),L=[],G=[];for(let[w,j]of Object.entries(p)){if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(w))continue;if(A.has(w))continue;if(new RegExp(`(?:^|[\\s;{])(?:const|let|var|function)\\s+${w}\\b`).test(f))continue;L.push(w),G.push(j)}let je=He(f).map((w)=>`module.exports.${w} = typeof ${w} !== 'undefined' ? ${w} : module.exports.${w};`).join(`
|
|
19
|
+
`),Fe=e.params??{},Z=[],X=[];for(let w=0;w<y.length;w++){if(y[w]==="params")continue;Z.push(y[w]),X.push(k[w])}let J=await Function(...he,...L,...Z,`return (async () => {
|
|
20
20
|
${f}
|
|
21
|
-
${
|
|
21
|
+
${je}
|
|
22
22
|
return module.exports
|
|
23
|
-
})()`)(s,r,u,p,d,m,v,
|
|
24
|
-
`),s=[],r=0;while(r<i.length){let a=i[r].trim();if(a.startsWith("interface ")||a.startsWith("export interface ")||a.startsWith("type ")||a.startsWith("export type ")){if(a.includes("{")&&!a.includes("}")){let c=0;for(;r<i.length;r++){for(let l of i[r])if(l==="{")c++;else if(l==="}")c--;if(c<=0)break}}r++;continue}if(a.startsWith("definePageMeta(")){let c=0,l=!1,u=r;for(let m=r;m<i.length&&!l;m++){let g=null,v=!1
|
|
25
|
-
`),d=[];for(let m of["title","description"]){let g=new RegExp(`\\b${m}\\s*:\\s*(['"\`])((?:\\\\.|(?!\\1)[^\\\\])*)\\1`).exec(p);if(g)d.push(`${m}: ${JSON.stringify(g[2])}`)}if(d.length>0)s.push(`useSeoMeta({ ${d.join(", ")} });`);continue}if(a.startsWith("import ")||a==="import"||a.startsWith("import{")){let c=a,l=0;while(!
|
|
26
|
-
`+m;if(p<=0&&d>=r)break}s.push(u),s.push(`module.exports.${l} = ${l};`),r=d+1}else s.push(a),r++}else if(a.includes("module.exports"))s.push(a),r++;else if(a.trim()&&!a.startsWith("//"))s.push(a),r++;else r++}return
|
|
27
|
-
`),t,o)}function
|
|
28
|
-
`)a=!1;s++;continue}if(c){if(i+=u,u==="*"&&p==="/"){i+=p,s+=2,c=!1;continue}s++;continue}if(!r&&u==="/"&&p==="/"){a=!0,i+=u,s++;continue}if(!r&&u==="/"&&p==="*"){c=!0,i+=u,s++;continue}if(r){if(i+=u,u==="\\"){i+=p,s+=2;continue}if(u===r&&r!=="`"){r=null,s++;continue}if(r==="`"){if(u==="$"&&p==="{"){l++,i+=p,s+=2;continue}if(u==="`"){r=null,s++;continue}}s++;continue}if(l>0){if(u==="{")l++;else if(u==="}")l--}if(u==='"'||u==="'"||u==="`"){r=u,i+=u,s++;continue}if(u==="a"&&n.startsWith("await",s)){let d=
|
|
29
|
-
`);return{type:g,name:
|
|
30
|
-
${
|
|
31
|
-
${n[l]}`,l++;else break}return c=c.trim().replace(/;$/,""),{type:s,name:r,value:c,nextIndex:l}}function
|
|
23
|
+
})()`)(s,r,u,p,d,m,v,N,S,_,x,I,E,C,R,D,O,z,V,ve,be,ye,xe,we,$e,Se,ke,_e,g,Ee,Ie,Ae,Ne,M,Re,Ce,Te,Pe,Oe,We,De,Me,F.confirm,F.alert,F.fetch,Fe,...G,...X);if(o.preserveExisting){for(let[w,j]of Object.entries(J))if(!(w in e)||e[w]===void 0)e[w]=j}else Object.assign(e,J);for(let[w,j]of Object.entries(p))if(!(w in e))e[w]=j}catch(f){let h=f instanceof Error?f.message:String(f);if(Qe(h))console.warn(`[stx] server <script> in ${t??"<unknown>"} imports a module that does not resolve, so every variable in that script is undefined. Cause: ${h}`);else if(Ye(h))console.warn(`[stx] server <script> in ${t??"<unknown>"} names something that does not exist, so every variable in that script is undefined. Optional chaining does not help here: an undefined identifier throws before the chain is reached. Cause: ${h}`);else if(W.env.STX_DEBUG)console.warn(`[stx] server <script> did not execute in ${t??"<unknown>"} \u2014 falling back to static extraction. Cause: ${h}`);try{await ct(i,e,t)}catch(b){if(W.env.STX_DEBUG){let y=b instanceof Error?b.message:String(b);console.warn(`[stx] fallback extraction also failed in ${t??"<unknown>"}: ${y}`)}}}}function et(n){let e=0,t=null,o=!1,i=!1;for(let s=0;s<n.length;s++){let r=n[s];if(t){if(r===t){if(t=null,o||e===0)i=!0}continue}if(r==="'"||r==='"'||r==="`"){t=r;continue}if(r==="{")e++;else if(r==="}")e--;else if(n.startsWith("from",s)&&e===0)o=!0}return t===null&&e===0&&i}var tt=/^(?:export\s+)?(?:const|let|var)\s+[A-Za-z_$][\w$]*(?:\s*,\s*[A-Za-z_$][\w$]*)*\s*;?$/;function nt(n,e){let t=e?T.dirname(e):W.cwd(),o=W.cwd(),i=n.split(`
|
|
24
|
+
`),s=[],r=0;while(r<i.length){let a=i[r].trim();if(a.startsWith("interface ")||a.startsWith("export interface ")||a.startsWith("type ")||a.startsWith("export type ")){if(a.includes("{")&&!a.includes("}")){let c=0;for(;r<i.length;r++){for(let l of i[r])if(l==="{")c++;else if(l==="}")c--;if(c<=0)break}}r++;continue}if(a.startsWith("definePageMeta(")){let c=0,l=!1,u=r;for(let m=r;m<i.length&&!l;m++){let g=null,v=!1,S=i[m];for(let _=0;_<S.length;_++){let x=S[_];if(v){v=!1;continue}if(x==="\\"){v=!0;continue}if(g){if(x===g)g=null;continue}if(x==='"'||x==="'"||x==="`"){g=x;continue}if(x==="(")c++;else if(x===")"){if(c--,c===0){r=m+1,l=!0;break}}}}if(!l)r=i.length;let p=i.slice(u,r).join(`
|
|
25
|
+
`),d=[];for(let m of["title","description"]){let g=new RegExp(`\\b${m}\\s*:\\s*(['"\`])((?:\\\\.|(?!\\1)[^\\\\])*)\\1`).exec(p);if(g)d.push(`${m}: ${JSON.stringify(g[2])}`)}if(d.length>0)s.push(`useSeoMeta({ ${d.join(", ")} });`);continue}if(a.startsWith("import ")||a==="import"||a.startsWith("import{")){let c=a,l=0;while(!et(c)&&r+l+1<i.length)l++,c=`${c} ${i[r+l].trim()}`;r+=l;let u=c.match(/^import\s+(\w+)\s+from\s+['"](.+?)['"]/),p=c.match(/^import\s+\{([^}]*)\}\s+from\s+['"](.+?)['"]/),d=c.match(/^import\s+['"](.+?)['"]/),m=c,g=(v)=>{if(v.startsWith("."))return T.resolve(t,v);if(v.startsWith("~/")||v.startsWith("@/"))return T.resolve(o,v.slice(2));return v};if(u){let[,v,S]=u,_=g(S);s.push(`const ${v} = (await import('${_}')).default`),s.push(`module.exports.${v} = ${v};`)}else if(p){let[,v,S]=p,_=g(S),x=[],I=[],E=Je.has(S);for(let C of v.split(",")){let R=C.trim();if(!R)continue;let N=R.split(/\s+as\s+/);if(N.length===2){let[D,O]=[N[0].trim(),N[1].trim()];if(E&&ie.has(D)){s.push(`const ${O} = ${D};`),I.push(O);continue}x.push(`${D}: ${O}`),I.push(O)}else{if(E&&ie.has(R)){I.push(R);continue}x.push(R),I.push(R)}}if(x.length>0)s.push(`const { ${x.join(", ")} } = await import('${_}')`);for(let C of I)s.push(`module.exports.${C} = ${C};`)}else if(d){let v=g(d[1]);s.push(`await import('${v}')`)}else s.push(m);r++;continue}if(tt.test(a))s.push(i[r]),r++;else if(a.startsWith("export const ")||a.startsWith("export let ")||a.startsWith("export var ")){let c=re(i,r),{type:l,name:u,value:p}=c;s.push(`${l} ${u} = ${p};`),s.push(`module.exports.${u} = ${u};`),r=c.nextIndex}else if(a.startsWith("export function ")||a.startsWith("export async function ")){let c=U(i,r);s.push(c.functionCode),s.push(`module.exports.${c.name} = ${c.name};`),r=c.nextIndex}else if(a.startsWith("const ")||a.startsWith("let ")||a.startsWith("var ")){let c=re(i,r),{type:l,name:u,value:p}=c;s.push(`${l} ${u} = ${p};`),s.push(`module.exports.${u} = ${u};`),r=c.nextIndex}else if(a.startsWith("function ")||a.startsWith("async function ")){let c=U(i,r);s.push(c.functionCode),s.push(`module.exports.${c.name} = ${c.name};`),r=c.nextIndex}else if(a.startsWith("export default function ")||a.startsWith("export default async function ")){let c=i[r].replace(/^(\s*)export\s+default\s+/,"$1"),l=[...i];l[r]=c;let u=U(l,r);if(s.push(u.functionCode),u.name)s.push(`module.exports.default = ${u.name};`);r=u.nextIndex}else if(a.startsWith("export default ")){let c=a.replace(/^export\s+default\s+/,"").replace(/;$/,"");s.push(`module.exports.default = ${c};`),r++}else if(a.startsWith("class ")||a.startsWith("export class ")){let c=a.match(/(?:export\s+)?class\s+(\w+)/);if(c){let l=c[1],u=i[r].replace(/^export\s+/,""),p=0,d=r;for(;d<i.length;d++){let m=i[d];for(let g of m)if(g==="{")p++;else if(g==="}")p--;if(d>r)u+=`
|
|
26
|
+
`+m;if(p<=0&&d>=r)break}s.push(u),s.push(`module.exports.${l} = ${l};`),r=d+1}else s.push(a),r++}else if(a.includes("module.exports"))s.push(a),r++;else if(a.trim()&&!a.startsWith("//"))s.push(a),r++;else r++}return it(s.join(`
|
|
27
|
+
`),t,o)}function it(n,e,t){let o=n.length,i="",s=0,r=null,a=!1,c=!1,l=0;while(s<o){let u=n[s],p=n[s+1];if(a){if(i+=u,u===`
|
|
28
|
+
`)a=!1;s++;continue}if(c){if(i+=u,u==="*"&&p==="/"){i+=p,s+=2,c=!1;continue}s++;continue}if(!r&&u==="/"&&p==="/"){a=!0,i+=u,s++;continue}if(!r&&u==="/"&&p==="*"){c=!0,i+=u,s++;continue}if(r){if(i+=u,u==="\\"){i+=p,s+=2;continue}if(u===r&&r!=="`"){r=null,s++;continue}if(r==="`"){if(u==="$"&&p==="{"){l++,i+=p,s+=2;continue}if(u==="`"){r=null,s++;continue}}s++;continue}if(l>0){if(u==="{")l++;else if(u==="}")l--}if(u==='"'||u==="'"||u==="`"){r=u,i+=u,s++;continue}if(u==="a"&&n.startsWith("await",s)){let d=st(n,s);if(d){let{quote:m,path:g,end:v}=d;if(g.startsWith(".")||g.startsWith("~/")||g.startsWith("@/")){let S=g.startsWith(".")?T.resolve(e,g):T.resolve(t,g.slice(2));i+=`await import(${m}${S}${m})`,s=v;continue}}}i+=u,s++}return i}function st(n,e){let t=e+5;if(t>=n.length)return null;if(!/\s/.test(n[t]))return null;while(t<n.length&&/\s/.test(n[t]))t++;if(!n.startsWith("import",t))return null;t+=6;while(t<n.length&&/\s/.test(n[t]))t++;if(n[t]!=="(")return null;t++;while(t<n.length&&/\s/.test(n[t]))t++;let o=n[t];if(o!=="'"&&o!=='"')return null;t++;let i=t;while(t<n.length&&n[t]!==o)if(n[t]==="\\")t+=2;else t++;if(t>=n.length)return null;let s=n.slice(i,t);t++;while(t<n.length&&/\s/.test(n[t]))t++;if(n[t]!==")")return null;return{quote:o,path:s,end:t+1}}function pe(n,e){let t=n[e];if(t!=="{"&&t!=="[")return null;let o=P(n,t,t==="{"?"}":"]",e);if(o===-1)return null;return{pattern:n.slice(e,o+1),endPos:o+1}}function de(n){let e=[],t=n.slice(1,-1).trim();if(!t)return e;let o=0,i=0,s="";while(o<t.length){let r=t[o];if(r==="{"||r==="["){let a=i===0?pe(t,o):null;if(a){e.push(...de(a.pattern)),o=a.endPos,s="";continue}i++}else if(r==="}"||r==="]")i--;if(i>0){o++;continue}if(r===","){if(s.trim())e.push(s.trim());s="",o++;continue}if(r===":"){s="",o++;continue}if(r==="="){if(s.trim())e.push(s.trim());s="",o++;while(o<t.length&&t[o]!==","&&i===0){if(t[o]==="{"||t[o]==="[")i++;else if(t[o]==="}"||t[o]==="]")i--;o++}continue}if(/[\w$]/.test(r))s+=r;o++}if(s.trim())e.push(s.trim());return e}function rt(n){let e=/^(?:export\s+)?(const|let|var)\s+([A-Za-z_$][\w$]*)/.exec(n);if(!e)return null;let t=e[0].length,o=(i)=>i===" "||i==="\t";while(t<n.length&&o(n[t]))t++;if(n[t]===":"){let i=0,s=null;t++;for(;t<n.length;t++){let r=n[t];if(s){if(r==="\\"){t++;continue}if(r===s)s=null;continue}if(r==="'"||r==='"'||r==="`"){s=r;continue}if(r==="("||r==="["||r==="{"||r==="<"){i++;continue}if(r===")"||r==="]"||r==="}"||r===">"){i--;continue}if(r==="="&&i<=0){let a=n[t+1],c=n[t-1];if(a!=="="&&a!==">"&&c!=="="&&c!=="!"&&c!=="<"&&c!==">")break}}if(n[t]!=="=")return null}while(t<n.length&&o(n[t]))t++;if(n[t]!=="=")return null;return{type:e[1],name:e[2],value:n.slice(t+1).trim()}}function se(n,e,t,o){let i=null,s=!1;for(let r of n){if(s){s=!1;continue}if(r==="\\"){s=!0;continue}if(i){if(r===i)i=null;continue}if(r==="'"||r==='"'||r==="`"){i=r;continue}if(r===e)o++;else if(r===t)o--}return o}function re(n,e){let t=n[e].trim(),o=rt(t),i=o?[t,o.type,o.name,o.value]:null;if(!i){let u=t.match(/^(?:export\s+)?(const|let|var)\s+/);if(u){let p=t.slice(u[0].length),d=e;if(p.startsWith("{")||p.startsWith("[")){let g=p[0],v=g==="{"?"}":"]",S=se(p,g,v,0),_=p;for(let x=e+1;x<n.length&&S>0;x++)_+=` ${n[x].trim()}`,d=x,S=se(n[x],g,v,S);if(S>0)_=p,d=e;p=_}let m=pe(p,0);if(m){let g=u[1],v=m.pattern,S=p.slice(m.endPos).trim();if(S.startsWith("=")){let _=S.slice(1).trim(),x=_,I=Math.max(d,e);if(oe(_)){let N=ae(n,I,_);x=N.value,I=N.nextIndex}else I=I+1;x=x.trim().replace(/;$/,"");let E=de(v),C=`__stx_src_${e}`,R=E.map((N)=>`module.exports.${N} = ${N};`).join(`
|
|
29
|
+
`);return{type:g,name:C,value:`${x}; ${g} ${v} = ${C};
|
|
30
|
+
${R}`,nextIndex:I}}}}throw Error(`Failed to parse variable declaration: ${t}`)}let[,s,r,a]=i,c=a,l=e;if(oe(a)){let u=ae(n,e,a);c=u.value,l=u.nextIndex}else l=e+1;while(l<n.length){let u=n[l].trim();if(u.startsWith(".")||u.startsWith("?."))c+=`
|
|
31
|
+
${n[l]}`,l++;else break}return c=c.trim().replace(/;$/,""),{type:s,name:r,value:c,nextIndex:l}}function U(n,e){let t=n[e].trim(),o=t.match(/^(?:export\s+)?(?:async\s+)?function\s+(\w+)/);if(!o)throw Error(`Failed to parse function declaration: ${t}`);let[,i]=o,s=t.replace(/^export\s+/,""),r=e;if(ot(t)){let a=at(n,e,s);s=a.functionCode,r=a.nextIndex}else r=e+1;return{name:i,functionCode:s,nextIndex:r}}function oe(n){let e=n.trim();if(e.startsWith("{"))return P(e,"{","}",0)===-1;if(e.startsWith("["))return P(e,"[","]",0)===-1;return!me(e)}function me(n){let e={paren:0,bracket:0,brace:0},t=null,o=0;for(let i=0;i<n.length;i++){let s=n[i];if((i>0?n[i-1]:"")==="\\"&&t)continue;if((s==='"'||s==="'")&&!t){t=s;continue}if(s===t&&t!=="`"){t=null;continue}if(s==="`"&&!t){t="`";continue}if(s==="`"&&t==="`"&&o===0){t=null;continue}if(t==="`"&&s==="$"&&n[i+1]==="{"){o++,i++;continue}if(o>0&&s==="{"){o++;continue}if(o>0&&s==="}"){o--;continue}if(t)continue;if(s==="(")e.paren++;else if(s===")")e.paren--;else if(s==="[")e.bracket++;else if(s==="]")e.bracket--;else if(s==="{")e.brace++;else if(s==="}")e.brace--}return e.paren===0&&e.bracket===0&&e.brace===0&&t===null}function ge(n){let e=n.indexOf("(");if(e===-1)return n.indexOf("{");let t=P(n,"(",")",e);if(t===-1)return-1;return n.indexOf("{",t)}function ot(n){let e=ge(n);if(e===-1)return!0;return P(n,"{","}",e)===-1}function ae(n,e,t){let o=t,i=e+1;while(i<n.length&&!me(o)){let s=n[i];o+=`
|
|
32
32
|
${s}`,i++}while(i<n.length){let s=n[i].trim();if(s.startsWith(".")||s.startsWith("?."))o+=`
|
|
33
|
-
${n[i]}`,i++;else break}return{value:o,nextIndex:i}}function
|
|
34
|
-
${r}`,i++}return{functionCode:o,nextIndex:i}}function
|
|
35
|
-
export{
|
|
33
|
+
${n[i]}`,i++;else break}return{value:o,nextIndex:i}}function at(n,e,t){let o=t,i=e+1;while(i<n.length){let s=ge(o);if(s!==-1){if(P(o,"{","}",s)!==-1)break}let r=n[i];o+=`
|
|
34
|
+
${r}`,i++}return{functionCode:o,nextIndex:i}}function ce(n,e){let t=B(n,e)??B(`(${n})`,e);if(t!==void 0)return t;if(!/\bprocess\b/.test(n))return;let o={...e,process:Object.freeze({env:{...W.env}})};try{return Function(...Object.keys(o),`'use strict'; return (${n});`)(...Object.values(o))}catch{try{return Function(...Object.keys(o),`'use strict'; return ${n};`)(...Object.values(o))}catch{return}}}async function ct(n,e,t){let o=n.matchAll(/export\s+(const|let|var)\s+(\w+)\s*=\s*([\s\S]*?)(?=\s*(?:export\s+|$))/g);for(let s of o){let[,,r,a]=s;try{let c=a.trim().replace(/;$/,""),l=ce(c,e);if(l!==void 0)e[r]=l}catch(c){console.warn(`Failed to parse export ${r} in fallback:`,c)}}let i=n.matchAll(/(?:^|\n)\s*(const|let|var)\s+(\w+)\s*=\s*([\s\S]*?)(?=\s*(?:(?:const|let|var|function|export)\s+|$))/g);for(let s of i){let[,,r,a]=s;if(!(r in e))try{let c=a.trim().replace(/;$/,""),l=ce(c,e);if(l!==void 0)e[r]=l}catch{}}}function St(n){let e=n.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),t=e?e[1]:"",o=e?n.replace(/<script\b[^>]*>[\s\S]*?<\/script>/i,""):n;return{scriptContent:t,templateWithoutScript:o}}function kt(n){let e=n.trim();if(!e)return!1;return/(?:const|let|var|function)\s+\w+/.test(e)}
|
|
35
|
+
export{ee as kn,B as ln,ht as mn,pt as nn,Xe as on,dt as pn,Le as qn,P as rn,lt as sn,ut as tn,he as un,Ke as vn,Qe as wn,Ye as xn,$t as yn,et as zn,nt as An,rt as Bn,St as Cn,kt as Dn};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{jm as a,km as b,lm as c,mm as d,nm as e,om as f,pm as g,qm as h,rm as i,sm as j,tm as k}from"./chunk-ryvmyskt.js";import"./chunk-2g8m379z.js";import"./chunk-ezqwq17j.js";import"./chunk-wm805tte.js";import"./chunk-58tfvayh.js";import"./chunk-brpgjyqg.js";import"./chunk-2rr178et.js";import"./chunk-5be9x5cq.js";import"./chunk-5zrnk2kq.js";import"./chunk-p0qhpnqh.js";import"./chunk-nf3kv7kv.js";export{d as convertSignalDirectivesToAttributes,f as convertSignalLoopsToAttributes,h as extractExports,j as findMarkupIndexOutsideScripts,c as hasSignalsSyntax,b as parseLoopExpression,e as preEvalLiteralReactiveIfs,g as processScriptSetup,i as processSignals,k as rewriteStxImportSpecifiers,a as scanScriptTags};
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Zu as I}from"./chunk-nf3kv7kv.js";import{existsSync as Be,statSync as $e}from"fs";import{join as St,relative as Tt,resolve as _e}from"path";import J from"process";import{Buffer as S}from"buffer";import{createCipheriv as Ot,createDecipheriv as Ft,randomBytes as oe}from"crypto";import{closeSync as le,createReadStream as Ie,createWriteStream as Nt,existsSync as Y,fsyncSync as We,openSync as Ue,writeFileSync as jt}from"fs";import{access as kt,constants as Ze,mkdir as Pt,readdir as z,rename as Ve,stat as k,unlink as H,writeFile as ce}from"fs/promises";import{isAbsolute as Rt,join as P,resolve as Dt}from"path";import p from"process";import{pipeline as Mt}from"stream/promises";import{createGzip as Ke}from"zlib";import R from"process";import T from"process";import G from"process";import{existsSync as q}from"fs";import{resolve as fe}from"path";import{existsSync as Lt}from"fs";import{existsSync as ye,mkdirSync as Bt,readdirSync as $t,readFileSync as _t,writeFileSync as It}from"fs";import{homedir as D}from"os";import{dirname as Ye,resolve as E}from"path";import j from"process";import{existsSync as Wt,readdirSync as Ut}from"fs";import{extname as ue,resolve as ze}from"path";import Zt from"process";import{basename as Pr,extname as Rr,join as Dr,relative as Mr,resolve as et,sep as Lr}from"path";import{pathToFileURL as Br}from"url";import{mkdir as tt,writeFile as Ur}from"fs/promises";import{dirname as Zr,join as Vr}from"path";import{mkdir as Kr,writeFile as Yr}from"fs/promises";import{dirname as zr,isAbsolute as Hr,relative as Gr}from"path";import qr from"process";import{mkdir as Te,writeFile as Oe}from"fs/promises";import{dirname as re,isAbsolute as Xr,relative as Qr,sep as Jr}from"path";var Vt=Object.defineProperty,Kt=(e)=>e;function Yt(e,t){this[e]=Kt.bind(null,t)}var zt=(e,t)=>{for(var r in t)Vt(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Yt.bind(t,r)})},F=(e,t)=>()=>(e&&(t=e(e=0)),t),Ht=import.meta.require;class Fe{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],[,i])=>r.timestamp.getTime()-i.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,i){if(!this.options.enabled)return;let n=this.generateKey(e,r),a=i??this.options.ttl,s=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:a,hits:0,size:s}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!Be(e))return!0;return $e(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,i){try{let n=Be(r)?$e(r):null,a=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:a},r,i)}catch{this.set(e,t,r,i)}}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((i,n)=>i+n.size,0),r=e.map((i)=>i.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 i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class Ne{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let a=await t(),s=performance.now()-i;return this.recordMetric({operation:e,duration:s,timestamp:n,...r}),a}catch(a){let s=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:s,timestamp:n,...r}),a}}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((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,a)=>n+a,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Gt(e,t={}){let r=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return r?`${e}:${r}`:e}function qt(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Xt(e){return e.getStats().size*2}var M,V,rt,K=F(()=>{M=new Fe,V=new Ne,rt={createKey:Gt,isEquivalent:qt,estimateMemoryUsage:Xt}});function Qt(e,t={}){let r=J.cwd();while(r.includes("storage"))r=_e(r,"..");let i=_e(r,e||"");if(t?.relative)return Tt(J.cwd(),i);return i}function w(){if(T.env.NODE_ENV==="test"||T.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Jt(){if(T.env.NODE_ENV==="test"||T.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof T<"u"){let e=T.type;if(e==="renderer"||e==="worker")return!1;return!!(T.versions&&(T.versions.node||T.versions.bun))}return!1}class it{async format(e){let t=await Jt(),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:R.pid,hostname:t(),environment:R.env.NODE_ENV||"development",platform:R.platform,version:R.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:R.env.NODE_ENV||R.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class ie{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...W},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new it,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??p.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),a=this.generateKey();this.currentKeyId=n,this.keys.set(n,a),this.encryptionKeys.set(n,{key:a,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Q,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Q};return{...Q,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:W.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!w()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let i,n=0,a=3,s=1000;while(n<a)try{try{try{await kt(this.config.logDirectory,Ze.F_OK|Ze.W_OK)}catch(o){if(o instanceof Error&&"code"in o)if(o.code==="ENOENT")await Pt(this.config.logDirectory,{recursive:!0,mode:493});else if(o.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw o;else throw o}}catch(o){throw console.error("Debug: [writeToFile] Failed to create log directory:",o),o}let l=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:S.from(e);try{if(!Y(this.currentLogFile))await ce(this.currentLogFile,"",{mode:420});if(i=Ue(this.currentLogFile,"a",420),jt(i,l,{flag:"a"}),We(i),i!==void 0)le(i),i=void 0;if((await k(this.currentLogFile)).size===0){if(await ce(this.currentLogFile,l,{flag:"w",mode:420}),(await k(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(o){let c=o;if(c.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(c.code)){if(n<a-1){let f=typeof c.message==="string"?c.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${a}:`,f);let u=s*2**n;await new Promise((h)=>setTimeout(h,u)),n++;continue}}if(c?.code&&["ENOSPC","EDQUOT"].includes(c.code))throw Error(`Disk quota exceeded or no space left on device: ${c.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",c),c}finally{if(i!==void 0)try{le(i)}catch(o){console.error("Debug: [writeToFile] Error closing file descriptor:",o)}}}catch(l){if(n===a-1){let c=l,f=typeof c.message==="string"?c.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),l}n++;let o=s*2**(n-1);await new Promise((c)=>setTimeout(c,o))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return P(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 P(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return P(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(w())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,s],[,l])=>l.createdAt.getTime()-s.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,a=Math.max(1,n);if(i.length>a)for(let[s]of i.slice(a))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return oe(16).toString("hex")}generateKey(){return oe(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=oe(16),i=Ot("aes-256-gcm",t,r),n=S.isBuffer(e)?e:S.from(e,"utf8"),a=i.update(n),s=i.final(),l=a.length+s.length,o=i.getAuthTag(),c=S.allocUnsafe(16+l+16);return r.copy(c,0),a.copy(c,16),s.copy(c,16+a.length),o.copy(c,16+l),{encrypted:c,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=Ke(),n=[];i.on("data",(a)=>n.push(a)),i.on("end",()=>t(S.from(S.concat(n)))),i.on("error",r),i.write(e),i.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(w())return;if(!this.shouldWriteToFile())return;let e=await k(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,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await z(this.config.logDirectory),a=n.filter((o)=>o.startsWith(this.name)&&/\.log\.\d+$/.test(o)).sort((o,c)=>{let f=Number.parseInt(o.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),s=a.length>0?Number.parseInt(a[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${r}.${s}`;if(await k(r).catch(()=>null))try{if(await Ve(r,l),t.compress)try{let o=`${l}.gz`;await this.compressLogFile(l,o),await H(l)}catch(o){console.error("Error compressing rotated file:",o)}if(a.length===0&&!n.some((o)=>o.endsWith(".log.1")))try{let o=`${r}.1`;await ce(o,"")}catch(o){console.error("Error creating backup file:",o)}}catch(o){console.error(`Error during rotation: ${o instanceof Error?o.message:String(o)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),a=r.replace(/\.log$/,`-${n}.log`);if(await k(r).catch(()=>null))await Ve(r,a)}if(this.currentLogFile=i,t.maxFiles){let n=(await z(this.config.logDirectory)).filter((a)=>a.startsWith(this.name)).sort((a,s)=>s.localeCompare(a));for(let a of n.slice(t.maxFiles))await H(P(this.config.logDirectory,a))}}}async compressLogFile(e,t){let r=Ie(e),i=Nt(t),n=Ke();await Mt(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Y(this.currentLogFile))try{let e=Ue(this.currentLogFile,"r+");We(e),le(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(!w()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await z(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await H(P(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?m.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||w())return!1;let e=typeof p.env.NO_COLOR<"u",t=p.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof p.stderr<"u"&&p.stderr.isTTY||typeof p.stdout<"u"&&p.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:a,showTimestamp:s=!0}=e,l=(g)=>g.replace(this.ANSI_PATTERN,"");if(!this.fancy){let g=[];if(s)g.push(t);if(a==="warning")g.push("WARN");else if(a==="error")g.push("ERROR");else if(r)g.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)g.push(i.replace(/[[\]]/g,""));return g.push(n),g.join(" ")}let o=p.stdout.columns||120,c="";if(a==="warning"||a==="error")c=`${r} ${n}`;else if(a==="info"||a==="success")c=`${r} ${i} ${n}`;else c=`${r} ${i} ${m.cyan(n)}`;if(!s)return c.trim();let f=l(c).trim().length,u=l(t).length,h=Math.max(1,o-2-f-u);return`${c.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(a,s)=>{let l=Number.parseInt(s,10);return l<t[0].length?String(t[0][l]):a});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(a,s)=>{if(s==="%")return"%";if(i>=t.length)return a;let l=t[i++];switch(s){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return a}});if(i<t.length)n+=` ${t.slice(i).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let a=m.underline(m.blue(i)),s=this.toAbsoluteFilePath(n);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(s)}`,o="\x1B]8;;",c="\x1B\\";return`\x1B]8;;${l}\x1B\\${a}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${a}\x1B]8;;\x1B\\`;return a}),t=t.replace(/`([^`]+)`/g,(r,i)=>m.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>m.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>m.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>m.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>m.strikethrough(i)),t}supportsHyperlinks(){if(w())return!1;let e=p.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=p.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(Rt(t)||t.startsWith("./")||t.startsWith("../"))t=Dt(t);else return null;return Y(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let i=new Date,n=this.formatConsoleTimestamp(i),a=this.formatFileTimestamp(i),s,l;if(t instanceof Error)s=t.message,l=t.stack;else s=this.formatMessage(t,r);let{consoleText:o,fileText:c}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":nt[e],h=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",g;switch(e){case"debug":g=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:m.gray(o),level:e}),console.error(g);break;case"info":g=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:o,level:e}),console.warn(g);break;case"success":g=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:m.green(o),level:e}),console.error(g);break;case"warning":g=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:o,level:e}),console.warn(g);break;case"error":if(g=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:o,level:e}),console.error(g),l){let b=l.split(`
|
|
3
|
+
`);for(let d of b)if(d.trim()&&!d.includes(s))console.error(this.formatConsoleMessage({timestamp:n,message:m.gray(` ${d}`),level:e,showTimestamp:!1}))}break}}else if(!w()){if(console.error(`${a} ${this.environment}.${e.toUpperCase()}: ${s}`),l)console.error(l)}let f=`${a} ${this.environment}.${e.toUpperCase()}: ${c}
|
|
4
|
+
`;if(l)f+=`${l}
|
|
5
|
+
`;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(e,t=""){let r={update:(n,a)=>{},finish:(n)=>{},interrupt:(n,a)=>{}};if(!this.enabled)return r;let i=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!w()&&p.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(n,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,n),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!w()&&p.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(n)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,n)},interrupt:(n,a="info")=>{if(!w()&&p.stdout.isTTY)p.stdout.write(`
|
|
6
|
+
`);if(this[a==="warning"?"warn":a](n),this.activeProgressBar&&this.shouldStyleConsole()&&!w()&&p.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":m.blue("\u25D0"),tag:r,message:`${m.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),a=`${e} completed in ${n}ms`,s=new Date,l=this.formatConsoleTimestamp(s),o=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${a}`;if(r)o+=` ${JSON.stringify(r)}`;if(o+=`
|
|
7
|
+
`,o=o.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":m.green("\u2713"),tag:c,message:`${a}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!w())console.error(o.trim());if(this.shouldWriteToFile())await this.writeToFile(o)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new ie(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(w())throw Error("createReadStream is not supported in browser environments");if(!Y(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ie(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let i=S.isBuffer(e)?e:S.from(e,"base64"),n=i.subarray(0,16),a=i.subarray(i.length-16),s=i.subarray(16,i.length-16),l=Ft("aes-256-gcm",r,n);l.setAuthTag(a);let o=l.update(s),c=l.final(),f=o.length+c.length,u=S.allocUnsafe(f);return o.copy(u,0),c.copy(u,o.length),u.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return w()}isServerMode(){return!w()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t),{consoleText:n,fileText:a}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let l=n.split(`
|
|
8
|
+
`),o=Math.max(...l.map((h)=>h.length))+2,c=`\u250C${"\u2500".repeat(o)}\u2510`,f=`\u2514${"\u2500".repeat(o)}\u2518`,u=l.map((h)=>this.formatConsoleMessage({timestamp:r,message:m.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:m.cyan(c),showTimestamp:!1})),u.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:m.cyan(f),showTimestamp:!1}))}else if(!w())console.error(`${i} ${this.environment}.INFO: [BOX] ${a}`);let s=`${i} ${this.environment}.INFO: [BOX] ${a}
|
|
9
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(e){if(w())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${m.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();p.stdin.removeListener("data",r);try{if(typeof p.stdin.setRawMode==="function")p.stdin.setRawMode(!1)}catch{}p.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof p.stdin.setRawMode==="function")p.stdin.setRawMode(!0)}catch{}p.stdin.resume(),p.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let s=/%([sdijfo%])/g,l=0;if(r=e.replace(s,(o,c)=>{if(c==="%")return"%";if(l>=t.length)return o;let f=t[l++];switch(c){case"s":return String(f);case"d":case"i":return Number(f).toString();case"j":case"o":return JSON.stringify(f,null,2);default:return o}}),l<t.length)r+=` ${t.slice(l).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`}let{consoleText:i,fileText:n}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${m.blue("\u25D0")} `;console.error(`${l}${s} ${m.cyan(i)}`)}let a=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
10
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!p.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,a=m.green("\u2501".repeat(i)),s=m.gray("\u2501".repeat(n)),l=`[${a}${s}]`,o=`${r}%`.padStart(4),c=e.message?` ${e.message}`:"",f=this.options.showIcons===!1?"":t||r===100?m.green("\u2713"):m.blue("\u25B6"),u=this.options.showTags!==!1&&this.name?` ${m.gray(this.formatTag(this.name))}`:"",h=`\r${f}${u} ${l} ${o}${c}`,g=p.stdout.columns||80,b=" ".repeat(Math.max(0,g-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${b}`,p.stdout.write(e.lastRenderedLine),t)p.stdout.write(`
|
|
11
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||w()||!p.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(w()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await z(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let n=P(this.config.logDirectory,i);if(e.before)try{if((await k(n)).mtime>=e.before)continue}catch(a){console.error(`Failed to get stats for file ${n}:`,a);continue}r.push(n)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await H(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var He,he,W,er,v,m,tr,Ge,rr,qe,ir,nr,ge,ar,Xe,Qe,sr,me,or,lr,cr,fr,ur,Q,nt,hr,gr=F(()=>{He=J.env.CLARITY_LOG_DIR||St(Qt(),"logs"),he={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:He,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},W={...he},er=(async()=>{try{let{loadConfig:e}=await Promise.resolve().then(()=>(wt(),yt)),t=await e({name:"clarity",alias:"logging",defaultConfig:he,cwd:J.cwd()});if(t)Object.assign(W,t)}catch{}return W})(),v={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},m=v,tr=v.red,Ge=v.green,rr=v.yellow,qe=v.blue,ir=v.magenta,nr=v.cyan,ge=v.white,ar=v.gray,Xe=v.bgRed,Qe=v.bgYellow,sr=v.bgGray,me=v.bold,or=v.dim,lr=v.italic,cr=v.underline,fr=v.strikethrough,ur=v.reset,Q={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},nt={debug:"\uD83D\uDD0D",info:qe("\u2139"),success:Ge("\u2713"),warning:Qe(ge(me(" WARN "))),error:Xe(ge(me(" ERROR ")))},hr=new ie("stacks")}),mr="0.15.9",pr=()=>{};async function at(e,t={}){let{maxRetries:r=3,retryDelay:i=1000,isRetryable:n=()=>!0,fallback:a}=t,s=Error("Unknown error occurred");for(let l=0;l<=r;l++)try{return await e()}catch(o){if(s=o instanceof Error?o:Error(String(o)),l===r||!n(s))break;if(i>0)await new Promise((c)=>setTimeout(c,i))}if(a!==void 0)return a;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}function st(e){return e instanceof C}function dr(e){return e instanceof ee}function yr(e){if(st(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((t)=>e.message.toLowerCase().includes(t.toLowerCase()))}var C,ee,U,we,ve,te,be,Ee,Z,Ce,xe,N,L=F(()=>{C=class extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}},ee=class extends C{code="CONFIG_NOT_FOUND";constructor(e,t,r){let i=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],n="";if(i.length===1)n=` or alias "${i[0]}"`;else if(i.length>1)n=` or aliases ${i.map((a)=>`"${a}"`).join(", ")}`;super(`Configuration "${e}"${n} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}},U=class extends C{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},we=class extends C{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},ve=class extends C{code="CONFIG_MERGE_ERROR";constructor(e,t,r,i){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}},te=class extends C{code="ENV_VAR_ERROR";constructor(e,t,r,i){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:i})}},be=class extends C{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Ee=class extends C{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Z=class extends C{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Ce=class extends C{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,i){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:i})}},xe=class extends C{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}},N={configNotFound(e,t,r){return new ee(e,t,r)},configLoad(e,t,r){return new U(e,t,r)},configValidation(e,t,r){return new we(e,t,r)},configMerge(e,t,r,i){return new ve(e,t,r,i)},envVar(e,t,r,i){return new te(e,t,r,i)},fileSystem(e,t,r){return new be(e,t,r)},typeGeneration(e,t,r){return new Ee(e,t,r)},schemaValidation(e,t,r){return new Z(e,t,r)},browserConfig(e,t,r,i){return new Ce(e,t,r,i)},plugin(e,t,r){return new xe(e,t,r)}}});class ne{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:i,useCamelCase:n=!0,useBackwardCompatibility:a=!0,customParsers:s={},verbose:l=!1,trackPerformance:o=!0}=r,c=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let f=i||this.generateEnvPrefix(e),u={...t};return this.processObject(u,[],f,{useCamelCase:n,useBackwardCompatibility:a,customParsers:s,verbose:l,configName:e}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(o)return V.track("applyEnvironmentVariables",c,{configName:e});return c()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,i){for(let[n,a]of Object.entries(e)){let s=[...t,n],l=s.map((f)=>this.formatEnvKey(f,i.useCamelCase)),o=`${r}_${l.join("_")}`,c=i.useBackwardCompatibility?`${r}_${s.map((f)=>f.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof a==="object"&&a!==null&&!Array.isArray(a))this.processObject(a,s,r,i);else{let f=G.env[o]||(c?G.env[c]:void 0);if(f!==void 0){if(i.verbose){let u=G.env[o]?o:c}try{e[n]=this.parseEnvironmentValue(f,typeof a,o,i.customParsers,i.configName)}catch(u){if(u instanceof te)throw u;throw N.envVar(o,f,typeof a,i.configName)}}}}}parseEnvironmentValue(e,t,r,i,n){for(let[a,s]of Object.entries(i))try{return s(e)}catch{continue}for(let a of this.defaultParsers)if(a.canParse(e,t))try{return a.parse(e)}catch{throw N.envVar(r,e,`${t} (via ${a.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[i,n]of Object.entries(G.env))if(i.startsWith(r)&&n!==void 0)t[i]=n;return t}validateEnvironmentVariable(e,t,r){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))i.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(n){i.push(`Cannot parse value "${t}" as ${r}: ${n}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(e,t,r={}){let{prefix:i,format:n="text"}=r,a=i||this.generateEnvPrefix(e),s=[];switch(this.extractEnvVarInfo(t,[],a,s),n){case"markdown":return this.formatAsMarkdown(s,e);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,e)}}extractEnvVarInfo(e,t,r,i){for(let[n,a]of Object.entries(e)){let s=[...t,n],l=`${r}_${s.map((o)=>this.formatEnvKey(o,!0)).join("_")}`;if(typeof a==="object"&&a!==null&&!Array.isArray(a))this.extractEnvVarInfo(a,s,r,i);else i.push({key:l,type:Array.isArray(a)?"array":typeof a,description:`Configuration for ${s.join(".")}`,example:this.generateExample(a)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
12
|
+
|
|
13
|
+
`;for(let i of e)r+=`${i.key}
|
|
14
|
+
`,r+=` Type: ${i.type}
|
|
15
|
+
`,r+=` Description: ${i.description}
|
|
16
|
+
`,r+=` Example: ${i.example}
|
|
17
|
+
|
|
18
|
+
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
19
|
+
|
|
20
|
+
`;r+=`| Variable | Type | Description | Example |
|
|
21
|
+
`,r+=`|----------|------|-------------|----------|
|
|
22
|
+
`;for(let i of e)r+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
|
|
23
|
+
`;return r}}var ot=F(()=>{K(),L()});function wr(e,t){let r=Ht("process");if(typeof r>"u"||!r.env)return t;let i=r.env[e];return i!==void 0?i:t}function lt(e,t,r={}){return ct(e,t,r,new WeakMap)}function ct(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:a=!1,customMerger:s}=r;if(t===null||t===void 0)return a?e:t;if(s){let l=s(e,t);if(l!==void 0)return l}if(Array.isArray(t)||Array.isArray(e))return ft(e,t,n,i);if(!A(t)||!A(e))return t;return Cr(e,t,r,i)}function ft(e,t,r,i){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 vr(e,t);case"smart":return br(e,t,i);default:return t}return t}function vr(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Ae(n,i)))r.push(i);return r}function br(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(A(t[0])&&A(e[0]))return Er(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function Er(e,t,r){let i=[...t];for(let n of e){if(!A(n)){i.push(n);continue}let a=["id","name","key","path","type"],s=!1;for(let l of a)if(l in n){if(i.find((o)=>A(o)&&(l in o)&&o[l]===n[l])){s=!0;break}}if(!s)i.push(n)}return i}function Cr(e,t,r,i){let n=t;if(A(n)&&i.has(n))return i.get(n);let a={...e};if(A(n))i.set(n,a);for(let s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;let l=n[s],o=a[s];if(r.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){a[s]=l;continue}if(A(l)&&A(o))a[s]=ct(o,l,r,i);else if(Array.isArray(l)||Array.isArray(o))a[s]=ft(o,l,r.arrayMergeMode||"smart",i);else a[s]=l}return a}function je(e,t,r="replace"){return lt(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Ae(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(!Ae(e[r],t[r]))return!1;return!0}if(A(e)&&A(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Ae(e[n],t[n]))return!1}return!0}return!1}function A(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}var ut,ke=F(()=>{ut={replace:"replace",concat:"concat",smart:"smart"}});class ae{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:a,trackPerformance:s=!0,verbose:l=!1}=r;if(n){let c=M.getWithFileCheck("file",e);if(c){if(l)console.log(`Configuration loaded from cache: ${e}`);return c}}let o=async()=>{if(!q(e))return null;try{let c=`?t=${Date.now()}`,f=await import(e+c),u=f.default||f,h="default"in f,g=Object.keys(f).length>0;if(!h&&!g)throw new U(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new U(e,Error("Configuration must export a valid object"),"unknown");let b={config:je(t,u,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)M.setWithFileCheck("file",b,e,a);return b}catch(c){throw c instanceof Error?N.configLoad(e,c):N.configLoad(e,Error(String(c)))}};if(s)return V.track("loadFromPath",o,{path:e});return o()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let a of i)for(let s of this.extensions)n.push(fe(t,`${a}${s}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let i=t===void 0?[]:Array.isArray(t)?t:[t];for(let a of i){if(!a)continue;if(r.push(a,`.${a}.config`,`${a}.config`,`.${a}`),e)r.push(`${e}.${a}.config`,`.${e}.${a}.config`)}let n=new Set;return r.filter((a)=>{if(!a||n.has(a))return!1;return n.add(a),!0})}checkFileAccess(e){return at(async()=>q(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!q(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let a of n)for(let s of this.extensions){let l=fe(e,`${a}${s}`);if(await this.checkFileAccess(l))i.push(l)}}else try{let{readdirSync:n}=await import("fs"),a=n(e);for(let s of a)if(this.looksLikeConfigFile(s)){let l=fe(e,s);if(await this.checkFileAccess(l))i.push(l)}}catch{return[]}return i}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!q(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),a=n(e,"utf8");JSON.parse(a)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}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(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}var ht=F(()=>{K(),L(),ke()});class Pe{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:a=!0,customRules:s=[],trackPerformance:l=!0,verbose:o=!1}=r,c=async()=>{let f=[],u=[],h={stopOnFirstError:i,validateRequired:n,validateTypes:a,customRules:s,trackPerformance:l,verbose:o};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...s],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(l)return await V.track("validateConfiguration",c);return c()}async validateWithSchemaFile(e,t,r){try{if(!Lt(t))throw new Z(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new Z(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,a){if(a.validateTypes&&t.type){let s=Array.isArray(e)?"array":typeof e,l=Array.isArray(t.type)?t.type:[t.type];if(!l.includes(s)){if(i.push({path:r,message:`Expected type ${l.join(" or ")}, got ${s}`,expected:l.join(" or "),actual:s,rule:"type"}),a.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),a.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)i.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)i.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))i.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)i.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)i.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 s=0;s<e.length;s++){let l=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,l,i,n,a),a.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let s=e;if(a.validateRequired&&t.required){for(let l of t.required)if(!(l in s)){if(i.push({path:r?`${r}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),a.stopOnFirstError)return}}if(t.properties){for(let[l,o]of Object.entries(t.properties))if(l in s){let c=r?`${r}.${l}`:l;if(this.validateObjectAgainstSchema(s[l],o,c,i,n,a),a.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let l=new Set(Object.keys(t.properties||{}));for(let o of Object.keys(s))if(!l.has(o))n.push({path:r?`${r}.${o}`:o,message:`Additional property '${o}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let a of t)try{let s=this.getValueByPath(e,a.path),l=this.validateWithRule(s,a,a.path);if(i.push(...l),r.stopOnFirstError&&i.length>0)break}catch(s){i.push({path:a.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))i.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))i.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 n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,a,s]=i;t.push({path:n,required:!a,type:this.mapTypeScriptType(s)})}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:gt},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var gt,mt=F(()=>{K(),L(),gt=/^https?:\/\//});function xr(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 Re{fileLoader=new ae;envProcessor=new ne;validator=new Pe;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:a,...s}=e;try{if(r?.enabled){let o=this.checkCache(s.name||"",s);if(o)return o}let l;try{l=await this.loadConfigurationStrategies(s,!0,r)}catch(o){let c=s.__strictErrorHandling;if(o instanceof Error&&o.name==="ConfigNotFoundError"){if(c)throw o;l={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(o instanceof Error&&o.name==="ConfigLoadError"){let f=o.message.includes("EACCES")||o.message.includes("EPERM")||o.message.includes("permission denied"),u=!f&&(o.message.includes("syntax")||o.message.includes("Expected")||o.message.includes("Unexpected")||o.message.includes("BuildMessage")||o.message.includes("errors building")),h=o.message.includes("Configuration must export a valid object")||o.message.includes("Configuration file is empty and exports nothing");if(c&&(h||f))throw o;if(u&&(!c||!h))l={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!c)l={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${o.message}`]};else throw o}else l={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${o instanceof Error?o.message:String(o)}`]}}if(n||a)await this.validateConfiguration(l.config,n,a,s.name);if(r?.enabled&&l)this.cacheResult(s.name||"",l,r,s);if(i?.enabled){let o={operation:"loadConfig",duration:Date.now()-t,configName:s.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(o);if(i.slowThreshold&&o.duration>i.slowThreshold)x.warn(`Slow configuration loading detected: ${o.duration}ms for ${s.name}`);l.metrics=o}return l}catch(l){let o=Date.now()-t;throw x.error(`Configuration loading failed after ${o}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:a,configDir:s,defaultConfig:l,checkEnv:o=!0,arrayStrategy:c="replace",verbose:f=!1}=e,u=a||j.cwd(),h=[],g=await this.loadLocalConfiguration(i,n,u,s,l,c,f,o,r);if(g)return h.push(...this.getLocalSearchPaths(i,n,u,s)),this.finalizeResult(g,h,o,i,f);let b=await this.loadHomeConfiguration(i,n,l,c,f,o);if(b)return h.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(b,h,o,i,f);let d=await this.loadPackageJsonConfiguration(i,n,u,l,c,f,o);if(d)return h.push(E(u,"package.json")),this.finalizeResult(d,h,o,i,f);if(h.push(...this.getAllSearchPaths(i,n,u,s)),t)throw N.configNotFound(i,h,n);return{...await this.applyEnvironmentVariables(i,l,o,f),warnings:[`No configuration file found for "${i}"${xr(n)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,a,s,l,o){let c=l?_(e,n,s):n,f=this.getLocalDirectories(r,i);for(let u of f){if(s)x.info(`Searching for configuration in: ${u}`);let h=this.fileLoader.generateConfigPaths(e,u,t),g=await this.fileLoader.tryLoadFromPaths(h,c,{arrayStrategy:a,verbose:s,cacheTtl:o?.ttl,useCache:!o?.ttl||o.ttl>100});if(g){if(s)x.success(`Configuration loaded from: ${g.source.path}`);return g}}return null}async loadHomeConfiguration(e,t,r,i,n,a){if(!e)return null;let s=a?_(e,r,n):r,l=[E(D(),".config",e),E(D(),".config"),D()];for(let o of l){if(n)x.info(`Checking home directory: ${o}`);let c=this.fileLoader.generateConfigPaths(e,o,t),f=await this.fileLoader.tryLoadFromPaths(c,s,{arrayStrategy:i,verbose:n});if(f){if(n)x.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,a,s){let l=s?_(e,i,a):i;try{let o=E(r,"package.json");if(!ye(o))return null;let c={};try{c=JSON.parse(_t(o,"utf8"))}catch(h){if(a)x.warn("Failed to parse package.json:",[h instanceof Error?h:Error(String(h))]);return null}let f=c[e],u=e;if(!f&&t){let h=Array.isArray(t)?t:[t];for(let g of h){if(!g)continue;if(c[g]){f=c[g],u=g;break}}}if(f&&typeof f==="object"&&!Array.isArray(f)){if(a)x.success(`Configuration loaded from package.json: ${u}`);return{config:je(l,f,n),source:{type:"package.json",path:o,priority:30,timestamp:new Date}}}}catch(o){if(a)x.warn("Failed to load package.json:",[o instanceof Error?o:Error(String(o))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:_(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let a=r(e);if(a)n.push(...a)}if(t){let a=await this.validator.validateConfiguration(e,t);if(!a.isValid)n.push(...a.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(n.length>0)throw N.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return M.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);M.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let i=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${i}`)}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,E(e,"config"),E(e,".config"),t?E(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(E(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),a=[];for(let s of n)a.push(...this.fileLoader.generateConfigPaths(e,s,t));return a}getHomeSearchPaths(e,t){if(!e)return[];let r=[E(D(),".config",e),E(D(),".config"),D()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}function Je(e){let t=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),r=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return t||r}async function Ar(e){return O.loadConfig({...e,__strictErrorHandling:!0})}async function De(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 i;if(r)i=await O.loadConfig(e);else i=await O.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??t}catch(i){let n=i instanceof Error?i.name:"UnknownError",a=i instanceof Error?i.message:String(i);if(!(n==="ConfigNotFoundError"||n==="ConfigLoadError"||n==="ConfigValidationError"||a.includes("config"))&&e.verbose)x.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let s=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await O.applyEnvironmentVariables(s.name||"",t,!0,s.verbose||!1))?.config??t;return t}}async function Sr(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await O.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&Je(r)))return(await O.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await O.loadConfig({...e,cwd:e.cwd||j.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Je(t)))return(await O.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Tr(e,t,r="replace"){let i=new ae;try{let n=await i.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return n?n.config:null}catch{return null}}function _(e,t,r=!1){let i=new ne,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function a(s,l=[]){let o={...s};for(let[c,f]of Object.entries(s)){let u=[...l,c],h=[`${n}_${u.join("_").toUpperCase()}`,`${n}_${u.map((d)=>d.toUpperCase()).join("")}`,`${n}_${u.map((d)=>d.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],g,b;for(let d of h)if(g=j.env[d],g!==void 0){b=d;break}if(g!==void 0&&b)if(typeof f==="boolean")o[c]=["true","1","yes"].includes(g.toLowerCase());else if(typeof f==="number"){let d=Number(g);if(!Number.isNaN(d))o[c]=d}else if(Array.isArray(f))try{o[c]=JSON.parse(g)}catch{o[c]=g.split(",").map((d)=>d.trim())}else o[c]=g;else if(f&&typeof f==="object"&&!Array.isArray(f))o[c]=a(f,u)}return o}return a(t)}function Or(e){let t=E(j.cwd(),e.configDir),r=E(j.cwd(),e.generatedDir),i=E(r,"config-types.ts");if(!ye(Ye(i)))Bt(Ye(i),{recursive:!0,mode:511});let n=ye(t)?$t(t).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],a=`// Generated by bunfig v${mr}
|
|
24
|
+
export type ConfigNames = ${n.length?`'${n.join("' | '")}'`:"string"}
|
|
25
|
+
`;It(i,a,{mode:438})}function Fr(e){let t=null,r=null,i=()=>{if(!r)r=De(e).then((a)=>(t=a,a),(a)=>{let s="defaultConfig"in e?e.defaultConfig:{};if(t=s,"verbose"in e&&e.verbose)x.warn("Config loading failed, using defaults:",[a instanceof Error?a:Error(String(a))]);return s});return r},n="defaultConfig"in e?e.defaultConfig:{};return t=n,i(),new Proxy({},{get(a,s){if(t)return t[s];let l=n[s];return i(),l},has(a,s){return s in(t||n)},ownKeys(){return Object.keys(t||n)},getOwnPropertyDescriptor(a,s){return Object.getOwnPropertyDescriptor(t||n,s)},set(a,s,l){if(!t)t={...n};return t[s]=l,!0}})}var x,O,pt,dt,Nr=F(()=>{gr(),pr(),K(),L(),ot(),ht(),mt(),ke(),x=new ie("bunfig",{showTags:!0}),O=new Re,pt=E(j.cwd(),"config"),dt=E(j.cwd(),"src/generated")});function jr(e){let t=ze(Zt.cwd(),e?.configDir||"./config");function r(){if(!Wt(t))return[];let n=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),a=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],s=Ut(t).filter((o)=>n.has(ue(o))).map((o)=>({base:o.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:o})),l=new Map;for(let{base:o,file:c}of s){let f=ue(c).toLowerCase(),u=l.get(o);if(!u){l.set(o,c);continue}let h=ue(u).toLowerCase();if(a.indexOf(f)<a.indexOf(h))l.set(o,c)}return Array.from(l.entries()).map(([o,c])=>({base:o,file:c})).sort((o,c)=>o.base.localeCompare(c.base))}function i(){let n=r(),a=n.map((o)=>o.base),s=a.length?a.map((o)=>`'${o}'`).join(" | "):"string",l=n.length?`{
|
|
26
|
+
${n.map((o)=>{let c=ze(t,o.file).replace(/\\/g,"/");return` '${o.base}': typeof import('${c}').default`}).join(`,
|
|
27
|
+
`)}
|
|
28
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${s}
|
|
29
|
+
export type ConfigByName = ${l}
|
|
30
|
+
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
31
|
+
export type ConfigOf = Config
|
|
32
|
+
`}return{name:"bunfig-plugin",setup(n){n.onResolve({filter:/^virtual:bunfig-types$/},(a)=>({path:a.path,namespace:"bunfig-virtual"})),n.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:i(),loader:"ts"}))}}}var kr=()=>{},yt={};zt(yt,{withErrorRecovery:()=>at,tryLoadConfig:()=>Tr,loadConfigWithResult:()=>Ar,loadConfig:()=>De,isRetryableError:()=>yr,isConfigNotFoundError:()=>dr,isBunfigError:()=>st,globalPerformanceMonitor:()=>V,globalCache:()=>M,getEnvOrDefault:()=>wr,generateConfigTypes:()=>Or,defaultGeneratedDir:()=>dt,defaultConfigDir:()=>pt,deepMergeWithArrayStrategy:()=>je,deepMerge:()=>lt,createLibraryConfig:()=>Fr,config:()=>Sr,bunfigPlugin:()=>jr,applyEnvVarsToConfig:()=>_,TypeGenerationError:()=>Ee,SchemaValidationError:()=>Z,PluginError:()=>xe,PerformanceMonitor:()=>Ne,FileSystemError:()=>be,ErrorFactory:()=>N,EnvVarError:()=>te,EnvProcessor:()=>ne,ConfigValidator:()=>Pe,ConfigValidationError:()=>we,ConfigNotFoundError:()=>ee,ConfigMergeError:()=>ve,ConfigLoader:()=>Re,ConfigLoadError:()=>U,ConfigFileLoader:()=>ae,ConfigCache:()=>Fe,CacheUtils:()=>rt,BunfigError:()=>C,BrowserConfigError:()=>Ce,ArrayMergeStrategies:()=>ut});var wt=F(()=>{Nr(),L(),K(),L(),kr(),ot(),ht(),mt(),ke()});wt();var vt={translationsDir:"locales",defaultLocale:"en",fallbackLocale:void 0,include:void 0,verbose:!1,outDir:"dist/i18n",typesOutFile:"dist/i18n/keys.d.ts",sources:["ts"]},pe=null;async function Ti(){if(!pe)pe=await De({name:"i18n",defaultConfig:vt});return pe}var Oi=vt;async function $r(e,t){let r=[];for(let i of e){let n=new Bun.Glob(i);for await(let a of n.scan({dot:t.dot??!1}))r.push(a)}return r}async function _r(e){let t=await(e.startsWith("file://")?import(e):import(Br(e).href));return t&&(t.default??t.translations??t)}function bt(e){return e!=null&&typeof e==="object"&&!Array.isArray(e)}function Et(e,t){let r={...e};for(let i of Object.keys(t)){let n=t[i];if(bt(n)){let a=r[i]&&typeof r[i]==="object"?r[i]:{};r[i]=Et(a,n)}else r[i]=n}return r}function Ir(e,t,r){let i=e;for(let n=0;n<t.length-1;n++){let a=t[n];if(!i[a]||typeof i[a]!=="object")i[a]={};i=i[a]}i[t[t.length-1]]=r}function Wr(e){let t=[];if(e.includes("yaml"))t.push("**/*.yml","**/*.yaml");if(e.includes("ts"))t.push("**/*.ts","**/*.js");if(e.includes("json"))t.push("**/*.json");return t}async function ji(e){if(typeof e.translationsDir!=="string"||e.translationsDir.trim().length===0)throw Error("ts-i18n: translationsDir must be a non-empty string");let t=et(e.translationsDir),r=(e.include??Wr(e.sources??["ts"])).map((s)=>Dr(t,s)),i=(await $r(r,{dot:!1})).map((s)=>et(s));if(!i.length){if(e.optional)return{};throw Error(`ts-i18n: No translation files found under ${t}. Looked for ${r.join(", ")}. If this is a fresh scaffold, add a sample file or pass \`optional: true\`.`)}let n=await Promise.all(i.map(async(s)=>{let l=Rr(s).toLowerCase(),o=l===".yml"||l===".yaml",c=l===".ts"||l===".js",f=l===".json",u;if(o)try{let y=await Bun.file(s).text(),B=Bun.YAML.parse(y);u=B==null?{}:B}catch(y){throw Error(`ts-i18n: Failed to parse YAML file ${s}: ${y?.message??y}`)}else if(f)try{let y=await Bun.file(s).text();u=y.trim().length===0?{}:JSON.parse(y)}catch(y){throw Error(`ts-i18n: Failed to parse JSON file ${s}: ${y?.message??y}`)}else if(c)try{let y=await _r(s);u=y.default??y}catch(y){throw Error(`ts-i18n: Failed to import TS translation module ${s}: ${y?.message??y}`)}if(!bt(u))throw Error(`ts-i18n: Translation file must export an object. File: ${s}`);let h=Mr(t,s).split(Lr),g=h[0],b=h.slice(1);if(b.length===0)g=Pr(g,l);if(!g)throw Error(`ts-i18n: Could not infer locale from file path: ${s}`);let d=u,se={};if(b.length===0)se=d;else{let y=b.join("/").replace(l,"").split("/").filter(Boolean),B=y[y.length-1],Me=d;if(d&&typeof d==="object"&&!Array.isArray(d)&&Object.keys(d).length===1&&Object.prototype.hasOwnProperty.call(d,B))Me=d[B];let Le={};Ir(Le,y,Me),se=Le}return{locale:g,container:se}})),a={};for(let{locale:s,container:l}of n){if(!a[s])a[s]={};a[s]=Et(a[s],l)}return a}function Ct(e){if(e==null||typeof e!=="object")return e;let t=Array.isArray(e)?[]:{};for(let[r,i]of Object.entries(e)){if(typeof i==="function")continue;if(i&&typeof i==="object")t[r]=Ct(i);else t[r]=i}return t}async function Ri(e,t){await tt(t,{recursive:!0});let r=[];for(let[i,n]of Object.entries(e)){let a=Vr(t,`${i}.json`),s=Ct(n),l=JSON.stringify(s,null,2);await tt(Zr(a),{recursive:!0}),await Ur(a,l,"utf8"),r.push(a)}return r}function Se(e){if(typeof e==="string")return JSON.stringify(e);if(typeof e==="number"||typeof e==="boolean")return String(e);if(e==null)return"undefined";if(Array.isArray(e))return`[${e.map((t)=>Se(t)).join(", ")}]`;if(typeof e==="object")return`{ ${Object.entries(e).map(([t,r])=>`${JSON.stringify(t)}: ${Se(r)}`).join(", ")} }`;return"undefined"}function de(e){if(!e)return e;return Hr(e)?Gr(qr.cwd(),e):e}async function Bi(e,t=".config/i18n.config.ts"){let r={...e,translationsDir:de(e.translationsDir),outDir:de(e.outDir),typesOutFile:de(e.typesOutFile)},i=`// ts-i18n configuration sample
|
|
33
|
+
// Update values as needed for your project
|
|
34
|
+
|
|
35
|
+
export default ${Se(r)}
|
|
36
|
+
`;return await Kr(zr(t),{recursive:!0}),await Yr(t,i,"utf8"),t}function xt(e,t=""){let r={};for(let[i,n]of Object.entries(e)){let a=t?`${t}.${i}`:i;if(n==null)continue;if(typeof n==="function"||typeof n==="string"||typeof n==="number"||typeof n==="boolean")r[a]=n;else if(n&&typeof n==="object"&&!Array.isArray(n))Object.assign(r,xt(n,a))}return r}function X(e,t){if(!e.includes(t))e.push(t)}function $i(e,t){let{defaultLocale:r,fallbackLocale:i}=t,n={};for(let[s,l]of Object.entries(e))n[s]=xt(l);function a(s,l,o){let c=[];if(l)X(c,l);if(X(c,r),i)if(Array.isArray(i))for(let f of i)X(c,f);else X(c,i);for(let f of c){let u=n[f];if(!u)continue;let h=u[s];if(h==null)continue;if(typeof h==="function")return h(o);if(typeof h==="string"||typeof h==="number"||typeof h==="boolean")return String(h)}return s}return function(s,l,o){let c,f;if(typeof l==="string")c=l,f=o;else f=l;return a(s,c,f)??s}}function At(e,t=""){let r=[];for(let[i,n]of Object.entries(e)){let a=t?`${t}.${i}`:i;if(n&&typeof n==="object"&&!Array.isArray(n))r.push(...At(n,a));else r.push(a)}return r}async function Wi(e,t){let r=Object.keys(e);if(r.length===0){await Te(re(t),{recursive:!0}),await Oe(t,`export type TranslationKey = string
|
|
37
|
+
`);return}let i=r[0],n=e[i],a=`export type TranslationKey = ${At(n).sort().map((s)=>JSON.stringify(s)).join(" | ")}
|
|
38
|
+
`;await Te(re(t),{recursive:!0}),await Oe(t,a)}async function Ui(e,t,r){let i=ei(e,t),n=`// Auto-generated by ts-i18n. Do not edit.
|
|
39
|
+
import type { DotPaths, ParamsForKey, TranslatorFor } from 'ts-i18n'
|
|
40
|
+
import * as Mod from ${ti(i)}
|
|
41
|
+
|
|
42
|
+
type Base = (
|
|
43
|
+
Mod extends { default: infer D } ? D :
|
|
44
|
+
Mod extends { translations: infer T } ? T :
|
|
45
|
+
Mod
|
|
46
|
+
) extends infer X ? X : never
|
|
47
|
+
|
|
48
|
+
export type TranslationKey = DotPaths<Base>
|
|
49
|
+
export type ParamsFor<K extends TranslationKey> = ParamsForKey<Base, K>
|
|
50
|
+
export type TypedTranslator = TranslatorFor<Base>
|
|
51
|
+
`;await Te(re(t),{recursive:!0}),await Oe(t,n)}function ei(e,t){if(!Xr(e))return e;let r=Qr(re(t),e).split(Jr).join("/");if(!r.startsWith("."))r=`./${r}`;return r}function ti(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`}export{Oi as config,$i as createTranslator,vt as defaultConfig,Bi as generateSampleConfig,Wi as generateTypes,Ui as generateTypesFromModule,Ti as getConfig,ji as loadTranslations,Ri as writeOutputs};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./chunk-
|
|
2
|
+
import"./chunk-nf3kv7kv.js";function r(){return`<script data-stx-scoped data-stx-x-element-runtime data-stx-run="always">
|
|
3
3
|
(function() {
|
|
4
4
|
'use strict';
|
|
5
5
|
|
|
@@ -285,4 +285,4 @@ else {
|
|
|
285
285
|
})();
|
|
286
286
|
</script>`}function l(t){return/\bx-data(?:\s|=)/.test(t)}function c(t){let a=/<script\b(?=[^>]*\bdata-stx-x-element-runtime\b)[^>]*>[\s\S]*?<\/script>\s*/gi,n=t.match(a)||[],e=n.length>0?t.replace(a,""):t;if(!l(e))return e;let s=n[0]?.trim()||r(),i=e.lastIndexOf("</body>");if(i!==-1)return e.slice(0,i)+s+`
|
|
287
287
|
`+e.slice(i);return e+`
|
|
288
|
-
`+s}export{
|
|
288
|
+
`+s}export{r as generateXElementRuntime,l as hasXElementDirectives,c as processXElementDirectives};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Au as g,Bu as h,Cu as i,Du as j,Eu as k,uu as a,vu as b,wu as c,xu as d,yu as e,zu as f}from"./chunk-2w8f3swz.js";import"./chunk-6x1feysm.js";import"./chunk-nf3kv7kv.js";export{a as VideoProcessorCache,j as analyzeVideo,d as clearVideoCache,i as generateDASHManifest,h as generateHLSManifest,e as generatePoster,g as generateSpriteSheet,f as generateThumbnails,b as getCachedVideoResult,k as processVideo,c as setCachedVideoResult};
|