@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
package/dist/cli.js
CHANGED
|
@@ -1,95 +1,86 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import{
|
|
3
|
+
import{Zp as fe}from"./chunk-vcp8dnjq.js";import"./chunk-p0qhpnqh.js";import"./chunk-nf3kv7kv.js";import v from"process";import{existsSync as _e}from"fs";import U from"fs/promises";import se from"os";import H from"path";import S from"process";import{EventEmitter as je}from"events";import x from"process";import re from"process";import q from"process";import A from"process";import M from"process";import ae from"tty";import bt,{stdin as cs,stdout as us}from"process";class le{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let e=se.homedir(),t=H.join(e,".config","clapp");this.configPath=H.join(t,"telemetry.json")}async isEnabled(){if(S.env.DO_NOT_TRACK==="1"||S.env.DO_NOT_TRACK==="true")return!1;if(S.env.NO_TELEMETRY==="1"||S.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let e=await this.loadConfig();if(e.enabled=!0,!e.userId)e.userId=this.generateUserId();await this.saveConfig(e)}async disable(){let e=await this.loadConfig();e.enabled=!1,await this.saveConfig(e)}async track(e,t){if(!await this.isEnabled())return;let r={event:e,...t,timestamp:Date.now(),platform:se.platform(),nodeVersion:S.version};if(this.events.push(r),this.events.length>=10)await this.send()}async trackCommand(e,t){await this.track("command",{command:e,duration:t})}async trackError(e,t){await this.track("error",{error:e,command:t})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let t=await this.loadConfig();return t.lastSent=Date.now(),await this.saveConfig(t),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let t=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(t),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(e){return new Promise((t)=>setTimeout(t,e))}async status(){let e=await this.loadConfig();return{enabled:e.enabled,doNotTrack:S.env.DO_NOT_TRACK==="1"||S.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:e.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(_e(this.configPath)){let e=await U.readFile(this.configPath,"utf-8");return this.config=JSON.parse(e),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(e){this.config=e;try{let t=H.dirname(this.configPath);await U.mkdir(t,{recursive:!0}),await U.writeFile(this.configPath,JSON.stringify(e,null,2),"utf-8")}catch{}}generateUserId(){let e=Math.random().toString(36).substring(2,15),t=Date.now().toString(36);return`${e}-${t}`}}var Jt=new le;function ke(e,t={}){let s={_:[]},r=t.alias||{},n=new Set(t.boolean||[]),o={};for(let a of Object.keys(r))for(let i of r[a])o[i]=a;for(let a of n)if(r[a])for(let i of r[a])n.add(i);function l(a,i){let u=o[a]||a;if(s[u]=i,r[u])for(let d of r[u])s[d]=i;if(o[a]&&r[o[a]])for(let d of r[o[a]])s[d]=i;s[a]=i}for(let a=0;a<e.length;a++){let i=e[a];if(i==="--"){s._.push(...e.slice(a+1));break}if(i.startsWith("--")){let u=i.indexOf("=");if(u!==-1){let d=i.slice(2,u),h=i.slice(u+1);l(d,h)}else{let d=i.slice(2);if(d.startsWith("no-")){let m=d.slice(3);l(m,!1);continue}let h=o[d]||d;if(n.has(h)||n.has(d))l(d,!0);else{let m=e[a+1];if(m!==void 0&&!m.startsWith("-"))l(d,m),a++;else l(d,!0)}}}else if(i.startsWith("-")&&i.length>1){let u=i.slice(1);for(let d=0;d<u.length;d++){let h=u[d],m=o[h]||h;if(d===u.length-1&&!n.has(m)&&!n.has(h)){let f=e[a+1];if(f!==void 0&&!f.startsWith("-"))l(h,f),a++;else l(h,!0)}else l(h,!0)}}else s._.push(i)}return s}function z(e){return e.replace(/[<[].+/,"").trim()}function Be(e){let t=/<([^>]+)>/g,s=/\[([^\]]+)\]/g,r=[],n=(a)=>{let i=!1,u=a[1];if(u.startsWith("..."))u=u.slice(3),i=!0;return{required:a[0].startsWith("<"),value:u,variadic:i}},o;while(o=t.exec(e))r.push(n(o));let l;while(l=s.exec(e))r.push(n(l));return r}function Ae(e){let t={alias:{},boolean:[]};for(let[s,r]of e.entries()){if(r.names.length>1)t.alias[r.names[0]]=r.names.slice(1);if(r.isBoolean)if(r.negated){if(!e.some((o,l)=>l!==s&&o.names.some((a)=>r.names.includes(a))&&typeof o.required==="boolean"))t.boolean.push(r.names[0])}else t.boolean.push(r.names[0])}return t}function ie(e){return e.reduce((t,s)=>t.length>=s.length?t:s,"")}function G(e,t){return e.length>=t?e:`${e}${" ".repeat(t-e.length)}`}function Ne(e){return e.replace(/([a-z])-([a-z])/g,(t,s,r)=>s+r.toUpperCase())}function Le(e,t,s){let r=0,n=t.length,o=e,l;for(;r<n;++r)l=o[t[r]],o=o[t[r]]=r===n-1?s:l!=null?l:!!~t[r+1].indexOf(".")||!(+t[r+1]>-1)?{}:[]}function Pe(e,t){for(let s of Object.keys(t)){let r=t[s];if(r.shouldTransform){if(e[s]=Array.prototype.concat.call([],e[s]),typeof r.transformFunction==="function")e[s]=e[s].map(r.transformFunction)}}}function Ve(e){let t=/([^\\/]+)$/.exec(e);return t?t[1]:""}function ce(e){return e.split(".").map((t,s)=>s===0?Ne(t):t).join(".")}class B extends Error{exitCode=2;isUsageError=!0;constructor(e){super(e);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(e).stack}format(e=!1){if(e&&this.stack)return`${this.message}
|
|
4
4
|
|
|
5
5
|
Stack trace:
|
|
6
|
-
${this.stack}`;return this.message}}function
|
|
7
|
-
`);let
|
|
8
|
-
|
|
9
|
-
`;
|
|
10
|
-
`,
|
|
11
|
-
`)}
|
|
12
|
-
`)})}let
|
|
13
|
-
`)})}if(this.examples.length>0)
|
|
14
|
-
`)});if(
|
|
15
|
-
${
|
|
16
|
-
|
|
17
|
-
`))}outputVersion(){let{name:
|
|
18
|
-
|
|
19
|
-
Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:
|
|
20
|
-
|
|
21
|
-
Did you mean one of these?`,
|
|
22
|
-
\u2022 ${
|
|
23
|
-
|
|
24
|
-
Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new
|
|
25
|
-
|
|
26
|
-
Example: ${this.cli.name} ${this.rawName} ${
|
|
27
|
-
|
|
28
|
-
Received ${
|
|
29
|
-
\u2717 Command "${
|
|
30
|
-
`)),this.enableDidYouMean){let
|
|
31
|
-
Run \`${this.name??"cli"} --help\` for usage.`;
|
|
32
|
-
`),
|
|
33
|
-
`),$=J.split(`
|
|
34
|
-
`),Q=[];for(let j=0;j<Math.max(Z.length,$.length);j++)if(Z[j]!==$[j])Q.push(j);return Q}var I4=Az.platform.startsWith("win"),K6=Symbol("clapp:cancel");function k(z,J){let Z=z;if(Z.isTTY)Z.setRawMode(J)}function Sz(z){return z.replace(/\x1b\[[0-9;]*m/g,"")}function kz(z){return Sz(z).length}function F6(z,J,Z){if(!J||J<1)return z;let $=Z?.hard??!1,Q=Z?.trim??!0,j=z.split(`
|
|
35
|
-
`),q=[];for(let X of j){if(kz(X)<=J){q.push(Q?X.trimEnd():X);continue}if($){let Y="",G=0,H=0;while(H<X.length){let K=X.slice(H).match(/^\x1b\[[0-9;]*m/);if(K){Y+=K[0],H+=K[0].length;continue}if(G>=J)q.push(Q?Y.trimEnd():Y),Y="",G=0;Y+=X[H],G++,H++}if(Y)q.push(Q?Y.trimEnd():Y)}else q.push(Q?X.trimEnd():X)}return q.join(`
|
|
36
|
-
`)}class J6{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;_manualLine="";state="initial";error="";value;userInput="";constructor(z,J=!0){let{input:Z=Cz,output:$=Rz,render:Q,signal:j,...q}=z;this.opts=q,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=Q.bind(this),this._track=J,this._abortSignal=j,this.input=Z,this.output=$}unsubscribe(){this._subscribers.clear()}setSubscriber(z,J){let Z=this._subscribers.get(z)??[];Z.push(J),this._subscribers.set(z,Z)}on(z,J){return this.setSubscriber(z,{cb:J}),this}once(z,J){return this.setSubscriber(z,{cb:J,once:!0}),this}emit(z,...J){let Z=this._subscribers.get(z)??[],$=[];for(let Q of Z)if(Q.cb(...J),Q.once)$.push(()=>Z.splice(Z.indexOf(Q),1));for(let Q of $)Q();return this}prompt(){return new Promise((z)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),z(K6);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=vz.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0)this._setUserInput(this.opts.initialUserInput,!0);this.input.on("keypress",this.onKeypress),k(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(w.show),this.output.off("resize",this.render),k(this.input,!1),z(this.value)}),this.once("cancel",()=>{this.output.write(w.show),this.output.off("resize",this.render),k(this.input,!1),z(K6)})})}_isActionKey(z,J){return z==="\t"}_setValue(z){this.value=z,this.emit("value",this.value)}_setUserInput(z,J){if(this.userInput=z??"",this.emit("userInput",this.userInput),J&&this._track&&this.rl)this.rl.write(this.userInput),this._cursor=this.rl.cursor}onKeypress(z,J){if(this._track&&J.name!=="return"){if(J.name&&this._isActionKey(z,J))this.rl?.write(null,{ctrl:!0,name:"h"});this._cursor=this.rl?.cursor??0;let Z=J.name==="tab"||J.name==="escape"||J.name==="backspace"||J.name==="delete"||J.name==="enter"||J.name==="return"||J.name&&["up","down","left","right"].includes(J.name);if(z&&!Z&&z.length===1&&z>=" ")this._manualLine+=z;else if(J.name==="backspace"&&this._manualLine.length>0)this._manualLine=this._manualLine.slice(0,-1);let $=this._manualLine.length>=(this.rl?.line?.length||0)?this._manualLine:this.rl?.line;this._setUserInput($)}if(this.state==="error")this.state="active",this.error="";if(J?.name){if(!this._track&&f.aliases.has(J.name))this.emit("cursor",f.aliases.get(J.name));if(f.actions.has(J.name))this.emit("cursor",J.name)}if(z&&(z.toLowerCase()==="y"||z.toLowerCase()==="n"))this.emit("confirm",z.toLowerCase()==="y");if(this.emit("key",z?.toLowerCase(),J),J?.name==="return"){if(this.opts.validate){let Z=this.opts.validate(this.value);if(Z)this.error=Z instanceof Error?Z.message:Z,this.state="error"}if(this.state!=="error")this.state="submit"}if(w6([z,J?.name,J?.sequence],"cancel"))this.state="cancel";if(this.state==="submit"||this.state==="cancel")this.emit("finalize");if(this.render(),this.state==="submit"||this.state==="cancel")this.close()}close(){if(this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
37
|
-
`),k(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.state==="cancel")setTimeout(()=>{this.unsubscribe()},10);else this.unsubscribe()}restoreCursor(){let z=F6(this._prevFrame,V6.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
38
|
-
`).length-1;this.output.write(w.move(-999,z*-1))}render(){let z=F6(this._render(this)??"",V6.stdout.columns,{hard:!0,trim:!1});if(z===this._prevFrame)return;if(this.state==="initial")this.output.write(w.hide);else{let J=Pz(this._prevFrame,z);if(this.restoreCursor(),J&&J?.length===1){let Z=J[0];this.output.write(w.move(0,Z)),this.output.write(r.lines(1));let $=z.split(`
|
|
39
|
-
`);this.output.write($[Z]),this._prevFrame=z,this.output.write(w.move(0,$.length-Z-1));return}if(J&&J?.length>1){let Z=J[0];this.output.write(w.move(0,Z)),this.output.write(r.down());let Q=z.split(`
|
|
40
|
-
`).slice(Z);this.output.write(Q.join(`
|
|
41
|
-
`)),this._prevFrame=z;return}this.output.write(r.down())}if(this.output.write(z),this.state==="initial")this.state="active";this._prevFrame=z}}function yz(z,J){if(z===void 0)return 0;if(J.length===0)return 0;let $=J.findIndex((Q)=>Q.value===z);return $!==-1?$:0}function _z(z,J){return(J.label??String(J.value)).toLowerCase().includes(z.toLowerCase())}function gz(z,J){if(!J)return;if(z)return J;return J[0]}class fz extends J6{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#z=0;#Z="";#$;#J;get cursor(){return this.#z}get userInputWithCursor(){if(!this.userInput)return g.inverse(g.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let z=this.userInput.slice(0,this._cursor),[J,...Z]=this.userInput.slice(this._cursor);return`${z}${g.inverse(J)}${Z.join("")}`}get options(){if(typeof this.#J==="function")return this.#J();return this.#J}constructor(z){super(z);this.#J=z.options;let J=this.options;this.filteredOptions=[...J],this.multiple=z.multiple===!0,this.#$=z.filter??_z;let Z;if(z.initialValue&&Array.isArray(z.initialValue))if(this.multiple)Z=z.initialValue;else Z=z.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)Z=[this.options[0].value];if(Z)for(let $ of Z){let Q=J.findIndex((j)=>j.value===$);if(Q!==-1)this.toggleSelected($),this.#z=Q}this.focusedValue=this.options[this.#z]?.value,this.on("key",($,Q)=>this.#Q($,Q)),this.on("userInput",($)=>this.#Y($))}_isActionKey(z,J){return z==="\t"||this.multiple&&this.isNavigating&&J.name==="space"&&z!==void 0&&z!==""}#Q(z,J){let Z=J.name==="up",$=J.name==="down",Q=J.name==="return";if(Z||$){if(this.#z=Math.max(0,Math.min(this.#z+(Z?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#z]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(Q)this.value=gz(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&(J.name==="tab"||this.isNavigating&&J.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected(z){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes(z))this.selectedValues=this.selectedValues.filter((J)=>J!==z);else this.selectedValues=[...this.selectedValues,z];else this.selectedValues=[z]}#Y(z){if(z!==this.#Z){this.#Z=z;let J=this.options;if(z)this.filteredOptions=J.filter((Z)=>this.#$(z,Z));else this.filteredOptions=[...J];if(this.#z=yz(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#z]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class hz extends J6{options;cursor=0;#z;getGroupItems(z){return this.options.filter((J)=>J.group===z)}isGroupSelected(z){let J=this.getGroupItems(z),Z=this.value;if(Z===void 0)return!1;return J.every(($)=>Z.includes($.value))}toggleValue(){let z=this.options[this.cursor];if(this.value===void 0)this.value=[];if(z.group===!0){let J=String(z.value),Z=this.getGroupItems(J);if(this.isGroupSelected(J))this.value=this.value.filter(($)=>Z.findIndex((Q)=>Q.value===$)===-1);else this.value=[...this.value,...Z.map(($)=>$.value)];this.value=Array.from(new Set(this.value))}else{let J=this.value.includes(z.value);this.value=J?this.value.filter((Z)=>Z!==z.value):[...this.value,z.value]}}constructor(z){super(z,!1);let{options:J}=z;this.#z=z.selectableGroups!==!1,this.options=Object.entries(J).flatMap(([Z,$])=>[{value:Z,group:!0,label:Z},...$.map((Q)=>({...Q,group:Z}))]),this.value=[...z.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:Z})=>Z===z.cursorAt),this.#z?0:1),this.on("cursor",(Z)=>{switch(Z){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let $=this.options[this.cursor]?.group===!0;if(!this.#z&&$)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let $=this.options[this.cursor]?.group===!0;if(!this.#z&&$)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var mz=a6();var D=(z,J)=>mz?z:J,R4=D("\u25C6","*"),v4=D("\u25A0","x"),S4=D("\u25B2","x"),k4=D("\u25C7","o"),y4=D("\u250C","T"),dz=D("\u2502","|"),_4=D("\u2514","\u2014"),g4=D("\u25CF",">"),f4=D("\u25CB"," "),h4=D("\u25FB","[\u2022]"),m4=D("\u25FC","[+]"),d4=D("\u25FB","[ ]"),u4=D("\u25AA","\u2022"),c4=D("\u2500","-"),i4=D("\u256E","+"),n4=D("\u251C","+"),p4=D("\u256F","+"),l4=D("\u25CF","\u2022"),a4=D("\u25C6","*"),r4=D("\u25B2","!"),s4=D("\u25A0","x");var t4={light:D("\u2500","-"),heavy:D("\u2501","="),block:D("\u2588","#")};function uz(){return`${g.gray(dz)} `}var o4=uz();var E6="0.1.0";import T from"fs/promises";import Z6 from"path";import m from"process";var N={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"},U={red:(z)=>`${N.red}${z}${N.reset}`,green:(z)=>`${N.green}${z}${N.reset}`,yellow:(z)=>`${N.yellow}${z}${N.reset}`,blue:(z)=>`${N.blue}${z}${N.reset}`,cyan:(z)=>`${N.cyan}${z}${N.reset}`,white:(z)=>`${N.white}${z}${N.reset}`,gray:(z)=>`${N.gray}${z}${N.reset}`,bold:(z)=>`${N.bold}${z}${N.reset}`,dim:(z)=>`${N.dim}${z}${N.reset}`,hex:(z)=>(J)=>J};async function d(z){let J=Object.entries(B6).map(([$,Q])=>({name:$,className:Q.constructor.name})),Z=`/**
|
|
6
|
+
${this.stack}`;return this.message}}function De(){let{env:e}=re,{TERM:t,TERM_PROGRAM:s}=e;if(re.platform!=="win32")return t!=="linux";return Boolean(e.WT_SESSION)||Boolean(e.TERMINUS_SUBLIME)||e.ConEmuTask==="{cmd::Cmder}"||s==="Terminus-Sublime"||s==="vscode"||t==="xterm-256color"||t==="alacritty"||t==="rxvt-unicode"||t==="rxvt-unicode-256color"||e.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var N="\x1B",w=`${N}[`;var ne={to(e,t){if(!t)return`${w}${e+1}G`;return`${w}${t+1};${e+1}H`},move(e,t){let s="";if(e<0)s+=`${w}${-e}D`;else if(e>0)s+=`${w}${e}C`;if(t<0)s+=`${w}${-t}A`;else if(t>0)s+=`${w}${t}B`;return s},up:(e=1)=>`${w}${e}A`,down:(e=1)=>`${w}${e}B`,forward:(e=1)=>`${w}${e}C`,backward:(e=1)=>`${w}${e}D`,nextLine:(e=1)=>`${w}E`.repeat(e),prevLine:(e=1)=>`${w}F`.repeat(e),left:`${w}G`,hide:`${w}?25l`,show:`${w}?25h`,save:`${N}7`,restore:`${N}8`};var es={screen:`${w}2J`,up:(e=1)=>`${w}1J`.repeat(e),down:(e=1)=>`${w}J`.repeat(e),line:`${w}2K`,lineEnd:`${w}K`,lineStart:`${w}1K`,lines(e){let t="";for(let s=0;s<e;s++)t+=this.line+(s<e-1?ne.up():"");if(e)t+=ne.left;return t}},ts={screen:`${N}c`};function Fe(e,t){let s=[];for(let r=0;r<=t.length;r++)s[r]=[r];for(let r=0;r<=e.length;r++)s[0][r]=r;for(let r=1;r<=t.length;r++)for(let n=1;n<=e.length;n++)if(t.charAt(r-1)===e.charAt(n-1))s[r][n]=s[r-1][n-1];else s[r][n]=Math.min(s[r-1][n-1]+1,s[r][n-1]+1,s[r-1][n]+1);return s[t.length][e.length]}function ue(e,t,s=2,r=3){return t.map((n)=>({cmd:n,distance:Fe(e,n)})).filter(({distance:n})=>n<=s).sort((n,o)=>n.distance-o.distance).slice(0,r).map(({cmd:n})=>n)}class de{rawName;description;name;names;isBoolean;required;config;negated;constructor(e,t,s){if(this.rawName=e,this.description=t,this.config=Object.assign({},s),e=e.replace(/\.\*/g,""),this.negated=!1,this.names=z(e).split(",").map((r)=>{let n=r.trim().replace(/^-{1,2}/,"");if(n.startsWith("no-"))this.negated=!0,n=n.replace(/^no-/,"");return ce(n)}).sort((r,n)=>r.length>n.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(e.includes("<"))this.required=!0;else if(e.includes("["))this.required=!1;else this.isBoolean=!0}}var rs=q.argv,We=`${q.platform}-${q.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,oe=A.argv,Ue=`${A.platform}-${A.arch} node-${A.version}`;class K{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor(e,t,s,r){this.rawName=e,this.description=t,this.config=s,this.cli=r,this.options=[],this.aliasNames=[],this.name=z(e);let n=z(e),o=n.indexOf(":");if(o>0)this.namespace=n.substring(0,o),this.name=n.substring(o+1);if(this.args=Be(e),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!s)this.config={}}usage(e){return this.usageText=e,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(e,t="-v, --version"){return this.versionNumber=e,this.option(t,"Display version number"),this}example(e){return this.examples.push(e),this}option(e,t,s){let r=new de(e,t,s);return this.options.push(r),this}alias(e){return this.aliasNames.push(e),this}action(e){return this.commandAction=e,this}before(e){return this.beforeHooks.push(e),this}after(e){return this.afterHooks.push(e),this}use(e){return this.middleware.push(e),this}isMatched(e){if(this.aliasNames.includes(e))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===e;return this.name===e}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof Y}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(e){return e=e.split(".")[0],!!this.options.find((t)=>t.names.includes(e))}outputHelp(){let{name:e,commands:t}=this.cli,{versionNumber:s,options:r,helpCallback:n}=this.cli.globalCommand,o=[{body:`${e}${s?`/${s}`:""}`}];if(o.push({title:"Usage",body:` $ ${e} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&t.length>0){let i=ie(t.map((f)=>f.rawName)),u=new Map,d=[];for(let f of t)if(f.namespace){if(!u.has(f.namespace))u.set(f.namespace,[]);u.get(f.namespace).push(f)}else d.push(f);let h="";if(d.length>0)h+=d.map((f)=>` ${G(f.rawName,i.length)} ${f.description}`).join(`
|
|
7
|
+
`);let m=Array.from(u.keys()).sort();for(let f of m){let Me=u.get(f);if(h.length>0)h+=`
|
|
8
|
+
|
|
9
|
+
`;h+=` ${f}:
|
|
10
|
+
`,h+=Me.map((te)=>` ${G(te.rawName,i.length-2)} ${te.description}`).join(`
|
|
11
|
+
`)}o.push({title:"Commands",body:h}),o.push({title:"For more info, run any command with the `--help` flag",body:t.map((f)=>` $ ${e}${f.displayName===""?"":` ${f.displayName}`} --help`).join(`
|
|
12
|
+
`)})}let a=this.isGlobalCommand?r:[...this.options,...r||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)a=a.filter((i)=>i.name!=="version");if(a.length>0){let i=ie(a.map((u)=>u.rawName));o.push({title:"Options",body:a.map((u)=>` ${G(u.rawName,i.length)} ${u.description} ${u.config.default===void 0?"":`(default: ${u.config.default})`}`).join(`
|
|
13
|
+
`)})}if(this.examples.length>0)o.push({title:"Examples",body:this.examples.map((i)=>{if(typeof i==="function")return i(e);return i}).join(`
|
|
14
|
+
`)});if(n)o=n(o)||o;console.log(o.map((i)=>i.title?`${i.title}:
|
|
15
|
+
${i.body}`:i.body).join(`
|
|
16
|
+
|
|
17
|
+
`))}outputVersion(){let{name:e}=this.cli,{versionNumber:t}=this.cli.globalCommand;if(t)console.log(`${e}/${t} ${typeof Bun<"u"?We:Ue}`)}checkRequiredArgs(){let e=this.args.filter((t)=>t.required).length;if(this.cli.args.length<e){let s=this.args.filter((n)=>n.required).slice(this.cli.args.length),r=s.map((n)=>`<${n.value}>`).join(" ");throw new B(`Missing required argument${s.length>1?"s":""}: ${r}
|
|
18
|
+
|
|
19
|
+
Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:e,globalCommand:t}=this.cli;if(!this.config.allowUnknownOptions){for(let s of Object.keys(e))if(s!=="--"&&!this.hasOption(s)&&!t.hasOption(s)){let n=[...t.options,...this.options].flatMap((i)=>i.names),o=s.length>1?`--${s}`:`-${s}`,l=ue(s,n),a=`Unknown option \`${o}\``;if(l.length>0)a+=`
|
|
20
|
+
|
|
21
|
+
Did you mean one of these?`,l.forEach((i)=>{let u=i.length>1?`--${i}`:`-${i}`;a+=`
|
|
22
|
+
\u2022 ${u}`});throw a+=`
|
|
23
|
+
|
|
24
|
+
Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new B(a)}}}checkOptionValue(){let{options:e,globalCommand:t}=this.cli,s=[...t.options,...this.options];for(let r of s){let n=e[r.name.split(".")[0]];if(r.required){let o=s.some((l)=>l.negated&&l.names.includes(r.name));if(n===!0||n===!1&&!o)throw new B(`Option \`${r.rawName}\` requires a value.
|
|
25
|
+
|
|
26
|
+
Example: ${this.cli.name} ${this.rawName} ${r.rawName} <value>`)}}}}class Y extends K{constructor(e){super("@@global@@","",{},e)}}var He=K,C={red:["\x1B[31m","\x1B[39m"],green:["\x1B[32m","\x1B[39m"],blue:["\x1B[34m","\x1B[39m"],yellow:["\x1B[33m","\x1B[39m"],cyan:["\x1B[36m","\x1B[39m"],magenta:["\x1B[35m","\x1B[39m"],white:["\x1B[37m","\x1B[39m"],gray:["\x1B[90m","\x1B[39m"],bgRed:["\x1B[41m","\x1B[49m"],bgGreen:["\x1B[42m","\x1B[49m"],bgBlue:["\x1B[44m","\x1B[49m"],bgYellow:["\x1B[43m","\x1B[49m"],bgCyan:["\x1B[46m","\x1B[49m"],bgMagenta:["\x1B[45m","\x1B[49m"],bold:["\x1B[1m","\x1B[22m"],italic:["\x1B[3m","\x1B[23m"],underline:["\x1B[4m","\x1B[24m"],dim:["\x1B[2m","\x1B[22m"],inverse:["\x1B[7m","\x1B[27m"],hidden:["\x1B[8m","\x1B[28m"],strikethrough:["\x1B[9m","\x1B[29m"]};var I={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function Ge(){return!0}function ze(){let e={};e.supportsColor=Ge();function t(r,n=[]){let o=r===""?[]:[...n,r],l=function(i){if(!e.supportsColor)return i;let u="",d="";for(let h of o)if(h in I&&I[h]in C){let m=I[h];u+=C[m][0],d=C[m][1]+d}else if(h in C)u+=C[h][0],d=C[h][1]+d;return u+i+d},a=[...Object.keys(C),...Object.keys(I)];for(let i of a)if(!(i in l))Object.defineProperty(l,i,{get(){return t(i,o)}});return l}let s=[...Object.keys(C),...Object.keys(I)];for(let r of s)if(!(r in e))Object.defineProperty(e,r,{get(){return t(r)}});return e}var E=ze();class J extends je{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;enableDidYouMean=!0;signalHandlersSet=!1;isVerbose=!1;isQuiet=!1;isDebug=!1;isNoInteraction=!1;environment;isDryRun=!1;isForce=!1;useEmoji=!0;theme;isNoCache=!1;constructor(e=""){super();this.name=e,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new Y(this),this.globalCommand.usage("<command> [options]")}handleSignals(e){if(this.signalHandlersSet)return this;let t=async(s)=>{if(console.log(`
|
|
27
|
+
|
|
28
|
+
Received ${s}, cleaning up...`),e)try{await e()}catch(r){console.error("Error during cleanup:",r)}x.exit(0)};return x.on("SIGINT",()=>t("SIGINT")),x.on("SIGTERM",()=>t("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean(e=!0){return this.enableDidYouMean=e,this}verbose(){return this.globalCommand.option("-v, --verbose","Enable verbose output"),this}quiet(){return this.globalCommand.option("-q, --quiet","Suppress non-essential output"),this}debug(){return this.globalCommand.option("--debug","Enable debug mode with detailed error information"),this}noInteraction(){return this.globalCommand.option("-n, --no-interaction","Do not ask any interactive questions (for CI/CD)"),this}env(){return this.globalCommand.option("--env <environment>","Target environment (e.g., production, staging, local)"),this}dryRun(){return this.globalCommand.option("--dry-run","Preview actions without executing them"),this}force(){return this.globalCommand.option("-f, --force","Skip confirmation prompts"),this}emoji(){return this.globalCommand.option("--no-emoji","Disable emoji in output"),this}themes(){return this.globalCommand.option("--theme <theme>","Color theme (default, dracula, nord, solarized, monokai)"),this}cache(){return this.globalCommand.option("--no-cache","Disable caching"),this}usage(e){return this.globalCommand.usage(e),this}command(e,t,s){if(!s)s={};let r=new He(e,t||"",s,this);return r.globalCommand=this.globalCommand,this.commands.push(r),r}option(e,t,s){return this.globalCommand.option(e,t,s),this}help(e){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=e,this.showHelpOnExit=!0,this}version(e,t="-v, --version"){return this.globalCommand.version(e,t),this.showVersionOnExit=!0,this}example(e){return this.globalCommand.example(e),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:e,options:t},s,r){if(this.args=e,this.options=t,s)this.matchedCommand=s;if(r)this.matchedCommandName=r;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound(e){if(console.log(E.red(`
|
|
29
|
+
\u2717 Command "${e}" not found.
|
|
30
|
+
`)),this.enableDidYouMean){let t=[];for(let r of this.commands){if(r.displayName)t.push(r.displayName);if(r.aliasNames)t.push(...r.aliasNames)}let s=ue(e,t);if(s.length>0)console.log(E.yellow("Did you mean one of these?")),s.forEach((r)=>console.log(` ${E.dim("\u2022")} ${this.name} ${r}`)),console.log("")}console.log(E.dim("Run"),`${this.name} --help`,E.dim("to see all available commands")),x.exit(1)}async parse(e=oe,t={}){let{run:s=!0,exitOnError:r=!1}=t;if(r)try{return await this.parse(e,{run:s})}catch(i){throw this.handleUsageError(i),i}if(this.rawArgs=e,!this.name)this.name=e[1]?Ve(e[1]):"cli";let n=!0,o=e.slice(2),l=o[0];if(l&&!l.startsWith("-")){for(let i of this.commands)if(i.isMatched(l)){let u=this.mri(o,i);n=!1;let d={...u,args:u.args.slice(1)};this.setParsedInfo(d,i,l),this.emit(`command:${l}`,i);break}}if(n){for(let i of this.commands)if(i.name===""){n=!1;let u=this.mri(o,i);this.setParsedInfo(u,i),this.emit("command:!",i);break}}if(n){let i=this.mri(e.slice(2));this.setParsedInfo(i)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji!==void 0)this.useEmoji=!this.options.noEmoji;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache!==void 0)this.isNoCache=Boolean(this.options.noCache);if(this.options.help&&this.showHelpOnExit)this.outputHelp(),s=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),s=!1,this.unsetMatchedCommand();let a={args:this.args,options:this.options};if(s)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return a}mri(e,t){let s=[...this.globalCommand.options,...t?t.options:[]],r=Ae(s),n=[],o=e.indexOf("--");if(o>-1)n=e.slice(o+1),e=e.slice(0,o);let l=ke(e,r),a={_:l._};for(let m of Object.keys(l))if(m!=="_")a[ce(m)]=l[m];let i=a._,u={"--":n},d=t&&t.config.ignoreOptionDefaultValue?t.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,h=Object.create(null);for(let m of s){if(!d&&m.config.default!==void 0)for(let f of m.names)u[f]=m.config.default;if(Array.isArray(m.config.type)){if(h[m.name]===void 0)h[m.name]={shouldTransform:!0,transformFunction:m.config.type[0]}}}for(let m of Object.keys(a))if(m!=="_"){let f=m.split(".");Le(u,f,a[m]),Pe(u,h)}return{args:i,options:u}}async run(e=oe){return this.parse(e,{run:!0,exitOnError:!0})}handleUsageError(e){if(!(!!e&&typeof e==="object"&&e.name==="ClappError"&&e.isUsageError!==!1))return;let r=e,n=r.message??"command-line error",o=this.name?`${this.name}: `:"",l=/--help/.test(n)?"":`
|
|
31
|
+
Run \`${this.name??"cli"} --help\` for usage.`;x.stderr.write(`${o}${n}${l}
|
|
32
|
+
`),x.exit(r.exitCode??2)}async runMatchedCommand(){let{args:e,options:t,matchedCommand:s}=this;if(!s||!s.commandAction)return;s.checkUnknownOptions(),s.checkOptionValue(),s.checkRequiredArgs();let r=[];s.args.forEach((a,i)=>{if(a.variadic)r.push(e.slice(i));else r.push(e[i])}),r.push(t);let n={command:s,args:r,options:t};for(let a of s.beforeHooks)await a(n);let o,l=async()=>{let a=s.commandAction.apply(this,r);if(a instanceof Promise)o=await a;else o=a;return o};if(s.middleware.length>0){let a=0,i=async()=>{if(a<s.middleware.length){let u=s.middleware[a++];await u({...n,next:i})}else await l()};await i()}else await l();for(let a of s.afterHooks)await a(n);return o}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return x.removeAllListeners("SIGINT"),x.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class he{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get(e){if(!this.enabled){this.misses++;return}let t=this.cache.get(e);if(!t){this.misses++;return}if(Date.now()-t.timestamp>t.ttl){this.cache.delete(e),this.misses++;return}return this.hits++,t.value}set(e,t,s=5000){if(!this.enabled)return;this.cache.set(e,{value:t,timestamp:Date.now(),ttl:s})}has(e){if(!this.enabled)return!1;let t=this.cache.get(e);if(!t)return!1;if(Date.now()-t.timestamp>t.ttl)return this.cache.delete(e),!1;return!0}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let e=Date.now();for(let[t,s]of this.cache.entries())if(e-s.timestamp>s.ttl)this.cache.delete(t)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var ns=new he;function qe(){if("FORCE_COLOR"in M.env)return M.env.FORCE_COLOR!=="0";if("NO_COLOR"in M.env||M.env.TERM==="dumb")return!1;if(M.platform==="win32")return!0;return ae.isatty(1)&&ae.isatty(2)}var me=qe();function y(e,t){if(!me)return(s)=>s;return(s)=>e+s+t}var Ke=y("\x1B[0m","\x1B[0m"),Ye=y("\x1B[31m","\x1B[39m"),Je=y("\x1B[32m","\x1B[39m"),Qe=y("\x1B[33m","\x1B[39m"),Xe=y("\x1B[34m","\x1B[39m"),Ze=y("\x1B[35m","\x1B[39m"),et=y("\x1B[36m","\x1B[39m"),tt=y("\x1B[37m","\x1B[39m"),st=y("\x1B[90m","\x1B[39m"),rt=y("\x1B[1m","\x1B[22m"),it=y("\x1B[3m","\x1B[23m"),nt=y("\x1B[4m","\x1B[24m"),ot=y("\x1B[2m","\x1B[22m"),at=y("\x1B[7m","\x1B[27m"),lt=y("\x1B[8m","\x1B[28m"),ct=y("\x1B[9m","\x1B[29m"),ut=y("\x1B[41m","\x1B[49m"),dt=y("\x1B[42m","\x1B[49m"),ht=y("\x1B[43m","\x1B[49m"),mt=y("\x1B[44m","\x1B[49m"),pt=y("\x1B[45m","\x1B[49m"),ft=y("\x1B[46m","\x1B[49m"),gt=y("\x1B[47m","\x1B[49m"),yt=me,$t={reset:Ke,red:Ye,green:Je,yellow:Qe,blue:Xe,magenta:Ze,cyan:et,white:tt,gray:st,bold:rt,italic:it,underline:nt,dim:ot,inverse:at,hidden:lt,strikethrough:ct,bgRed:ut,bgGreen:dt,bgYellow:ht,bgBlue:mt,bgMagenta:pt,bgCyan:ft,bgWhite:gt,isColorSupported:yt},wt=$t,vt=["up","down","left","right","space","enter","cancel"],ds={actions:new Set(vt),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};var hs=bt.platform.startsWith("win"),ms=Symbol("clapp:cancel");var xt=De();var g=(e,t)=>xt?e:t,ps=g("\u25C6","*"),fs=g("\u25A0","x"),gs=g("\u25B2","x"),ys=g("\u25C7","o"),$s=g("\u250C","T"),Ct=g("\u2502","|"),ws=g("\u2514","\u2014"),bs=g("\u25CF",">"),vs=g("\u25CB"," "),xs=g("\u25FB","[\u2022]"),Cs=g("\u25FC","[+]"),Rs=g("\u25FB","[ ]"),Os=g("\u25AA","\u2022"),Ss=g("\u2500","-"),Ts=g("\u256E","+"),Is=g("\u251C","+"),Es=g("\u256F","+"),Ms=g("\u25CF","\u2022"),_s=g("\u25C6","*"),js=g("\u25B2","!"),ks=g("\u25A0","x");var Bs={light:g("\u2500","-"),heavy:g("\u2501","="),block:g("\u2588","#")};function Rt(){return`${wt.gray(Ct)} `}var As=Rt();var pe="0.1.2";import R from"fs/promises";import Q from"path";import L from"process";var b={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"},c={red:(e)=>`${b.red}${e}${b.reset}`,green:(e)=>`${b.green}${e}${b.reset}`,yellow:(e)=>`${b.yellow}${e}${b.reset}`,blue:(e)=>`${b.blue}${e}${b.reset}`,cyan:(e)=>`${b.cyan}${e}${b.reset}`,white:(e)=>`${b.white}${e}${b.reset}`,gray:(e)=>`${b.gray}${e}${b.reset}`,bold:(e)=>`${b.bold}${e}${b.reset}`,dim:(e)=>`${b.dim}${e}${b.reset}`,hex:(e)=>(t)=>t};async function P(e){let t=Object.entries(fe).map(([r,n])=>({name:r,className:n.constructor.name})),s=`/**
|
|
42
33
|
* This file is auto-generated.
|
|
43
34
|
* DO NOT EDIT THIS FILE DIRECTLY.
|
|
44
35
|
* To update, run 'bun router middleware:types'
|
|
45
36
|
*/
|
|
46
|
-
import type { ${
|
|
37
|
+
import type { ${t.map((r)=>r.className).join(", ")} } from './middleware'
|
|
47
38
|
|
|
48
39
|
/**
|
|
49
40
|
* Available middleware map with middleware names as keys
|
|
50
41
|
*/
|
|
51
42
|
export interface MiddlewareMap {
|
|
52
|
-
${
|
|
43
|
+
${t.map((r)=>` '${r.name}': ${r.className}`).join(`
|
|
53
44
|
`)}
|
|
54
45
|
}
|
|
55
46
|
|
|
56
47
|
/**
|
|
57
48
|
* String literal type of available middleware names
|
|
58
49
|
*/
|
|
59
|
-
export type MiddlewareName = ${
|
|
50
|
+
export type MiddlewareName = ${t.map((r)=>`'${r.name}'`).join(" | ")}
|
|
60
51
|
|
|
61
52
|
/**
|
|
62
53
|
* Middleware configuration type for router setup
|
|
63
54
|
*/
|
|
64
|
-
export type MiddlewareConfig = MiddlewareName | ${
|
|
55
|
+
export type MiddlewareConfig = MiddlewareName | ${t.map((r)=>r.className).join(" | ")}
|
|
65
56
|
|
|
66
57
|
/**
|
|
67
58
|
* Function to check if a middleware name is valid
|
|
68
59
|
*/
|
|
69
60
|
export function isValidMiddleware(name: string): name is MiddlewareName {
|
|
70
|
-
return [${
|
|
61
|
+
return [${t.map((r)=>`'${r.name}'`).join(", ")}].includes(name)
|
|
71
62
|
}
|
|
72
|
-
`;await
|
|
73
|
-
`),
|
|
74
|
-
`),
|
|
63
|
+
`;await R.writeFile(e,s)}async function ge(e){let t=[],s=await R.readdir(e,{withFileTypes:!0});for(let r of s){let n=Q.join(e,r.name);if(r.isDirectory())t.push(...await ge(n));else if(r.isFile()&&r.name.endsWith(".ts"))t.push(n)}return t}async function St(e){let t=[];try{let s=await R.readFile(e,"utf-8"),r=/export\s+(?:default\s+)?class\s+(\w+)\s+(?:implements\s+Middleware|\{[\s\S]*?handle\s*\([\s\S]*?\))/g,n=null;while(n=r.exec(s)){let o=n[1];if(o.includes("Middleware")||n[0].includes("implements Middleware")){let a=Q.relative(L.cwd(),e).replace(/\.ts$/,"");t.push({name:o,path:a})}}}catch(s){console.warn(c.yellow(`Error scanning file ${e}: ${s}`))}return t}async function V(e,t){console.log(c.blue(`Scanning directory: ${e} for middleware classes...`));try{let s=await ge(e),r=[];for(let i of s){let u=await St(i);r.push(...u)}if(r.length===0){console.warn(c.yellow("No middleware classes found in the specified directory."));return}let n=r.map((i)=>`import { ${i.name} } from '${i.path}'`).join(`
|
|
64
|
+
`),o=r.map((i)=>` ${i.name}: typeof ${i.name}`).join(`
|
|
65
|
+
`),l=r.map((i)=>i.name).join(" | "),a=`/**
|
|
75
66
|
* This file is auto-generated.
|
|
76
67
|
* DO NOT EDIT THIS FILE DIRECTLY.
|
|
77
68
|
* To update, run 'bun router middleware:map'
|
|
78
69
|
*/
|
|
79
70
|
|
|
80
|
-
${
|
|
71
|
+
${n}
|
|
81
72
|
|
|
82
73
|
/**
|
|
83
74
|
* Map of all available middleware in the project
|
|
84
75
|
*/
|
|
85
76
|
export interface MiddlewareMap {
|
|
86
|
-
${
|
|
77
|
+
${o}
|
|
87
78
|
}
|
|
88
79
|
|
|
89
80
|
/**
|
|
90
81
|
* Type representing all available middleware classes in the project
|
|
91
82
|
*/
|
|
92
|
-
export type MiddlewareType = ${
|
|
83
|
+
export type MiddlewareType = ${l}
|
|
93
84
|
|
|
94
85
|
/**
|
|
95
86
|
* Type for a middleware handler function
|
|
@@ -100,10 +91,10 @@ export type MiddlewareHandler = (req: any, next: () => Promise<Response>) => Pro
|
|
|
100
91
|
* Ensure the middleware module exports all the middleware classes used in the project
|
|
101
92
|
*/
|
|
102
93
|
export const middlewareMap: MiddlewareMap = {
|
|
103
|
-
${
|
|
94
|
+
${r.map((i)=>` ${i.name}: ${i.name}`).join(`,
|
|
104
95
|
`)}
|
|
105
96
|
}
|
|
106
|
-
`;await
|
|
97
|
+
`;await R.writeFile(t,a),console.log(c.green(`\u2728 Middleware map generated at ${t} with ${r.length} middleware classes`)),console.log(c.blue("Found middleware classes:"));for(let i of r)console.log(c.cyan(` - ${i.name} (${i.path})`))}catch(s){throw console.error(c.red(`Error generating middleware map: ${s}`)),s}}async function ye(e,t){try{await R.access(e)}catch{console.error(c.red(`Directory not found at ${e}`)),L.exit(1)}await V(e,t),console.log(c.blue(`Watching for changes in ${e}...`));let s=null,r=R.watch(e,{recursive:!0});for await(let n of r){if(s)clearTimeout(s);s=setTimeout(async()=>{console.log(c.yellow("Changes detected. Regenerating middleware map..."));try{await V(e,t)}catch(o){console.error(c.red(`Error regenerating middleware map: ${o.message}`))}s=null},500)}}async function $e(e){let t=Q.join(L.cwd(),"src","middleware");try{await R.access(t)}catch{console.error(c.red(`Middleware directory not found at ${t}`)),L.exit(1)}await P(e),console.log(c.green(`\u2728 Middleware types generated at ${e}`)),console.log(c.blue(`Watching for changes in ${t}...`));let s=null,r=R.watch(t,{recursive:!0});for await(let n of r){if(s)clearTimeout(s);s=setTimeout(async()=>{console.log(c.yellow("Changes detected in middleware directory. Regenerating types..."));try{await P(e),console.log(c.green(`\u2728 Middleware types regenerated at ${e}`))}catch(o){console.error(c.red(`Error regenerating types: ${o.message}`))}s=null},500)}}import Tt from"fs/promises";import X from"process";async function we(e){try{let t=`${X.cwd()}/routes/index.ts`,{router:s}=await import(t);if(!s)console.error(c.red(`Could not find router instance in ${t}.`)),X.exit(1);let r=s.routes||[];if(r.length===0)console.log(c.yellow("No routes defined. Creating empty OpenAPI specification."));let n=r.filter((i)=>i.type==="api"||i.path.startsWith("/api")),o={openapi:"3.0.3",info:{title:e.title||"API Documentation",version:e.version||"1.0.0",description:e.description||"Generated API documentation"},servers:It(e),paths:{},components:{schemas:{},securitySchemes:{}},tags:[]},l=new Set;for(let i of n){let u=o.paths[i.path]||{},d="";if(e.tags!==!1)d=i.tag||Et(i.path),l.add(d);let h={summary:i.summary||`${i.method.toUpperCase()} ${i.path}`,description:i.description||"",operationId:i.name||Mt(i.method,i.path),parameters:_t(i),responses:kt(i)};if(d)h.tags=[d];if(["post","put","patch"].includes(i.method.toLowerCase()))h.requestBody=Bt(i);if(e.security!==!1&&i.middleware){let m=At(i.middleware);if(m.length>0)h.security=m}u[i.method.toLowerCase()]=h,o.paths[i.path]=u}if(e.tags!==!1)o.tags=Array.from(l).map((i)=>({name:i,description:`Operations related to ${i}`}));let a=e.output||"openapi.json";await Tt.writeFile(a,JSON.stringify(o,null,2)),console.log(c.green(`\u2728 OpenAPI specification generated at ${a}`)),console.log(c.blue("Import this file into Postman, Swagger UI, or other API tools to explore your API."))}catch(t){if(t.code==="ERR_MODULE_NOT_FOUND")console.error(c.red(`Routes file not found at ${X.cwd()}/routes/index.ts`)),console.error(c.yellow('Make sure your routes are defined and exported as "router" in routes/index.ts'));else console.error(c.red(`Error generating OpenAPI specification: ${t.message}`));throw t}}function It(e){let t=[];if(e.servers){let s=e.servers.split(",").map((r)=>r.trim());for(let r of s)t.push({url:r,description:`Server ${t.length+1}`})}if(t.length===0)t.push({url:e.basePath||"/",description:"Default server"});return t}function Et(e){let t=e.split("/").filter(Boolean);if(t.length>0){if(t[0].toLowerCase()==="api"&&t.length>1)return t[1];return t[0]}return"default"}function Mt(e,t){let r=t.replace(/\{([^}]+)\}/g,"_$1").split("/").filter(Boolean);if(r.length===0)return e.toLowerCase();let n=e.toLowerCase();for(let o of r)n+=o.charAt(0).toUpperCase()+o.slice(1);return n}function _t(e){let t=[],s=e.path.match(/\{([^}]+)\}/g);if(s)for(let r of s){let n=r.slice(1,-1);t.push({name:n,in:"path",required:!0,schema:{type:"string"},description:`Path parameter: ${n}`})}if(e.params&&e.params.query)for(let[r,n]of Object.entries(e.params.query))t.push({name:r,in:"query",schema:jt(n),required:n.required===!0,description:n.description||`Query parameter: ${r}`});return t}function jt(e){if(!e||typeof e!=="object")return{type:"string"};let t={};if(e.type)t.type=e.type;if(e.format)t.format=e.format;if(e.enum)t.enum=e.enum;if(e.default!==void 0)t.default=e.default;return t}function kt(e){let t={200:{description:"Successful response",content:{"application/json":{schema:{}}}}};if(t["400"]={description:"Bad request",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"}}}}}},t["401"]={description:"Unauthorized",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"}}}}}},t["404"]={description:"Not found",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"}}}}}},t["500"]={description:"Server error",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"}}}}}},e.responses)for(let[s,r]of Object.entries(e.responses))t[s]={description:r.description||`Response with status ${s}`,content:{"application/json":{schema:r.schema||{}}}};return t}function Bt(e){let t={required:!0,content:{"application/json":{schema:{type:"object"}}}};if(e.params&&e.params.body)t.content["application/json"].schema=e.params.body;return t}function At(e){let t=[];for(let s of e){let r=typeof s==="string"?s:s.name;if(r&&r.toLowerCase().includes("auth"))if(r.toLowerCase().includes("jwt"))t.push({BearerAuth:[]});else if(r.toLowerCase().includes("apikey"))t.push({ApiKeyAuth:[]});else if(r.toLowerCase().includes("basic"))t.push({BasicAuth:[]});else t.push({[r]:[]})}return t}import Z from"fs/promises";import be from"path";import T from"process";async function D(e){try{let t=`${T.cwd()}/routes/index.ts`,{router:s}=await import(t);if(!s)console.error(c.red(`Could not find router instance in ${t}.`)),T.exit(1);let r=Object.getOwnPropertyNames(Object.getPrototypeOf(s)).filter((l)=>!l.startsWith("_")&&l!=="constructor"&&typeof s[l]==="function"),n=Object.keys(s).filter((l)=>!["routes","middleware","hooks","config"].includes(l)&&typeof l==="string"&&!l.startsWith("_")),o=`/**
|
|
107
98
|
* This file is auto-generated.
|
|
108
99
|
* DO NOT EDIT THIS FILE DIRECTLY.
|
|
109
100
|
* To update, run 'bun router router:types'
|
|
@@ -114,10 +105,10 @@ import type { Router, RouteHandler, MiddlewareHandler, RouteDefinition } from '.
|
|
|
114
105
|
* Extended Router interface with all available methods and properties
|
|
115
106
|
*/
|
|
116
107
|
export interface ExtendedRouter extends Router {
|
|
117
|
-
${
|
|
108
|
+
${r.map((l)=>{if(["get","post","put","delete","patch","options","head"].includes(l))return`${l}(path: string, handler: RouteHandler, options?: any): Router`;else if(l==="use")return`${l}(middleware: MiddlewareHandler | MiddlewareHandler[]): Router`;else if(l==="group")return`${l}(prefix: string, callback: (router: Router) => void): Router`;else return`${l}: Function`}).join(`
|
|
118
109
|
`)}
|
|
119
110
|
|
|
120
|
-
${
|
|
111
|
+
${n.map((l)=>{let a=typeof s[l];return`${l}: ${a}`}).join(`
|
|
121
112
|
`)}
|
|
122
113
|
}
|
|
123
114
|
|
|
@@ -148,9 +139,9 @@ export type RouterExtension = {
|
|
|
148
139
|
* \`\`\`
|
|
149
140
|
*/
|
|
150
141
|
export type ExtendRouter<T extends RouterExtension> = Router & T
|
|
151
|
-
`;await
|
|
152
|
-
Routes:`)),console.log(
|
|
153
|
-
Showing ${
|
|
142
|
+
`;await Z.writeFile(e,o),console.log(c.green(`\u2728 Router types generated at ${e}`))}catch(t){if(t.code==="ERR_MODULE_NOT_FOUND")console.error(c.red(`Routes file not found at ${T.cwd()}/routes/index.ts`)),console.error(c.yellow('Make sure your routes are defined and exported as "router" in routes/index.ts'));else console.error(c.red(`Error generating router types: ${t.message}`));throw t}}async function ve(e){let t=[be.join(T.cwd(),"routes"),be.join(T.cwd(),"src")],s=!1;for(let n of t)try{await Z.access(n),s=!0;break}catch{}if(!s)console.error(c.red("No valid source directories found to watch.")),T.exit(1);await D(e),console.log(c.green(`\u2728 Router types generated at ${e}`)),console.log(c.blue("Watching for changes in router files..."));let r=null;for(let n of t)try{let o=Z.watch(n,{recursive:!0});(async()=>{for await(let l of o){if(r)clearTimeout(r);r=setTimeout(async()=>{console.log(c.yellow("Changes detected in router files. Regenerating types..."));try{await D(e),console.log(c.green(`\u2728 Router types regenerated at ${e}`))}catch(a){console.error(c.red(`Error regenerating types: ${a.message}`))}r=null},500)}})()}catch{}}import ee from"fs/promises";import Nt from"path";import O from"process";async function xe(e){try{let t=`${O.cwd()}/routes/index.ts`,{router:s}=await import(t);if(!s)console.error(c.red(`Could not find router instance in ${t}.`)),O.exit(1);let r=s.routes||[];if(r.length===0){console.log(c.yellow("No routes defined."));return}let n=r;if(e.path)n=n.filter((o)=>o.path.startsWith(e.path));console.log(c.bold(`
|
|
143
|
+
Routes:`)),console.log(c.dim("+-----------------+-------------------------+------------------+----------------+")),console.log(c.dim("| ")+c.bold("Method")+c.dim(" | ")+c.bold("URI")+c.dim(" | ")+c.bold("Name")+c.dim(" | ")+c.bold("Handler")+c.dim(" |")),console.log(c.dim("+-----------------+-------------------------+------------------+----------------+")),n.forEach((o)=>{let l=F(o.method,15),a=F(o.path,23),i=F(o.name||"",16),u;if(typeof o.handler==="string")u=o.handler;else if(typeof o.handler==="function")u=o.handler.name?`${o.handler.name}()`:"Anonymous Function";else u="Class Handler";if(u=F(u,14),console.log(c.dim("| ")+Lt(o.method)(l)+c.dim(" | ")+c.green(a)+c.dim(" | ")+c.yellow(i)+c.dim(" | ")+c.blue(u)+c.dim(" |")),e.verbose&&o.middleware&&o.middleware.length>0)console.log(c.dim("| | ")+c.dim("Middleware: ")+o.middleware.map((d)=>typeof d==="string"?d:d.name||"Anonymous").join(", ")+c.dim(" |"))}),console.log(c.dim("+-----------------+-------------------------+------------------+----------------+")),console.log(`
|
|
144
|
+
Showing ${n.length} routes`)}catch(t){throw console.error(c.red(`Error: ${t.message}`)),console.error(c.yellow(`Make sure your routes are defined in ${O.cwd()}/routes/index.ts and export a 'router' instance.`)),t}}async function W(e){try{let t=`${O.cwd()}/routes/index.ts`,{router:s}=await import(t);if(!s)console.error(c.red(`Could not find router instance in ${t}.`)),O.exit(1);let r=s.routes||[];if(r.length===0)console.log(c.yellow("No routes defined. Creating empty types file."));let n=r.map((a)=>{if(a.name)return a.name;let i=a.method.toLowerCase(),u=a.path.replace(/^\//,"").replace(/\//g,".").replace(/\{([^}]+)\}/g,":$1");return u?`${i}.${u}`:i}),o=[...new Set(n)],l=`/**
|
|
154
145
|
* This file is auto-generated.
|
|
155
146
|
* DO NOT EDIT THIS FILE DIRECTLY.
|
|
156
147
|
* To update, run 'bun router route:types'
|
|
@@ -159,13 +150,13 @@ Showing ${Q.length} routes`)}catch(J){throw console.error(U.red(`Error: ${J.mess
|
|
|
159
150
|
/**
|
|
160
151
|
* String literal type for all available route names
|
|
161
152
|
*/
|
|
162
|
-
export type RouteName = ${
|
|
153
|
+
export type RouteName = ${o.length>0?o.map((a)=>`'${a}'`).join(" | "):"string"}
|
|
163
154
|
|
|
164
155
|
/**
|
|
165
156
|
* Object type with route names as keys and string (for path generation) as values
|
|
166
157
|
*/
|
|
167
158
|
export interface RouteNameMap {
|
|
168
|
-
${
|
|
159
|
+
${o.map((a)=>` '${a}': string`).join(`
|
|
169
160
|
`)}
|
|
170
161
|
}
|
|
171
162
|
|
|
@@ -178,13 +169,13 @@ export type RouteFunction = <T extends RouteName>(name: T, params?: Record<strin
|
|
|
178
169
|
* Validate that a string is a valid route name
|
|
179
170
|
*/
|
|
180
171
|
export function isValidRouteName(name: string): name is RouteName {
|
|
181
|
-
return [${
|
|
172
|
+
return [${o.map((a)=>`'${a}'`).join(", ")}].includes(name)
|
|
182
173
|
}
|
|
183
|
-
`;await
|
|
184
|
-
\uD83D\uDCC8 Routes by method:`);for(let[
|
|
185
|
-
\u26A0\uFE0F Found ${
|
|
186
|
-
\u26A0\uFE0F Potential issues:`);for(let
|
|
187
|
-
\u2705 No issues detected`)}}catch(
|
|
188
|
-
\uD83D\uDCCA Test Results:`),console.log(` Total: ${
|
|
189
|
-
\u274C Failures:`);for(let
|
|
190
|
-
\uD83D\uDCCB Available routes:`);let
|
|
174
|
+
`;await ee.writeFile(e,l),console.log(c.green(`\u2728 Route types generated at ${e}`))}catch(t){if(t.code==="ERR_MODULE_NOT_FOUND")console.error(c.red(`Routes file not found at ${O.cwd()}/routes/index.ts`)),console.error(c.yellow('Make sure your routes are defined and exported as "router" in routes/index.ts'));else console.error(c.red(`Error generating route types: ${t.message}`));throw t}}async function Ce(e){let t=Nt.join(O.cwd(),"routes");try{await ee.access(t)}catch{console.error(c.red(`Routes directory not found at ${t}`)),O.exit(1)}await W(e),console.log(c.green(`\u2728 Route types generated at ${e}`)),console.log(c.blue(`Watching for changes in ${t}...`));let s=null,r=ee.watch(t,{recursive:!0});for await(let n of r){if(s)clearTimeout(s);s=setTimeout(async()=>{console.log(c.yellow("Changes detected in routes directory. Regenerating types..."));try{await W(e),console.log(c.green(`\u2728 Route types regenerated at ${e}`))}catch(o){console.error(c.red(`Error regenerating types: ${o.message}`))}s=null},500)}}function F(e,t){return(e+" ".repeat(t)).substring(0,t)}function Lt(e){switch(e.toUpperCase()){case"GET":return c.cyan;case"POST":return c.green;case"PUT":return c.yellow;case"PATCH":return c.yellow;case"DELETE":return c.red;case"OPTIONS":return c.gray;default:return c.white}}import j from"process";var _={success:(e)=>c.green(`\u2728 ${e}`),info:(e)=>c.blue(e),warning:(e)=>c.yellow(e),error:(e)=>c.red(e),dim:(e)=>c.dim(e),bold:(e)=>c.bold(e)},p={success:(e)=>console.log(_.success(e)),info:(e)=>console.log(_.info(e)),warning:(e)=>console.log(_.warning(e)),error:(e)=>console.error(_.error(e)),debug:(e)=>console.debug(_.dim(e))};async function k(){try{let e=`${j.cwd()}/routes/index.ts`,{router:t}=await import(e);if(!t)p.error(`Could not find router instance in ${e}.`),j.exit(1);return t}catch(e){if(e.code==="ERR_MODULE_NOT_FOUND")p.error(`Routes file not found at ${j.cwd()}/routes/index.ts`),p.warning('Make sure your routes are defined and exported as "router" in routes/index.ts');else p.error(`Error loading router: ${e.message}`);throw e}}function Pt(e){switch(e.toUpperCase()){case"GET":return c.cyan.toString();case"POST":return c.green.toString();case"PUT":return c.yellow.toString();case"PATCH":return c.yellow.toString();case"DELETE":return c.red.toString();case"OPTIONS":return c.gray.toString();default:return c.white.toString()}}async function Re(e){p.info("\uD83D\uDD0D Checking router health...");try{let t=await k(),s=t.routes||[],r=t.globalMiddleware||[],n=t.namedRoutes||new Map,o={totalRoutes:s.length,namedRoutes:n.size,globalMiddleware:r.length,routesByMethod:{},duplicateRoutes:[],routesWithMiddleware:0,staticRoutes:0,dynamicRoutes:0},l=new Map;for(let a of s){let i=`${a.method}:${a.path}`;if(o.routesByMethod[a.method]=(o.routesByMethod[a.method]||0)+1,!l.has(i))l.set(i,[]);if(l.get(i).push(a.path),l.get(i).length>1)o.duplicateRoutes.push({path:a.path,method:a.method});if(a.middleware&&a.middleware.length>0)o.routesWithMiddleware++;if(a.path.includes("{")||a.path.includes("*"))o.dynamicRoutes++;else o.staticRoutes++}if(p.success("Router health check completed"),console.log(`\uD83D\uDCCA Routes: ${o.totalRoutes} total (${o.staticRoutes} static, ${o.dynamicRoutes} dynamic)`),console.log(`\uD83D\uDCDB Named routes: ${o.namedRoutes}`),console.log(`\uD83D\uDEE1\uFE0F Global middleware: ${o.globalMiddleware}`),console.log(`\uD83D\uDD27 Routes with middleware: ${o.routesWithMiddleware}`),e.verbose){console.log(`
|
|
175
|
+
\uD83D\uDCC8 Routes by method:`);for(let[i,u]of Object.entries(o.routesByMethod)){let d=Pt(i);console.log(` ${c.hex(d)(i.padEnd(8))}: ${u}`)}if(o.duplicateRoutes.length>0){p.warning(`
|
|
176
|
+
\u26A0\uFE0F Found ${o.duplicateRoutes.length} duplicate route(s):`);for(let i of o.duplicateRoutes)console.log(` ${i.method} ${i.path}`)}let a=[];if(o.totalRoutes===0)a.push("No routes defined");if(o.duplicateRoutes.length>0)a.push(`${o.duplicateRoutes.length} duplicate routes`);if(o.routesWithMiddleware===0&&o.globalMiddleware===0)a.push("No middleware configured");if(a.length>0){p.warning(`
|
|
177
|
+
\u26A0\uFE0F Potential issues:`);for(let i of a)console.log(` \u2022 ${i}`)}else p.success(`
|
|
178
|
+
\u2705 No issues detected`)}}catch(t){throw p.error(`Health check failed: ${t.message}`),t}}async function Oe(e){let t=e.baseUrl||"http://localhost:3000",s=e.timeout||5000,r=e.method?e.method.split(",").map((n)=>n.trim().toUpperCase()):null;p.info(`\uD83E\uDDEA Testing routes at ${t}...`);try{let o=(await k()).routes||[],l=o;if(e.filter){let i=new RegExp(e.filter.replace(/\*/g,".*"));l=o.filter((u)=>i.test(u.path))}if(r)l=l.filter((i)=>r.includes(i.method));if(l.length===0){p.warning("No routes match the specified filters");return}p.info(`Testing ${l.length} routes...`);let a={total:0,passed:0,failed:0,errors:[]};for(let i of l){if(a.total++,i.path.includes("{")){p.debug(`Skipping parameterized route: ${i.method} ${i.path}`);continue}try{let u=`${t}${i.path}`,d=await fetch(u,{method:i.method,signal:AbortSignal.timeout(s)});if(d.status<500)a.passed++,p.debug(`\u2705 ${i.method} ${i.path} \u2192 ${d.status}`);else a.failed++,a.errors.push({route:`${i.method} ${i.path}`,error:`HTTP ${d.status}`})}catch(u){a.failed++,a.errors.push({route:`${i.method} ${i.path}`,error:u.message})}}if(console.log(`
|
|
179
|
+
\uD83D\uDCCA Test Results:`),console.log(` Total: ${a.total}`),console.log(` Passed: ${c.green(String(a.passed))}`),console.log(` Failed: ${c.red(String(a.failed))}`),a.errors.length>0){console.log(`
|
|
180
|
+
\u274C Failures:`);for(let i of a.errors)console.log(` ${i.route}: ${i.error}`)}if(a.failed>0)j.exit(1);else p.success("All tests passed!")}catch(n){throw p.error(`Route testing failed: ${n.message}`),n}}async function Se(e,t){let s=t.method?.toUpperCase()||"GET";p.info(`\uD83D\uDD0D Debugging route matching for: ${s} ${e}`);try{let r=await k(),n=r.matchRoute?r.matchRoute(e,s):null;if(n){if(p.success("\u2705 Route matched!"),console.log(` Route: ${n.route.method} ${n.route.path}`),console.log(` Handler: ${typeof n.route.handler}`),Object.keys(n.params||{}).length>0){console.log(" Parameters:");for(let[o,l]of Object.entries(n.params))console.log(` ${o}: ${l}`)}if(n.route.middleware&&n.route.middleware.length>0)console.log(` Middleware: ${n.route.middleware.length} handler(s)`);if(n.route.name)console.log(` Named route: ${n.route.name}`)}else if(p.error(`\u274C No route matched for ${s} ${e}`),t.verbose){console.log(`
|
|
181
|
+
\uD83D\uDCCB Available routes:`);let l=(r.routes||[]).filter((a)=>a.method===s);if(l.length===0)console.log(` No routes defined for ${s} method`);else for(let a of l)console.log(` ${a.method} ${a.path}`)}}catch(r){throw p.error(`Route debugging failed: ${r.message}`),r}}async function Te(e){p.info("\uD83D\uDDD1\uFE0F Clearing route caches...");try{let t=await k();if(e.stats){if(t.getCacheStats){let s=t.getCacheStats();console.log("\uD83D\uDCCA Cache statistics before clearing:"),console.log(` Hit rate: ${s.hitRate}%`),console.log(` Total hits: ${s.hits}`),console.log(` Total misses: ${s.misses}`),console.log(` Cache size: ${s.size}`)}if(t.routeCache)console.log(` Route cache entries: ${t.routeCache.size}`);if(t.templateCache)console.log(` Template cache entries: ${t.templateCache.size}`)}if(t.clearRouteCache)t.clearRouteCache();if(t.routeCache&&t.routeCache.clear)t.routeCache.clear();if(t.templateCache&&t.templateCache.clear)t.templateCache.clear();if(t.clearModelCache)t.clearModelCache();p.success("\u2705 Caches cleared successfully")}catch(t){throw p.error(`Cache clearing failed: ${t.message}`),t}}async function Ie(e){p.info("\uD83D\uDD0D Validating route definitions...");try{let s=(await k()).routes||[],r=[],n=[];for(let l of s){if(!l.method)r.push(`Route missing method: ${l.path}`);if(!l.path)r.push(`Route missing path: ${l.method||"UNKNOWN"}`);if(!l.handler)r.push(`Route missing handler: ${l.method} ${l.path}`);if(l.path&&!l.path.startsWith("/"))r.push(`Route path should start with '/': ${l.method} ${l.path}`);if(l.path&&l.path.includes("{")){let a=l.path.match(/\{[^}]+\}/g)||[];for(let i of a)if(!i.match(/^\{[a-z_]\w*(\?|:[^}]+)?\}$/i))r.push(`Invalid parameter syntax in ${l.method} ${l.path}: ${i}`)}if(e.strict){if(!l.name&&!l.path.includes("{")&&l.path!=="/")n.push(`Consider adding a name to route: ${l.method} ${l.path}`);if(l.path.includes("/admin")&&(!l.middleware||l.middleware.length===0))n.push(`Admin route missing middleware: ${l.method} ${l.path}`)}}let o=new Map;for(let l of s){let a=`${l.method}:${l.path}`;o.set(a,(o.get(a)||0)+1)}for(let[l,a]of o.entries())if(a>1)r.push(`Duplicate route detected: ${l} (${a} times)`);if(r.length===0&&n.length===0){p.success("\u2705 All route definitions are valid");return}if(r.length>0){p.error(`\u274C Found ${r.length} validation error(s):`);for(let l of r)console.log(` \u2022 ${l}`)}if(n.length>0){p.warning(`\u26A0\uFE0F Found ${n.length} warning(s):`);for(let l of n)console.log(` \u2022 ${l}`)}if(e.fix)p.info("\uD83D\uDD27 Auto-fixing is not yet implemented");if(r.length>0)j.exit(1)}catch(t){throw p.error(`Route validation failed: ${t.message}`),t}}function Ee(){let e=new J("router");return e.version(pe),Vt(e),Dt(e),Ft(e),Wt(e),Ut(e),e.help(),e}function Vt(e){e.command("route:list","List all registered routes").option("-v, --verbose","Show detailed information including middleware").option("-vv, --extra-verbose","Show very detailed information").option("--path <path>","Filter routes by path prefix").option("--except-vendor","Exclude vendor routes").option("--only-vendor","Show only vendor routes").example("router route:list").example("router route:list -v").example("router route:list --path=/api").action(async(t)=>{try{await xe(t)}catch(s){console.error(`Failed to list routes: ${s.message}`),v.exit(1)}}),e.command("route:types","Generate TypeScript types for route names").option("--output <file>","Output file path",{default:"route-types.ts"}).option("--watch","Watch for changes in routes directory").example("router route:types").example("router route:types --output src/types/routes.ts").example("router route:types --watch").action(async(t)=>{try{let s=t.output||"route-types.ts";if(t.watch)await Ce(s);else await W(s)}catch(s){console.error(`Failed to generate route types: ${s.message}`),v.exit(1)}})}function Dt(e){e.command("middleware:types","Generate TypeScript types for middleware configurations").option("--output <file>","Output file path",{default:"middleware-types.ts"}).option("--watch","Watch for changes in middleware directory").example("router middleware:types").example("router middleware:types --output src/types/middleware.ts").example("router middleware:types --watch").action(async(t)=>{try{let s=t.output||"middleware-types.ts";if(t.watch)await $e(s);else await P(s)}catch(s){console.error(`Failed to generate middleware types: ${s.message}`),v.exit(1)}}),e.command("middleware:map","Generate TypeScript types for all middleware in the project").option("--dir <directory>","Directory to scan for middleware classes",{default:"src"}).option("--output <file>","Output file path",{default:"middleware-map.ts"}).option("--watch","Watch for changes in the specified directory").example("router middleware:map").example("router middleware:map --dir app").example("router middleware:map --output src/types/project-middleware.ts").example("router middleware:map --watch").action(async(t)=>{try{let s=t.output||"middleware-map.ts",r=t.dir||"src";if(t.watch)await ye(r,s);else await V(r,s)}catch(s){console.error(`Failed to generate middleware map: ${s.message}`),v.exit(1)}})}function Ft(e){e.command("router:types","Generate TypeScript types for router extensions").option("--output <file>","Output file path",{default:"router-types.ts"}).option("--watch","Watch for changes in router files").example("router router:types").example("router router:types --output src/types/router.ts").example("router router:types --watch").action(async(t)=>{try{let s=t.output||"router-types.ts";if(t.watch)await ve(s);else await D(s)}catch(s){console.error(`Failed to generate router types: ${s.message}`),v.exit(1)}})}function Wt(e){e.command("openapi","Generate OpenAPI specification for API routes").option("--output <file>","Output file path",{default:"openapi.json"}).option("--title <title>","API title",{default:"API Documentation"}).option("--version <version>","API version",{default:"1.0.0"}).option("--description <description>","API description").option("--base-path <path>","Base API path",{default:"/"}).option("--servers <urls>","Comma-separated list of server URLs").option("--tags","Group endpoints by tags",{default:!0}).option("--security","Include security schemes if available",{default:!0}).example("router openapi").example("router openapi --output api-spec.json").example('router openapi --title "My API" --version 2.0').example("router openapi --servers http://localhost:3000,https://api.example.com").action(async(t)=>{try{await we(t)}catch(s){console.error(`Failed to generate OpenAPI specification: ${s.message}`),v.exit(1)}})}function Ut(e){e.command("health","Check router health and configuration").option("--verbose","Show detailed health information").example("router health").example("router health --verbose").action(async(t)=>{try{await Re(t)}catch(s){console.error(`Health check failed: ${s.message}`),v.exit(1)}}),e.command("test:routes","Test routes by making HTTP requests").option("--base-url <url>","Base URL for testing",{default:"http://localhost:3000"}).option("--filter <pattern>","Filter routes by path pattern").option("--method <methods>","Test only specific HTTP methods (comma-separated)").option("--timeout <ms>","Request timeout in milliseconds",{default:5000}).example("router test:routes").example("router test:routes --base-url http://localhost:8080").example('router test:routes --filter "/api/*"').example("router test:routes --method GET,POST").action(async(t)=>{try{await Oe(t)}catch(s){console.error(`Route testing failed: ${s.message}`),v.exit(1)}}),e.command("debug:route <path>","Debug route matching for a specific path").option("--method <method>","HTTP method to test",{default:"GET"}).option("--verbose","Show detailed matching information").example("router debug:route /api/users/123").example("router debug:route /api/users/123 --method POST --verbose").action(async(t,s)=>{try{await Se(t,s)}catch(r){console.error(`Route debugging failed: ${r.message}`),v.exit(1)}}),e.command("cache:clear","Clear route caches").option("--stats","Show cache statistics before clearing").example("router cache:clear").example("router cache:clear --stats").action(async(t)=>{try{await Te(t)}catch(s){console.error(`Cache clearing failed: ${s.message}`),v.exit(1)}}),e.command("validate","Validate route definitions and configuration").option("--strict","Use strict validation rules").option("--fix","Automatically fix simple issues").example("router validate").example("router validate --strict --fix").action(async(t)=>{try{await Ie(t)}catch(s){console.error(`Route validation failed: ${s.message}`),v.exit(1)}})}var Ht=Ee();Ht.parse();
|