@stacksjs/bun-router 0.0.27 → 0.1.1

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.
Files changed (108) hide show
  1. package/dist/chunk-03m2j6h7.js +2 -0
  2. package/dist/chunk-08cw7ejr.js +3 -0
  3. package/dist/chunk-0e4g0fyv.js +62 -0
  4. package/dist/chunk-0mmn02yw.js +2 -0
  5. package/dist/chunk-126c9qm3.js +2 -0
  6. package/dist/chunk-12p13817.js +2 -0
  7. package/dist/chunk-14v65c37.js +4 -0
  8. package/dist/chunk-1b6a7t3v.js +231 -0
  9. package/dist/chunk-1wenkmk0.js +2 -0
  10. package/dist/chunk-2152npfd.js +2 -0
  11. package/dist/chunk-26w23krx.js +2 -0
  12. package/dist/chunk-2g8m379z.js +10 -0
  13. package/dist/chunk-2rr178et.js +1654 -0
  14. package/dist/chunk-2w8f3swz.js +29 -0
  15. package/dist/chunk-3y4gaz7v.js +82 -0
  16. package/dist/chunk-4r1x4afz.js +12 -0
  17. package/dist/chunk-4wyw66zk.js +2 -0
  18. package/dist/chunk-4z5sf8ag.js +2 -0
  19. package/dist/chunk-58tfvayh.js +4 -0
  20. package/dist/chunk-5be9x5cq.js +3 -0
  21. package/dist/chunk-5dp83qcx.js +397 -0
  22. package/dist/chunk-5f0d9j9a.js +2 -0
  23. package/dist/chunk-5z52b0fc.js +28 -0
  24. package/dist/chunk-5zrnk2kq.js +4 -0
  25. package/dist/chunk-6bbmkwng.js +3 -0
  26. package/dist/chunk-6dmqtdnq.js +2 -0
  27. package/dist/chunk-6e91956t.js +3 -0
  28. package/dist/chunk-6rv8w5jk.js +2 -0
  29. package/dist/chunk-6x1feysm.js +3 -0
  30. package/dist/chunk-7qnxdedn.js +321 -0
  31. package/dist/chunk-7y72hm1x.js +2 -0
  32. package/dist/chunk-8hbhfh6b.js +194 -0
  33. package/dist/chunk-8kfzygg5.js +3 -0
  34. package/dist/chunk-8wpj3fqe.js +351 -0
  35. package/dist/chunk-8wydx2we.js +2 -0
  36. package/dist/chunk-8zjnjvv7.js +2 -0
  37. package/dist/chunk-9805tt8n.js +341 -0
  38. package/dist/chunk-988h4bzr.js +2 -0
  39. package/dist/chunk-9b6a58ac.js +2 -0
  40. package/dist/chunk-a8fcaywb.js +2 -0
  41. package/dist/chunk-bfjwn7yg.js +2 -0
  42. package/dist/chunk-bp2522mm.js +2 -0
  43. package/dist/chunk-brpgjyqg.js +3 -0
  44. package/dist/chunk-bswe62q4.js +48 -0
  45. package/dist/chunk-c3v796c8.js +943 -0
  46. package/dist/chunk-ccqmwdry.js +2 -0
  47. package/dist/chunk-ck0crwnx.js +2 -0
  48. package/dist/chunk-cqgkxcb4.js +2 -0
  49. package/dist/chunk-dntnakjy.js +2 -0
  50. package/dist/chunk-dxg045wj.js +5 -0
  51. package/dist/chunk-e3qej0jr.js +4 -0
  52. package/dist/chunk-ettdpnrw.js +60 -0
  53. package/dist/chunk-ezqwq17j.js +185 -0
  54. package/dist/chunk-ezx3qsez.js +2 -0
  55. package/dist/chunk-f72nnjy4.js +15413 -0
  56. package/dist/chunk-fna5n0ey.js +246 -0
  57. package/dist/chunk-fqhckdt8.js +2 -0
  58. package/dist/chunk-fr6hbx25.js +2 -0
  59. package/dist/chunk-g9cwng6w.js +3 -0
  60. package/dist/chunk-gd3za5x0.js +2 -0
  61. package/dist/chunk-gf28608k.js +2 -0
  62. package/dist/chunk-h1dj6v8q.js +3 -0
  63. package/dist/chunk-hjxe7k2g.js +2 -0
  64. package/dist/chunk-hrkgznbn.js +2 -0
  65. package/dist/chunk-j6h5v0br.js +2 -0
  66. package/dist/chunk-kjtjbcq4.js +71 -0
  67. package/dist/chunk-mgb01qdv.js +14 -0
  68. package/dist/chunk-n24c9whp.js +2 -0
  69. package/dist/chunk-n2j24b0h.js +4540 -0
  70. package/dist/chunk-nf3kv7kv.js +3 -0
  71. package/dist/chunk-nhmtg01n.js +84 -0
  72. package/dist/chunk-p0qhpnqh.js +70 -0
  73. package/dist/chunk-p0w1x8y2.js +3 -0
  74. package/dist/chunk-p3dk1w2w.js +216 -0
  75. package/dist/chunk-q4e9pxs7.js +3 -0
  76. package/dist/chunk-q5dv1kyy.js +2 -0
  77. package/dist/chunk-qnqgf9tq.js +2 -0
  78. package/dist/chunk-qvwy1808.js +898 -0
  79. package/dist/chunk-r18f77vc.js +12 -0
  80. package/dist/chunk-r63za1mr.js +2 -0
  81. package/dist/chunk-rft8gw92.js +7851 -0
  82. package/dist/chunk-ryvmyskt.js +4211 -0
  83. package/dist/chunk-sa6mx308.js +2 -0
  84. package/dist/chunk-sw0chtw4.js +4 -0
  85. package/dist/chunk-va0pc7hx.js +2 -0
  86. package/dist/chunk-vcp8dnjq.js +412 -0
  87. package/dist/chunk-vg1erq1q.js +2 -0
  88. package/dist/chunk-vsh4390q.js +358 -0
  89. package/dist/chunk-w0jv49ch.js +11 -0
  90. package/dist/chunk-wm805tte.js +35 -0
  91. package/dist/chunk-xg9xscqz.js +1 -0
  92. package/dist/chunk-xj9h6mc9.js +2 -0
  93. package/dist/chunk-ytvzwrq3.js +51 -0
  94. package/dist/chunk-zde7ebc4.js +288 -0
  95. package/dist/chunk-zmqsv2xy.js +2 -0
  96. package/dist/cli.js +51 -3233
  97. package/dist/container/index.js +1 -321
  98. package/dist/index.d.ts +1 -0
  99. package/dist/index.js +80 -13987
  100. package/dist/typed/client.d.ts +89 -0
  101. package/dist/typed/contract.d.ts +34 -0
  102. package/dist/typed/endpoint.d.ts +90 -0
  103. package/dist/typed/index.d.ts +14 -0
  104. package/dist/typed/router.d.ts +141 -0
  105. package/package.json +1 -1
  106. package/dist/chunk-1ahs68ys.js +0 -18
  107. package/dist/chunk-cgptvjdf.js +0 -18131
  108. package/dist/chunk-g3ybefhg.js +0 -1923
package/dist/cli.js CHANGED
@@ -1,2197 +1,86 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import {
4
- middleware
5
- } from "./chunk-cgptvjdf.js";
6
- import"./chunk-1ahs68ys.js";
7
-
8
- // src/cli/index.ts
9
- import process15 from "process";
10
-
11
- // ../../node_modules/@stacksjs/clapp/dist/index.js
12
- import { existsSync } from "fs";
13
- import fs from "fs/promises";
14
- import os from "os";
15
- import path from "path";
16
- import process from "process";
17
- import { EventEmitter } from "events";
18
- import process5 from "process";
19
- import process2 from "process";
20
- import process3 from "process";
21
- import process4 from "process";
22
- import process7 from "process";
23
- import tty from "tty";
24
- import process8, { stdin, stdout } from "process";
25
- import process9, { stdin as stdin2, stdout as stdout2 } from "process";
26
- import readline2 from "readline";
27
- class Telemetry {
28
- configPath;
29
- config = null;
30
- events = [];
31
- retryCount = 0;
32
- maxRetries = 3;
33
- retryDelayMs = 1000;
34
- constructor() {
35
- const homeDir = os.homedir();
36
- const configDir = path.join(homeDir, ".config", "clapp");
37
- this.configPath = path.join(configDir, "telemetry.json");
38
- }
39
- async isEnabled() {
40
- if (process.env.DO_NOT_TRACK === "1" || process.env.DO_NOT_TRACK === "true") {
41
- return false;
42
- }
43
- if (process.env.NO_TELEMETRY === "1" || process.env.NO_TELEMETRY === "true") {
44
- return false;
45
- }
46
- const config = await this.loadConfig();
47
- return config.enabled;
48
- }
49
- async enable() {
50
- const config = await this.loadConfig();
51
- config.enabled = true;
52
- if (!config.userId) {
53
- config.userId = this.generateUserId();
54
- }
55
- await this.saveConfig(config);
56
- }
57
- async disable() {
58
- const config = await this.loadConfig();
59
- config.enabled = false;
60
- await this.saveConfig(config);
61
- }
62
- async track(event, data) {
63
- const enabled = await this.isEnabled();
64
- if (!enabled) {
65
- return;
66
- }
67
- const telemetryEvent = {
68
- event,
69
- ...data,
70
- timestamp: Date.now(),
71
- platform: os.platform(),
72
- nodeVersion: process.version
73
- };
74
- this.events.push(telemetryEvent);
75
- if (this.events.length >= 10) {
76
- await this.send();
77
- }
78
- }
79
- async trackCommand(command, duration) {
80
- await this.track("command", {
81
- command,
82
- duration
83
- });
84
- }
85
- async trackError(error, command) {
86
- await this.track("error", {
87
- error,
88
- command
89
- });
90
- }
91
- async send() {
92
- const enabled = await this.isEnabled();
93
- if (!enabled || this.events.length === 0) {
94
- return true;
95
- }
96
- try {
97
- this.events = [];
98
- this.retryCount = 0;
99
- const config = await this.loadConfig();
100
- config.lastSent = Date.now();
101
- await this.saveConfig(config);
102
- return true;
103
- } catch {
104
- if (this.retryCount < this.maxRetries) {
105
- this.retryCount++;
106
- const delay = this.retryDelayMs * 2 ** (this.retryCount - 1);
107
- await this.sleep(delay);
108
- return this.send();
109
- }
110
- this.events = [];
111
- this.retryCount = 0;
112
- return false;
113
- }
114
- }
115
- async flush() {
116
- if (this.events.length === 0) {
117
- return true;
118
- }
119
- return this.send();
120
- }
121
- sleep(ms) {
122
- return new Promise((resolve) => setTimeout(resolve, ms));
123
- }
124
- async status() {
125
- const config = await this.loadConfig();
126
- return {
127
- enabled: config.enabled,
128
- doNotTrack: process.env.DO_NOT_TRACK === "1" || process.env.DO_NOT_TRACK === "true",
129
- eventsQueued: this.events.length,
130
- lastSent: config.lastSent
131
- };
132
- }
133
- async loadConfig() {
134
- if (this.config) {
135
- return this.config;
136
- }
137
- try {
138
- if (existsSync(this.configPath)) {
139
- const data = await fs.readFile(this.configPath, "utf-8");
140
- this.config = JSON.parse(data);
141
- return this.config;
142
- }
143
- } catch {}
144
- this.config = {
145
- enabled: false
146
- };
147
- return this.config;
148
- }
149
- async saveConfig(config) {
150
- this.config = config;
151
- try {
152
- const configDir = path.dirname(this.configPath);
153
- await fs.mkdir(configDir, { recursive: true });
154
- await fs.writeFile(this.configPath, JSON.stringify(config, null, 2), "utf-8");
155
- } catch {}
156
- }
157
- generateUserId() {
158
- const random = Math.random().toString(36).substring(2, 15);
159
- const timestamp = Date.now().toString(36);
160
- return `${random}-${timestamp}`;
161
- }
162
- }
163
- var telemetry = new Telemetry;
164
- function parseArgv(argv, opts = {}) {
165
- const result = { _: [] };
166
- const alias = opts.alias || {};
167
- const booleans = new Set(opts.boolean || []);
168
- const aliasOf = {};
169
- for (const key of Object.keys(alias)) {
170
- for (const a of alias[key]) {
171
- aliasOf[a] = key;
172
- }
173
- }
174
- for (const b of booleans) {
175
- if (alias[b]) {
176
- for (const a of alias[b])
177
- booleans.add(a);
178
- }
179
- }
180
- function setKey(key, value) {
181
- const canonical = aliasOf[key] || key;
182
- result[canonical] = value;
183
- if (alias[canonical]) {
184
- for (const a of alias[canonical])
185
- result[a] = value;
186
- }
187
- if (aliasOf[key] && alias[aliasOf[key]]) {
188
- for (const a of alias[aliasOf[key]])
189
- result[a] = value;
190
- }
191
- result[key] = value;
192
- }
193
- for (let i = 0;i < argv.length; i++) {
194
- const arg = argv[i];
195
- if (arg === "--") {
196
- result._.push(...argv.slice(i + 1));
197
- break;
198
- }
199
- if (arg.startsWith("--")) {
200
- const eqIdx = arg.indexOf("=");
201
- if (eqIdx !== -1) {
202
- const key = arg.slice(2, eqIdx);
203
- const value = arg.slice(eqIdx + 1);
204
- setKey(key, value);
205
- } else {
206
- const key = arg.slice(2);
207
- if (key.startsWith("no-")) {
208
- const actualKey = key.slice(3);
209
- setKey(actualKey, false);
210
- continue;
211
- }
212
- const canonical = aliasOf[key] || key;
213
- if (booleans.has(canonical) || booleans.has(key)) {
214
- setKey(key, true);
215
- } else {
216
- const next = argv[i + 1];
217
- if (next !== undefined && !next.startsWith("-")) {
218
- setKey(key, next);
219
- i++;
220
- } else {
221
- setKey(key, true);
222
- }
223
- }
224
- }
225
- } else if (arg.startsWith("-") && arg.length > 1) {
226
- const chars = arg.slice(1);
227
- for (let j = 0;j < chars.length; j++) {
228
- const ch = chars[j];
229
- const canonical = aliasOf[ch] || ch;
230
- if (j === chars.length - 1 && !booleans.has(canonical) && !booleans.has(ch)) {
231
- const next = argv[i + 1];
232
- if (next !== undefined && !next.startsWith("-")) {
233
- setKey(ch, next);
234
- i++;
235
- } else {
236
- setKey(ch, true);
237
- }
238
- } else {
239
- setKey(ch, true);
240
- }
241
- }
242
- } else {
243
- result._.push(arg);
244
- }
245
- }
246
- return result;
247
- }
248
- function removeBrackets(v) {
249
- return v.replace(/[<[].+/, "").trim();
250
- }
251
- function findAllBrackets(v) {
252
- const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
253
- const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
254
- const res = [];
255
- const parse = (match) => {
256
- let variadic = false;
257
- let value = match[1];
258
- if (value.startsWith("...")) {
259
- value = value.slice(3);
260
- variadic = true;
261
- }
262
- return {
263
- required: match[0].startsWith("<"),
264
- value,
265
- variadic
266
- };
267
- };
268
- let angledMatch;
269
- while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) {
270
- res.push(parse(angledMatch));
271
- }
272
- let squareMatch;
273
- while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) {
274
- res.push(parse(squareMatch));
275
- }
276
- return res;
277
- }
278
- function getMriOptions(options) {
279
- const result = { alias: {}, boolean: [] };
280
- for (const [index, option] of options.entries()) {
281
- if (option.names.length > 1) {
282
- result.alias[option.names[0]] = option.names.slice(1);
283
- }
284
- if (option.isBoolean) {
285
- if (option.negated) {
286
- const hasStringTypeOption = options.some((o, i) => {
287
- return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean";
288
- });
289
- if (!hasStringTypeOption) {
290
- result.boolean.push(option.names[0]);
291
- }
292
- } else {
293
- result.boolean.push(option.names[0]);
294
- }
295
- }
296
- }
297
- return result;
298
- }
299
- function findLongest(arr) {
300
- return arr.reduce((a, b) => a.length >= b.length ? a : b, "");
301
- }
302
- function padRight(str, length) {
303
- return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
304
- }
305
- function camelcase(input) {
306
- return input.replace(/([a-z])-([a-z])/g, (_, p1, p2) => {
307
- return p1 + p2.toUpperCase();
308
- });
309
- }
310
- function setDotProp(obj, keys, val) {
311
- let i = 0;
312
- const length = keys.length;
313
- let t = obj;
314
- let x;
315
- for (;i < length; ++i) {
316
- x = t[keys[i]];
317
- t = t[keys[i]] = i === length - 1 ? val : x != null ? x : !!~keys[i + 1].indexOf(".") || !(+keys[i + 1] > -1) ? {} : [];
318
- }
319
- }
320
- function setByType(obj, transforms) {
321
- for (const key of Object.keys(transforms)) {
322
- const transform = transforms[key];
323
- if (transform.shouldTransform) {
324
- obj[key] = Array.prototype.concat.call([], obj[key]);
325
- if (typeof transform.transformFunction === "function") {
326
- obj[key] = obj[key].map(transform.transformFunction);
327
- }
328
- }
329
- }
330
- }
331
- function getFileName(input) {
332
- const m = /([^\\/]+)$/.exec(input);
333
- return m ? m[1] : "";
334
- }
335
- function camelcaseOptionName(name) {
336
- return name.split(".").map((v, i) => {
337
- return i === 0 ? camelcase(v) : v;
338
- }).join(".");
339
- }
340
-
341
- class ClappError extends Error {
342
- exitCode = 2;
343
- isUsageError = true;
344
- constructor(message) {
345
- super(message);
346
- this.name = this.constructor.name;
347
- if (typeof Error.captureStackTrace === "function") {
348
- Error.captureStackTrace(this, this.constructor);
349
- } else {
350
- this.stack = new Error(message).stack;
351
- }
352
- }
353
- format(showStack = false) {
354
- if (showStack && this.stack) {
355
- return `${this.message}
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}
356
4
 
357
5
  Stack trace:
358
- ${this.stack}`;
359
- }
360
- return this.message;
361
- }
362
- }
363
- function isUnicodeSupported() {
364
- const { env } = process2;
365
- const { TERM, TERM_PROGRAM } = env;
366
- if (process2.platform !== "win32") {
367
- return TERM !== "linux";
368
- }
369
- return Boolean(env.WT_SESSION) || Boolean(env.TERMINUS_SUBLIME) || env.ConEmuTask === "{cmd::Cmder}" || TERM_PROGRAM === "Terminus-Sublime" || TERM_PROGRAM === "vscode" || TERM === "xterm-256color" || TERM === "alacritty" || TERM === "rxvt-unicode" || TERM === "rxvt-unicode-256color" || env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
370
- }
371
- var ESC = "\x1B";
372
- var CSI = `${ESC}[`;
373
- var cursor = {
374
- to(x, y) {
375
- if (!y)
376
- return `${CSI}${x + 1}G`;
377
- return `${CSI}${y + 1};${x + 1}H`;
378
- },
379
- move(x, y) {
380
- let ret = "";
381
- if (x < 0)
382
- ret += `${CSI}${-x}D`;
383
- else if (x > 0)
384
- ret += `${CSI}${x}C`;
385
- if (y < 0)
386
- ret += `${CSI}${-y}A`;
387
- else if (y > 0)
388
- ret += `${CSI}${y}B`;
389
- return ret;
390
- },
391
- up: (count = 1) => `${CSI}${count}A`,
392
- down: (count = 1) => `${CSI}${count}B`,
393
- forward: (count = 1) => `${CSI}${count}C`,
394
- backward: (count = 1) => `${CSI}${count}D`,
395
- nextLine: (count = 1) => `${CSI}E`.repeat(count),
396
- prevLine: (count = 1) => `${CSI}F`.repeat(count),
397
- left: `${CSI}G`,
398
- hide: `${CSI}?25l`,
399
- show: `${CSI}?25h`,
400
- save: `${ESC}7`,
401
- restore: `${ESC}8`
402
- };
403
- var erase = {
404
- screen: `${CSI}2J`,
405
- up: (count = 1) => `${CSI}1J`.repeat(count),
406
- down: (count = 1) => `${CSI}J`.repeat(count),
407
- line: `${CSI}2K`,
408
- lineEnd: `${CSI}K`,
409
- lineStart: `${CSI}1K`,
410
- lines(count) {
411
- let clear = "";
412
- for (let i = 0;i < count; i++)
413
- clear += this.line + (i < count - 1 ? cursor.up() : "");
414
- if (count)
415
- clear += cursor.left;
416
- return clear;
417
- }
418
- };
419
- var clear = {
420
- screen: `${ESC}c`
421
- };
422
- function levenshteinDistance(a, b) {
423
- const matrix = [];
424
- for (let i = 0;i <= b.length; i++) {
425
- matrix[i] = [i];
426
- }
427
- for (let j = 0;j <= a.length; j++) {
428
- matrix[0][j] = j;
429
- }
430
- for (let i = 1;i <= b.length; i++) {
431
- for (let j = 1;j <= a.length; j++) {
432
- if (b.charAt(i - 1) === a.charAt(j - 1)) {
433
- matrix[i][j] = matrix[i - 1][j - 1];
434
- } else {
435
- matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j] + 1);
436
- }
437
- }
438
- }
439
- return matrix[b.length][a.length];
440
- }
441
- function findSimilarCommands(input, commands, maxDistance = 2, maxSuggestions = 3) {
442
- return commands.map((cmd) => ({ cmd, distance: levenshteinDistance(input, cmd) })).filter(({ distance }) => distance <= maxDistance).sort((a, b) => a.distance - b.distance).slice(0, maxSuggestions).map(({ cmd }) => cmd);
443
- }
444
-
445
- class Option {
446
- rawName;
447
- description;
448
- name;
449
- names;
450
- isBoolean;
451
- required;
452
- config;
453
- negated;
454
- constructor(rawName, description, config) {
455
- this.rawName = rawName;
456
- this.description = description;
457
- this.config = Object.assign({}, config);
458
- rawName = rawName.replace(/\.\*/g, "");
459
- this.negated = false;
460
- this.names = removeBrackets(rawName).split(",").map((v) => {
461
- let name = v.trim().replace(/^-{1,2}/, "");
462
- if (name.startsWith("no-")) {
463
- this.negated = true;
464
- name = name.replace(/^no-/, "");
465
- }
466
- return camelcaseOptionName(name);
467
- }).sort((a, b) => a.length > b.length ? 1 : -1);
468
- this.name = this.names[this.names.length - 1];
469
- if (this.negated && this.config.default == null) {
470
- this.config.default = true;
471
- }
472
- if (rawName.includes("<")) {
473
- this.required = true;
474
- } else if (rawName.includes("[")) {
475
- this.required = false;
476
- } else {
477
- this.isBoolean = true;
478
- }
479
- }
480
- }
481
- var processArgs = process3.argv;
482
- var platformInfo = `${process3.platform}-${process3.arch} bun-v${typeof Bun !== "undefined" ? Bun.version : "unknown"}`;
483
- var processArgs2 = process4.argv;
484
- var platformInfo2 = `${process4.platform}-${process4.arch} node-${process4.version}`;
485
-
486
- class Command {
487
- rawName;
488
- description;
489
- config;
490
- cli;
491
- options;
492
- aliasNames;
493
- name;
494
- namespace;
495
- args;
496
- commandAction;
497
- usageText;
498
- versionNumber;
499
- examples;
500
- helpCallback;
501
- globalCommand;
502
- beforeHooks;
503
- afterHooks;
504
- middleware;
505
- constructor(rawName, description, config, cli) {
506
- this.rawName = rawName;
507
- this.description = description;
508
- this.config = config;
509
- this.cli = cli;
510
- this.options = [];
511
- this.aliasNames = [];
512
- this.name = removeBrackets(rawName);
513
- const nameWithoutBrackets = removeBrackets(rawName);
514
- const colonIndex = nameWithoutBrackets.indexOf(":");
515
- if (colonIndex > 0) {
516
- this.namespace = nameWithoutBrackets.substring(0, colonIndex);
517
- this.name = nameWithoutBrackets.substring(colonIndex + 1);
518
- }
519
- this.args = findAllBrackets(rawName);
520
- this.examples = [];
521
- this.beforeHooks = [];
522
- this.afterHooks = [];
523
- this.middleware = [];
524
- if (!config) {
525
- this.config = {};
526
- }
527
- }
528
- usage(text) {
529
- this.usageText = text;
530
- return this;
531
- }
532
- allowUnknownOptions() {
533
- this.config.allowUnknownOptions = true;
534
- return this;
535
- }
536
- ignoreOptionDefaultValue() {
537
- this.config.ignoreOptionDefaultValue = true;
538
- return this;
539
- }
540
- version(version, customFlags = "-v, --version") {
541
- this.versionNumber = version;
542
- this.option(customFlags, "Display version number");
543
- return this;
544
- }
545
- example(example) {
546
- this.examples.push(example);
547
- return this;
548
- }
549
- option(rawName, description, config) {
550
- const option = new Option(rawName, description, config);
551
- this.options.push(option);
552
- return this;
553
- }
554
- alias(name) {
555
- this.aliasNames.push(name);
556
- return this;
557
- }
558
- action(callback) {
559
- this.commandAction = callback;
560
- return this;
561
- }
562
- before(handler) {
563
- this.beforeHooks.push(handler);
564
- return this;
565
- }
566
- after(handler) {
567
- this.afterHooks.push(handler);
568
- return this;
569
- }
570
- use(handler) {
571
- this.middleware.push(handler);
572
- return this;
573
- }
574
- isMatched(name) {
575
- if (this.aliasNames.includes(name))
576
- return true;
577
- if (this.namespace)
578
- return `${this.namespace}:${this.name}` === name;
579
- return this.name === name;
580
- }
581
- get isDefaultCommand() {
582
- return this.name === "" || this.aliasNames.includes("!");
583
- }
584
- get isGlobalCommand() {
585
- return this instanceof GlobalCommand;
586
- }
587
- get displayName() {
588
- return this.namespace ? `${this.namespace}:${this.name}` : this.name;
589
- }
590
- hasOption(name) {
591
- name = name.split(".")[0];
592
- return !!this.options.find((option) => {
593
- return option.names.includes(name);
594
- });
595
- }
596
- outputHelp() {
597
- const { name, commands } = this.cli;
598
- const {
599
- versionNumber,
600
- options: globalOptions,
601
- helpCallback
602
- } = this.cli.globalCommand;
603
- let sections = [
604
- {
605
- body: `${name}${versionNumber ? `/${versionNumber}` : ""}`
606
- }
607
- ];
608
- sections.push({
609
- title: "Usage",
610
- body: ` $ ${name} ${this.usageText || this.rawName}`
611
- });
612
- const showCommands = (this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0;
613
- if (showCommands) {
614
- const longestCommandName = findLongest(commands.map((command) => command.rawName));
615
- const namespaceGroups = new Map;
616
- const noNamespaceCommands = [];
617
- for (const command of commands) {
618
- if (command.namespace) {
619
- if (!namespaceGroups.has(command.namespace)) {
620
- namespaceGroups.set(command.namespace, []);
621
- }
622
- namespaceGroups.get(command.namespace).push(command);
623
- } else {
624
- noNamespaceCommands.push(command);
625
- }
626
- }
627
- let commandBody = "";
628
- if (noNamespaceCommands.length > 0) {
629
- commandBody += noNamespaceCommands.map((command) => {
630
- return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`;
631
- }).join(`
632
- `);
633
- }
634
- const sortedNamespaces = Array.from(namespaceGroups.keys()).sort();
635
- for (const namespace of sortedNamespaces) {
636
- const namespaceCommands = namespaceGroups.get(namespace);
637
- if (commandBody.length > 0) {
638
- commandBody += `
639
-
640
- `;
641
- }
642
- commandBody += ` ${namespace}:
643
- `;
644
- commandBody += namespaceCommands.map((command) => {
645
- return ` ${padRight(command.rawName, longestCommandName.length - 2)} ${command.description}`;
646
- }).join(`
647
- `);
648
- }
649
- sections.push({
650
- title: "Commands",
651
- body: commandBody
652
- });
653
- sections.push({
654
- title: `For more info, run any command with the \`--help\` flag`,
655
- body: commands.map((command) => ` $ ${name}${command.displayName === "" ? "" : ` ${command.displayName}`} --help`).join(`
656
- `)
657
- });
658
- }
659
- let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
660
- if (!this.isGlobalCommand && !this.isDefaultCommand) {
661
- options = options.filter((option) => option.name !== "version");
662
- }
663
- if (options.length > 0) {
664
- const longestOptionName = findLongest(options.map((option) => option.rawName));
665
- sections.push({
666
- title: "Options",
667
- body: options.map((option) => {
668
- return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === undefined ? "" : `(default: ${option.config.default})`}`;
669
- }).join(`
670
- `)
671
- });
672
- }
673
- if (this.examples.length > 0) {
674
- sections.push({
675
- title: "Examples",
676
- body: this.examples.map((example) => {
677
- if (typeof example === "function") {
678
- return example(name);
679
- }
680
- return example;
681
- }).join(`
682
- `)
683
- });
684
- }
685
- if (helpCallback) {
686
- sections = helpCallback(sections) || sections;
687
- }
688
- console.log(sections.map((section) => {
689
- return section.title ? `${section.title}:
690
- ${section.body}` : section.body;
691
- }).join(`
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+=`
692
8
 
693
- `));
694
- }
695
- outputVersion() {
696
- const { name } = this.cli;
697
- const { versionNumber } = this.cli.globalCommand;
698
- if (versionNumber) {
699
- const platformInfo3 = typeof Bun !== "undefined" ? platformInfo : platformInfo2;
700
- console.log(`${name}/${versionNumber} ${platformInfo3}`);
701
- }
702
- }
703
- checkRequiredArgs() {
704
- const minimalArgsCount = this.args.filter((arg) => arg.required).length;
705
- if (this.cli.args.length < minimalArgsCount) {
706
- const requiredArgs = this.args.filter((arg) => arg.required);
707
- const missingArgs = requiredArgs.slice(this.cli.args.length);
708
- const argNames = missingArgs.map((arg) => `<${arg.value}>`).join(" ");
709
- throw new ClappError(`Missing required argument${missingArgs.length > 1 ? "s" : ""}: ${argNames}
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(`
710
16
 
711
- ` + `Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`);
712
- }
713
- }
714
- checkUnknownOptions() {
715
- const { options, globalCommand } = this.cli;
716
- if (!this.config.allowUnknownOptions) {
717
- for (const name of Object.keys(options)) {
718
- if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) {
719
- const allOptions = [...globalCommand.options, ...this.options];
720
- const allOptionNames = allOptions.flatMap((opt) => opt.names);
721
- const optionFlag = name.length > 1 ? `--${name}` : `-${name}`;
722
- const suggestions = findSimilarCommands(name, allOptionNames);
723
- let errorMsg = `Unknown option \`${optionFlag}\``;
724
- if (suggestions.length > 0) {
725
- errorMsg += `
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}
726
18
 
727
- Did you mean one of these?`;
728
- suggestions.forEach((suggestion) => {
729
- const suggestedFlag = suggestion.length > 1 ? `--${suggestion}` : `-${suggestion}`;
730
- errorMsg += `
731
- \u2022 ${suggestedFlag}`;
732
- });
733
- }
734
- errorMsg += `
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+=`
735
20
 
736
- Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`;
737
- throw new ClappError(errorMsg);
738
- }
739
- }
740
- }
741
- }
742
- checkOptionValue() {
743
- const { options: parsedOptions, globalCommand } = this.cli;
744
- const options = [...globalCommand.options, ...this.options];
745
- for (const option of options) {
746
- const value = parsedOptions[option.name.split(".")[0]];
747
- if (option.required) {
748
- const hasNegated = options.some((o) => o.negated && o.names.includes(option.name));
749
- if (value === true || value === false && !hasNegated) {
750
- throw new ClappError(`Option \`${option.rawName}\` requires a value.
21
+ Did you mean one of these?`,l.forEach((i)=>{let u=i.length>1?`--${i}`:`-${i}`;a+=`
22
+ \u2022 ${u}`});throw a+=`
751
23
 
752
- ` + `Example: ${this.cli.name} ${this.rawName} ${option.rawName} <value>`);
753
- }
754
- }
755
- }
756
- }
757
- }
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.
758
25
 
759
- class GlobalCommand extends Command {
760
- constructor(cli) {
761
- super("@@global@@", "", {}, cli);
762
- }
763
- }
764
- var Command_default = Command;
765
- var codes = {
766
- red: ["\x1B[31m", "\x1B[39m"],
767
- green: ["\x1B[32m", "\x1B[39m"],
768
- blue: ["\x1B[34m", "\x1B[39m"],
769
- yellow: ["\x1B[33m", "\x1B[39m"],
770
- cyan: ["\x1B[36m", "\x1B[39m"],
771
- magenta: ["\x1B[35m", "\x1B[39m"],
772
- white: ["\x1B[37m", "\x1B[39m"],
773
- gray: ["\x1B[90m", "\x1B[39m"],
774
- bgRed: ["\x1B[41m", "\x1B[49m"],
775
- bgGreen: ["\x1B[42m", "\x1B[49m"],
776
- bgBlue: ["\x1B[44m", "\x1B[49m"],
777
- bgYellow: ["\x1B[43m", "\x1B[49m"],
778
- bgCyan: ["\x1B[46m", "\x1B[49m"],
779
- bgMagenta: ["\x1B[45m", "\x1B[49m"],
780
- bold: ["\x1B[1m", "\x1B[22m"],
781
- italic: ["\x1B[3m", "\x1B[23m"],
782
- underline: ["\x1B[4m", "\x1B[24m"],
783
- dim: ["\x1B[2m", "\x1B[22m"],
784
- inverse: ["\x1B[7m", "\x1B[27m"],
785
- hidden: ["\x1B[8m", "\x1B[28m"],
786
- strikethrough: ["\x1B[9m", "\x1B[29m"]
787
- };
788
- var theme = {
789
- primary: "blue",
790
- secondary: "cyan",
791
- success: "green",
792
- warning: "yellow",
793
- error: "red",
794
- info: "magenta",
795
- muted: "gray"
796
- };
797
- function detectColorSupport() {
798
- return true;
799
- }
800
- function createStyler() {
801
- const styler = {};
802
- styler.supportsColor = detectColorSupport();
803
- function createStyleFunction(styleName, styles = []) {
804
- const styleList = styleName === "" ? [] : [...styles, styleName];
805
- const fn = function(text) {
806
- if (!styler.supportsColor)
807
- return text;
808
- let openCodes = "";
809
- let closeCodes = "";
810
- for (const style of styleList) {
811
- if (style in theme && theme[style] in codes) {
812
- const themeStyle = theme[style];
813
- openCodes += codes[themeStyle][0];
814
- closeCodes = codes[themeStyle][1] + closeCodes;
815
- } else if (style in codes) {
816
- openCodes += codes[style][0];
817
- closeCodes = codes[style][1] + closeCodes;
818
- }
819
- }
820
- return openCodes + text + closeCodes;
821
- };
822
- const allStyles2 = [...Object.keys(codes), ...Object.keys(theme)];
823
- for (const style of allStyles2) {
824
- if (!(style in fn)) {
825
- Object.defineProperty(fn, style, {
826
- get() {
827
- return createStyleFunction(style, styleList);
828
- }
829
- });
830
- }
831
- }
832
- return fn;
833
- }
834
- const allStyles = [...Object.keys(codes), ...Object.keys(theme)];
835
- for (const style of allStyles) {
836
- if (!(style in styler)) {
837
- Object.defineProperty(styler, style, {
838
- get() {
839
- return createStyleFunction(style);
840
- }
841
- });
842
- }
843
- }
844
- return styler;
845
- }
846
- var style = createStyler();
847
- class CLI extends EventEmitter {
848
- name;
849
- commands;
850
- globalCommand;
851
- matchedCommand;
852
- matchedCommandName;
853
- rawArgs;
854
- args;
855
- options;
856
- showHelpOnExit;
857
- showVersionOnExit;
858
- enableDidYouMean = true;
859
- signalHandlersSet = false;
860
- isVerbose = false;
861
- isQuiet = false;
862
- isDebug = false;
863
- isNoInteraction = false;
864
- environment;
865
- isDryRun = false;
866
- isForce = false;
867
- useEmoji = true;
868
- theme;
869
- isNoCache = false;
870
- constructor(name = "") {
871
- super();
872
- this.name = name;
873
- this.commands = [];
874
- this.rawArgs = [];
875
- this.args = [];
876
- this.options = {};
877
- this.globalCommand = new GlobalCommand(this);
878
- this.globalCommand.usage("<command> [options]");
879
- }
880
- handleSignals(cleanup) {
881
- if (this.signalHandlersSet) {
882
- return this;
883
- }
884
- const handleSignal = async (signal) => {
885
- console.log(`
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(`
886
27
 
887
- Received ${signal}, cleaning up...`);
888
- if (cleanup) {
889
- try {
890
- await cleanup();
891
- } catch (error) {
892
- console.error("Error during cleanup:", error);
893
- }
894
- }
895
- process5.exit(0);
896
- };
897
- process5.on("SIGINT", () => handleSignal("SIGINT"));
898
- process5.on("SIGTERM", () => handleSignal("SIGTERM"));
899
- this.signalHandlersSet = true;
900
- return this;
901
- }
902
- didYouMean(enabled = true) {
903
- this.enableDidYouMean = enabled;
904
- return this;
905
- }
906
- verbose() {
907
- this.globalCommand.option("-v, --verbose", "Enable verbose output");
908
- return this;
909
- }
910
- quiet() {
911
- this.globalCommand.option("-q, --quiet", "Suppress non-essential output");
912
- return this;
913
- }
914
- debug() {
915
- this.globalCommand.option("--debug", "Enable debug mode with detailed error information");
916
- return this;
917
- }
918
- noInteraction() {
919
- this.globalCommand.option("-n, --no-interaction", "Do not ask any interactive questions (for CI/CD)");
920
- return this;
921
- }
922
- env() {
923
- this.globalCommand.option("--env <environment>", "Target environment (e.g., production, staging, local)");
924
- return this;
925
- }
926
- dryRun() {
927
- this.globalCommand.option("--dry-run", "Preview actions without executing them");
928
- return this;
929
- }
930
- force() {
931
- this.globalCommand.option("-f, --force", "Skip confirmation prompts");
932
- return this;
933
- }
934
- emoji() {
935
- this.globalCommand.option("--no-emoji", "Disable emoji in output");
936
- return this;
937
- }
938
- themes() {
939
- this.globalCommand.option("--theme <theme>", "Color theme (default, dracula, nord, solarized, monokai)");
940
- return this;
941
- }
942
- cache() {
943
- this.globalCommand.option("--no-cache", "Disable caching");
944
- return this;
945
- }
946
- usage(text) {
947
- this.globalCommand.usage(text);
948
- return this;
949
- }
950
- command(rawName, description, config) {
951
- if (!config) {
952
- config = {};
953
- }
954
- const command = new Command_default(rawName, description || "", config, this);
955
- command.globalCommand = this.globalCommand;
956
- this.commands.push(command);
957
- return command;
958
- }
959
- option(rawName, description, config) {
960
- this.globalCommand.option(rawName, description, config);
961
- return this;
962
- }
963
- help(callback) {
964
- this.globalCommand.option("-h, --help", "Display this message");
965
- this.globalCommand.helpCallback = callback;
966
- this.showHelpOnExit = true;
967
- return this;
968
- }
969
- version(version, customFlags = "-v, --version") {
970
- this.globalCommand.version(version, customFlags);
971
- this.showVersionOnExit = true;
972
- return this;
973
- }
974
- example(example) {
975
- this.globalCommand.example(example);
976
- return this;
977
- }
978
- outputHelp() {
979
- if (this.matchedCommand) {
980
- this.matchedCommand.outputHelp();
981
- } else {
982
- this.globalCommand.outputHelp();
983
- }
984
- }
985
- outputVersion() {
986
- this.globalCommand.outputVersion();
987
- }
988
- setParsedInfo({ args, options }, matchedCommand, matchedCommandName) {
989
- this.args = args;
990
- this.options = options;
991
- if (matchedCommand) {
992
- this.matchedCommand = matchedCommand;
993
- }
994
- if (matchedCommandName) {
995
- this.matchedCommandName = matchedCommandName;
996
- }
997
- return this;
998
- }
999
- unsetMatchedCommand() {
1000
- this.matchedCommand = undefined;
1001
- this.matchedCommandName = undefined;
1002
- }
1003
- showCommandNotFound(input) {
1004
- console.log(style.red(`
1005
- \u2717 Command "${input}" not found.
1006
- `));
1007
- if (this.enableDidYouMean) {
1008
- const allCommandNames = [];
1009
- for (const command of this.commands) {
1010
- if (command.displayName) {
1011
- allCommandNames.push(command.displayName);
1012
- }
1013
- if (command.aliasNames) {
1014
- allCommandNames.push(...command.aliasNames);
1015
- }
1016
- }
1017
- const suggestions = findSimilarCommands(input, allCommandNames);
1018
- if (suggestions.length > 0) {
1019
- console.log(style.yellow("Did you mean one of these?"));
1020
- suggestions.forEach((cmd) => console.log(` ${style.dim("\u2022")} ${this.name} ${cmd}`));
1021
- console.log("");
1022
- }
1023
- }
1024
- console.log(style.dim("Run"), `${this.name} --help`, style.dim("to see all available commands"));
1025
- process5.exit(1);
1026
- }
1027
- async parse(argv = processArgs2, options = {}) {
1028
- let { run = true, exitOnError = false } = options;
1029
- if (exitOnError) {
1030
- try {
1031
- return await this.parse(argv, { run });
1032
- } catch (err) {
1033
- this.handleUsageError(err);
1034
- throw err;
1035
- }
1036
- }
1037
- this.rawArgs = argv;
1038
- if (!this.name) {
1039
- this.name = argv[1] ? getFileName(argv[1]) : "cli";
1040
- }
1041
- let shouldParse = true;
1042
- const slicedArgv = argv.slice(2);
1043
- const candidateName = slicedArgv[0];
1044
- if (candidateName && !candidateName.startsWith("-")) {
1045
- for (const command of this.commands) {
1046
- if (command.isMatched(candidateName)) {
1047
- const parsed = this.mri(slicedArgv, command);
1048
- shouldParse = false;
1049
- const parsedInfo = {
1050
- ...parsed,
1051
- args: parsed.args.slice(1)
1052
- };
1053
- this.setParsedInfo(parsedInfo, command, candidateName);
1054
- this.emit(`command:${candidateName}`, command);
1055
- break;
1056
- }
1057
- }
1058
- }
1059
- if (shouldParse) {
1060
- for (const command of this.commands) {
1061
- if (command.name === "") {
1062
- shouldParse = false;
1063
- const parsed = this.mri(slicedArgv, command);
1064
- this.setParsedInfo(parsed, command);
1065
- this.emit(`command:!`, command);
1066
- break;
1067
- }
1068
- }
1069
- }
1070
- if (shouldParse) {
1071
- const parsed = this.mri(argv.slice(2));
1072
- this.setParsedInfo(parsed);
1073
- }
1074
- if (this.options.verbose) {
1075
- this.isVerbose = true;
1076
- }
1077
- if (this.options.quiet) {
1078
- this.isQuiet = true;
1079
- }
1080
- if (this.options.debug) {
1081
- this.isDebug = true;
1082
- }
1083
- if (this.options.noInteraction) {
1084
- this.isNoInteraction = true;
1085
- }
1086
- if (this.options.env) {
1087
- this.environment = String(this.options.env);
1088
- }
1089
- if (this.options.dryRun) {
1090
- this.isDryRun = true;
1091
- }
1092
- if (this.options.force) {
1093
- this.isForce = true;
1094
- }
1095
- if (this.options.noEmoji !== undefined) {
1096
- this.useEmoji = !this.options.noEmoji;
1097
- }
1098
- if (this.options.theme) {
1099
- this.theme = String(this.options.theme);
1100
- }
1101
- if (this.options.noCache !== undefined) {
1102
- this.isNoCache = Boolean(this.options.noCache);
1103
- }
1104
- if (this.options.help && this.showHelpOnExit) {
1105
- this.outputHelp();
1106
- run = false;
1107
- this.unsetMatchedCommand();
1108
- }
1109
- if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) {
1110
- this.outputVersion();
1111
- run = false;
1112
- this.unsetMatchedCommand();
1113
- }
1114
- const parsedArgv = { args: this.args, options: this.options };
1115
- if (run) {
1116
- await this.runMatchedCommand();
1117
- }
1118
- if (!this.matchedCommand && this.args[0]) {
1119
- this.emit("command:*");
1120
- const hasWildcardListener = this.listenerCount("command:*") > 0;
1121
- if (!hasWildcardListener) {
1122
- this.showCommandNotFound(this.args[0]);
1123
- }
1124
- }
1125
- return parsedArgv;
1126
- }
1127
- mri(argv, command) {
1128
- const cliOptions = [
1129
- ...this.globalCommand.options,
1130
- ...command ? command.options : []
1131
- ];
1132
- const mriOptions = getMriOptions(cliOptions);
1133
- let argsAfterDoubleDashes = [];
1134
- const doubleDashesIndex = argv.indexOf("--");
1135
- if (doubleDashesIndex > -1) {
1136
- argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
1137
- argv = argv.slice(0, doubleDashesIndex);
1138
- }
1139
- const raw = parseArgv(argv, mriOptions);
1140
- const parsed = { _: raw._ };
1141
- for (const name of Object.keys(raw)) {
1142
- if (name !== "_") {
1143
- parsed[camelcaseOptionName(name)] = raw[name];
1144
- }
1145
- }
1146
- const args = parsed._;
1147
- const options = {
1148
- "--": argsAfterDoubleDashes
1149
- };
1150
- const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
1151
- const transforms = Object.create(null);
1152
- for (const cliOption of cliOptions) {
1153
- if (!ignoreDefault && cliOption.config.default !== undefined) {
1154
- for (const name of cliOption.names) {
1155
- options[name] = cliOption.config.default;
1156
- }
1157
- }
1158
- if (Array.isArray(cliOption.config.type)) {
1159
- if (transforms[cliOption.name] === undefined) {
1160
- transforms[cliOption.name] = {
1161
- shouldTransform: true,
1162
- transformFunction: cliOption.config.type[0]
1163
- };
1164
- }
1165
- }
1166
- }
1167
- for (const key of Object.keys(parsed)) {
1168
- if (key !== "_") {
1169
- const keys = key.split(".");
1170
- setDotProp(options, keys, parsed[key]);
1171
- setByType(options, transforms);
1172
- }
1173
- }
1174
- return {
1175
- args,
1176
- options
1177
- };
1178
- }
1179
- async run(argv = processArgs2) {
1180
- return this.parse(argv, { run: true, exitOnError: true });
1181
- }
1182
- handleUsageError(err) {
1183
- const isClappError = !!err && typeof err === "object" && err.name === "ClappError";
1184
- const isUsage = isClappError && err.isUsageError !== false;
1185
- if (!isUsage)
1186
- return;
1187
- const e = err;
1188
- const raw = e.message ?? "command-line error";
1189
- const label = this.name ? `${this.name}: ` : "";
1190
- const suffix = /--help/.test(raw) ? "" : `
1191
- Run \`${this.name ?? "cli"} --help\` for usage.`;
1192
- process5.stderr.write(`${label}${raw}${suffix}
1193
- `);
1194
- process5.exit(e.exitCode ?? 2);
1195
- }
1196
- async runMatchedCommand() {
1197
- const { args, options, matchedCommand: command } = this;
1198
- if (!command || !command.commandAction)
1199
- return;
1200
- command.checkUnknownOptions();
1201
- command.checkOptionValue();
1202
- command.checkRequiredArgs();
1203
- const actionArgs = [];
1204
- command.args.forEach((arg, index) => {
1205
- if (arg.variadic) {
1206
- actionArgs.push(args.slice(index));
1207
- } else {
1208
- actionArgs.push(args[index]);
1209
- }
1210
- });
1211
- actionArgs.push(options);
1212
- const context = {
1213
- command,
1214
- args: actionArgs,
1215
- options
1216
- };
1217
- for (const hook of command.beforeHooks) {
1218
- await hook(context);
1219
- }
1220
- let actionResult;
1221
- const executeAction = async () => {
1222
- const result = command.commandAction.apply(this, actionArgs);
1223
- if (result instanceof Promise) {
1224
- actionResult = await result;
1225
- } else {
1226
- actionResult = result;
1227
- }
1228
- return actionResult;
1229
- };
1230
- if (command.middleware.length > 0) {
1231
- let index = 0;
1232
- const next = async () => {
1233
- if (index < command.middleware.length) {
1234
- const middleware2 = command.middleware[index++];
1235
- await middleware2({ ...context, next });
1236
- } else {
1237
- await executeAction();
1238
- }
1239
- };
1240
- await next();
1241
- } else {
1242
- await executeAction();
1243
- }
1244
- for (const hook of command.afterHooks) {
1245
- await hook(context);
1246
- }
1247
- return actionResult;
1248
- }
1249
- removeSignalHandlers() {
1250
- if (!this.signalHandlersSet) {
1251
- return this;
1252
- }
1253
- process5.removeAllListeners("SIGINT");
1254
- process5.removeAllListeners("SIGTERM");
1255
- this.signalHandlersSet = false;
1256
- return this;
1257
- }
1258
- destroy() {
1259
- this.removeSignalHandlers();
1260
- this.commands = [];
1261
- this.rawArgs = [];
1262
- this.args = [];
1263
- this.options = {};
1264
- this.matchedCommand = undefined;
1265
- this.matchedCommandName = undefined;
1266
- this.removeAllListeners();
1267
- }
1268
- }
1269
- class CLICache {
1270
- cache;
1271
- enabled;
1272
- cleanupInterval = null;
1273
- hits = 0;
1274
- misses = 0;
1275
- constructor() {
1276
- this.cache = new Map;
1277
- this.enabled = true;
1278
- this.startCleanupInterval();
1279
- }
1280
- startCleanupInterval() {
1281
- if (this.cleanupInterval) {
1282
- return;
1283
- }
1284
- this.cleanupInterval = setInterval(() => {
1285
- this.cleanup();
1286
- }, 30000);
1287
- this.cleanupInterval.unref();
1288
- }
1289
- stopCleanup() {
1290
- if (this.cleanupInterval) {
1291
- clearInterval(this.cleanupInterval);
1292
- this.cleanupInterval = null;
1293
- }
1294
- }
1295
- isEnabled() {
1296
- return this.enabled;
1297
- }
1298
- get(key) {
1299
- if (!this.enabled) {
1300
- this.misses++;
1301
- return;
1302
- }
1303
- const entry = this.cache.get(key);
1304
- if (!entry) {
1305
- this.misses++;
1306
- return;
1307
- }
1308
- const now = Date.now();
1309
- if (now - entry.timestamp > entry.ttl) {
1310
- this.cache.delete(key);
1311
- this.misses++;
1312
- return;
1313
- }
1314
- this.hits++;
1315
- return entry.value;
1316
- }
1317
- set(key, value, ttl = 5000) {
1318
- if (!this.enabled) {
1319
- return;
1320
- }
1321
- this.cache.set(key, {
1322
- value,
1323
- timestamp: Date.now(),
1324
- ttl
1325
- });
1326
- }
1327
- has(key) {
1328
- if (!this.enabled) {
1329
- return false;
1330
- }
1331
- const entry = this.cache.get(key);
1332
- if (!entry) {
1333
- return false;
1334
- }
1335
- const now = Date.now();
1336
- if (now - entry.timestamp > entry.ttl) {
1337
- this.cache.delete(key);
1338
- return false;
1339
- }
1340
- return true;
1341
- }
1342
- delete(key) {
1343
- this.cache.delete(key);
1344
- }
1345
- clear() {
1346
- this.cache.clear();
1347
- }
1348
- disable() {
1349
- this.enabled = false;
1350
- this.clear();
1351
- }
1352
- enable() {
1353
- this.enabled = true;
1354
- }
1355
- stats() {
1356
- return {
1357
- size: this.cache.size,
1358
- enabled: this.enabled,
1359
- hits: this.hits,
1360
- misses: this.misses
1361
- };
1362
- }
1363
- resetStats() {
1364
- this.hits = 0;
1365
- this.misses = 0;
1366
- }
1367
- keys() {
1368
- return Array.from(this.cache.keys());
1369
- }
1370
- cleanup() {
1371
- const now = Date.now();
1372
- for (const [key, entry] of this.cache.entries()) {
1373
- if (now - entry.timestamp > entry.ttl) {
1374
- this.cache.delete(key);
1375
- }
1376
- }
1377
- }
1378
- destroy() {
1379
- this.stopCleanup();
1380
- this.clear();
1381
- this.resetStats();
1382
- }
1383
- }
1384
- var cliCache = new CLICache;
1385
- function detectColorSupport2() {
1386
- if ("FORCE_COLOR" in process7.env) {
1387
- return process7.env.FORCE_COLOR !== "0";
1388
- }
1389
- if ("NO_COLOR" in process7.env || process7.env.TERM === "dumb") {
1390
- return false;
1391
- }
1392
- if (process7.platform === "win32") {
1393
- return true;
1394
- }
1395
- return tty.isatty(1) && tty.isatty(2);
1396
- }
1397
- var enabled = detectColorSupport2();
1398
- function wrap(open, close) {
1399
- if (!enabled)
1400
- return (text) => text;
1401
- return (text) => open + text + close;
1402
- }
1403
- var reset = wrap("\x1B[0m", "\x1B[0m");
1404
- var red = wrap("\x1B[31m", "\x1B[39m");
1405
- var green = wrap("\x1B[32m", "\x1B[39m");
1406
- var yellow = wrap("\x1B[33m", "\x1B[39m");
1407
- var blue = wrap("\x1B[34m", "\x1B[39m");
1408
- var magenta = wrap("\x1B[35m", "\x1B[39m");
1409
- var cyan = wrap("\x1B[36m", "\x1B[39m");
1410
- var white = wrap("\x1B[37m", "\x1B[39m");
1411
- var gray = wrap("\x1B[90m", "\x1B[39m");
1412
- var bold = wrap("\x1B[1m", "\x1B[22m");
1413
- var italic = wrap("\x1B[3m", "\x1B[23m");
1414
- var underline = wrap("\x1B[4m", "\x1B[24m");
1415
- var dim = wrap("\x1B[2m", "\x1B[22m");
1416
- var inverse = wrap("\x1B[7m", "\x1B[27m");
1417
- var hidden = wrap("\x1B[8m", "\x1B[28m");
1418
- var strikethrough = wrap("\x1B[9m", "\x1B[29m");
1419
- var bgRed = wrap("\x1B[41m", "\x1B[49m");
1420
- var bgGreen = wrap("\x1B[42m", "\x1B[49m");
1421
- var bgYellow = wrap("\x1B[43m", "\x1B[49m");
1422
- var bgBlue = wrap("\x1B[44m", "\x1B[49m");
1423
- var bgMagenta = wrap("\x1B[45m", "\x1B[49m");
1424
- var bgCyan = wrap("\x1B[46m", "\x1B[49m");
1425
- var bgWhite = wrap("\x1B[47m", "\x1B[49m");
1426
- var isColorSupported = enabled;
1427
- var colors = {
1428
- reset,
1429
- red,
1430
- green,
1431
- yellow,
1432
- blue,
1433
- magenta,
1434
- cyan,
1435
- white,
1436
- gray,
1437
- bold,
1438
- italic,
1439
- underline,
1440
- dim,
1441
- inverse,
1442
- hidden,
1443
- strikethrough,
1444
- bgRed,
1445
- bgGreen,
1446
- bgYellow,
1447
- bgBlue,
1448
- bgMagenta,
1449
- bgCyan,
1450
- bgWhite,
1451
- isColorSupported
1452
- };
1453
- var colors_default = colors;
1454
- var actions = ["up", "down", "left", "right", "space", "enter", "cancel"];
1455
- var settings = {
1456
- actions: new Set(actions),
1457
- aliases: new Map([
1458
- ["k", "up"],
1459
- ["j", "down"],
1460
- ["h", "left"],
1461
- ["l", "right"],
1462
- ["\x03", "cancel"],
1463
- ["escape", "cancel"]
1464
- ]),
1465
- messages: {
1466
- cancel: "Canceled",
1467
- error: "Something went wrong"
1468
- }
1469
- };
1470
- function isActionKey(key, action) {
1471
- if (typeof key === "string") {
1472
- return settings.aliases.get(key) === action;
1473
- }
1474
- for (const value of key) {
1475
- if (value === undefined)
1476
- continue;
1477
- if (isActionKey(value, action)) {
1478
- return true;
1479
- }
1480
- }
1481
- return false;
1482
- }
1483
- function diffLines(a, b) {
1484
- if (a === b)
1485
- return [];
1486
- const aLines = a.split(`
1487
- `);
1488
- const bLines = b.split(`
1489
- `);
1490
- const diff = [];
1491
- for (let i = 0;i < Math.max(aLines.length, bLines.length); i++) {
1492
- if (aLines[i] !== bLines[i])
1493
- diff.push(i);
1494
- }
1495
- return diff;
1496
- }
1497
- var isWindows = process8.platform.startsWith("win");
1498
- var CANCEL_SYMBOL = Symbol("clapp:cancel");
1499
- function setRawMode(input, value) {
1500
- const i = input;
1501
- if (i.isTTY)
1502
- i.setRawMode(value);
1503
- }
1504
- function stripAnsi(str) {
1505
- return str.replace(/\x1b\[[0-9;]*m/g, "");
1506
- }
1507
- function stringWidth(str) {
1508
- return stripAnsi(str).length;
1509
- }
1510
- function wrapAnsi(text, columns, options) {
1511
- if (!columns || columns < 1)
1512
- return text;
1513
- const hard = options?.hard ?? false;
1514
- const trim = options?.trim ?? true;
1515
- const lines = text.split(`
1516
- `);
1517
- const result = [];
1518
- for (const line of lines) {
1519
- if (stringWidth(line) <= columns) {
1520
- result.push(trim ? line.trimEnd() : line);
1521
- continue;
1522
- }
1523
- if (hard) {
1524
- let current = "";
1525
- let currentWidth = 0;
1526
- let i = 0;
1527
- while (i < line.length) {
1528
- const ansiMatch = line.slice(i).match(/^\x1b\[[0-9;]*m/);
1529
- if (ansiMatch) {
1530
- current += ansiMatch[0];
1531
- i += ansiMatch[0].length;
1532
- continue;
1533
- }
1534
- if (currentWidth >= columns) {
1535
- result.push(trim ? current.trimEnd() : current);
1536
- current = "";
1537
- currentWidth = 0;
1538
- }
1539
- current += line[i];
1540
- currentWidth++;
1541
- i++;
1542
- }
1543
- if (current) {
1544
- result.push(trim ? current.trimEnd() : current);
1545
- }
1546
- } else {
1547
- result.push(trim ? line.trimEnd() : line);
1548
- }
1549
- }
1550
- return result.join(`
1551
- `);
1552
- }
1553
-
1554
- class Prompt {
1555
- input;
1556
- output;
1557
- _abortSignal;
1558
- rl;
1559
- opts;
1560
- _render;
1561
- _track = false;
1562
- _prevFrame = "";
1563
- _subscribers = new Map;
1564
- _cursor = 0;
1565
- _manualLine = "";
1566
- state = "initial";
1567
- error = "";
1568
- value;
1569
- userInput = "";
1570
- constructor(options, trackValue = true) {
1571
- const { input = stdin2, output = stdout2, render, signal, ...opts } = options;
1572
- this.opts = opts;
1573
- this.onKeypress = this.onKeypress.bind(this);
1574
- this.close = this.close.bind(this);
1575
- this.render = this.render.bind(this);
1576
- this._render = render.bind(this);
1577
- this._track = trackValue;
1578
- this._abortSignal = signal;
1579
- this.input = input;
1580
- this.output = output;
1581
- }
1582
- unsubscribe() {
1583
- this._subscribers.clear();
1584
- }
1585
- setSubscriber(event, opts) {
1586
- const params = this._subscribers.get(event) ?? [];
1587
- params.push(opts);
1588
- this._subscribers.set(event, params);
1589
- }
1590
- on(event, cb) {
1591
- this.setSubscriber(event, { cb });
1592
- return this;
1593
- }
1594
- once(event, cb) {
1595
- this.setSubscriber(event, { cb, once: true });
1596
- return this;
1597
- }
1598
- emit(event, ...data) {
1599
- const cbs = this._subscribers.get(event) ?? [];
1600
- const cleanup = [];
1601
- for (const subscriber of cbs) {
1602
- subscriber.cb(...data);
1603
- if (subscriber.once) {
1604
- cleanup.push(() => cbs.splice(cbs.indexOf(subscriber), 1));
1605
- }
1606
- }
1607
- for (const cb of cleanup) {
1608
- cb();
1609
- }
1610
- return this;
1611
- }
1612
- prompt() {
1613
- return new Promise((resolve) => {
1614
- if (this._abortSignal) {
1615
- if (this._abortSignal.aborted) {
1616
- this.state = "cancel";
1617
- this.close();
1618
- return resolve(CANCEL_SYMBOL);
1619
- }
1620
- this._abortSignal.addEventListener("abort", () => {
1621
- this.state = "cancel";
1622
- this.close();
1623
- }, { once: true });
1624
- }
1625
- this.rl = readline2.createInterface({
1626
- input: this.input,
1627
- tabSize: 2,
1628
- prompt: "",
1629
- escapeCodeTimeout: 50,
1630
- terminal: true
1631
- });
1632
- this.rl.prompt();
1633
- if (this.opts.initialUserInput !== undefined) {
1634
- this._setUserInput(this.opts.initialUserInput, true);
1635
- }
1636
- this.input.on("keypress", this.onKeypress);
1637
- setRawMode(this.input, true);
1638
- this.output.on("resize", this.render);
1639
- this.render();
1640
- this.once("submit", () => {
1641
- this.output.write(cursor.show);
1642
- this.output.off("resize", this.render);
1643
- setRawMode(this.input, false);
1644
- resolve(this.value);
1645
- });
1646
- this.once("cancel", () => {
1647
- this.output.write(cursor.show);
1648
- this.output.off("resize", this.render);
1649
- setRawMode(this.input, false);
1650
- resolve(CANCEL_SYMBOL);
1651
- });
1652
- });
1653
- }
1654
- _isActionKey(char, _key) {
1655
- return char === "\t";
1656
- }
1657
- _setValue(value) {
1658
- this.value = value;
1659
- this.emit("value", this.value);
1660
- }
1661
- _setUserInput(value, write) {
1662
- this.userInput = value ?? "";
1663
- this.emit("userInput", this.userInput);
1664
- if (write && this._track && this.rl) {
1665
- this.rl.write(this.userInput);
1666
- this._cursor = this.rl.cursor;
1667
- }
1668
- }
1669
- onKeypress(char, key) {
1670
- if (this._track && key.name !== "return") {
1671
- if (key.name && this._isActionKey(char, key)) {
1672
- this.rl?.write(null, { ctrl: true, name: "h" });
1673
- }
1674
- this._cursor = this.rl?.cursor ?? 0;
1675
- const isSpecialKey = key.name === "tab" || key.name === "escape" || key.name === "backspace" || key.name === "delete" || key.name === "enter" || key.name === "return" || key.name && ["up", "down", "left", "right"].includes(key.name);
1676
- if (char && !isSpecialKey && char.length === 1 && char >= " ") {
1677
- this._manualLine += char;
1678
- } else if (key.name === "backspace" && this._manualLine.length > 0) {
1679
- this._manualLine = this._manualLine.slice(0, -1);
1680
- }
1681
- const effectiveLine = this._manualLine.length >= (this.rl?.line?.length || 0) ? this._manualLine : this.rl?.line;
1682
- this._setUserInput(effectiveLine);
1683
- }
1684
- if (this.state === "error") {
1685
- this.state = "active";
1686
- this.error = "";
1687
- }
1688
- if (key?.name) {
1689
- if (!this._track && settings.aliases.has(key.name)) {
1690
- this.emit("cursor", settings.aliases.get(key.name));
1691
- }
1692
- if (settings.actions.has(key.name)) {
1693
- this.emit("cursor", key.name);
1694
- }
1695
- }
1696
- if (char && (char.toLowerCase() === "y" || char.toLowerCase() === "n")) {
1697
- this.emit("confirm", char.toLowerCase() === "y");
1698
- }
1699
- this.emit("key", char?.toLowerCase(), key);
1700
- if (key?.name === "return") {
1701
- if (this.opts.validate) {
1702
- const problem = this.opts.validate(this.value);
1703
- if (problem) {
1704
- this.error = problem instanceof Error ? problem.message : problem;
1705
- this.state = "error";
1706
- }
1707
- }
1708
- if (this.state !== "error") {
1709
- this.state = "submit";
1710
- }
1711
- }
1712
- if (isActionKey([char, key?.name, key?.sequence], "cancel")) {
1713
- this.state = "cancel";
1714
- }
1715
- if (this.state === "submit" || this.state === "cancel") {
1716
- this.emit("finalize");
1717
- }
1718
- this.render();
1719
- if (this.state === "submit" || this.state === "cancel") {
1720
- this.close();
1721
- }
1722
- }
1723
- close() {
1724
- this.input.unpipe();
1725
- this.input.removeListener("keypress", this.onKeypress);
1726
- this.output.write(`
1727
- `);
1728
- setRawMode(this.input, false);
1729
- this.rl?.close();
1730
- this.rl = undefined;
1731
- this.emit(`${this.state}`, this.value);
1732
- if (this.state === "cancel") {
1733
- setTimeout(() => {
1734
- this.unsubscribe();
1735
- }, 10);
1736
- } else {
1737
- this.unsubscribe();
1738
- }
1739
- }
1740
- restoreCursor() {
1741
- const lines = wrapAnsi(this._prevFrame, process9.stdout.columns, { hard: true, trim: false }).split(`
1742
- `).length - 1;
1743
- this.output.write(cursor.move(-999, lines * -1));
1744
- }
1745
- render() {
1746
- const frame = wrapAnsi(this._render(this) ?? "", process9.stdout.columns, {
1747
- hard: true,
1748
- trim: false
1749
- });
1750
- if (frame === this._prevFrame) {
1751
- return;
1752
- }
1753
- if (this.state === "initial") {
1754
- this.output.write(cursor.hide);
1755
- } else {
1756
- const diff = diffLines(this._prevFrame, frame);
1757
- this.restoreCursor();
1758
- if (diff && diff?.length === 1) {
1759
- const diffLine = diff[0];
1760
- this.output.write(cursor.move(0, diffLine));
1761
- this.output.write(erase.lines(1));
1762
- const lines = frame.split(`
1763
- `);
1764
- this.output.write(lines[diffLine]);
1765
- this._prevFrame = frame;
1766
- this.output.write(cursor.move(0, lines.length - diffLine - 1));
1767
- return;
1768
- }
1769
- if (diff && diff?.length > 1) {
1770
- const diffLine = diff[0];
1771
- this.output.write(cursor.move(0, diffLine));
1772
- this.output.write(erase.down());
1773
- const lines = frame.split(`
1774
- `);
1775
- const newLines = lines.slice(diffLine);
1776
- this.output.write(newLines.join(`
1777
- `));
1778
- this._prevFrame = frame;
1779
- return;
1780
- }
1781
- this.output.write(erase.down());
1782
- }
1783
- this.output.write(frame);
1784
- if (this.state === "initial") {
1785
- this.state = "active";
1786
- }
1787
- this._prevFrame = frame;
1788
- }
1789
- }
1790
- function getCursorForValue(selected, items) {
1791
- if (selected === undefined) {
1792
- return 0;
1793
- }
1794
- const currLength = items.length;
1795
- if (currLength === 0) {
1796
- return 0;
1797
- }
1798
- const index = items.findIndex((item) => item.value === selected);
1799
- return index !== -1 ? index : 0;
1800
- }
1801
- function defaultFilter(input, option) {
1802
- const label = option.label ?? String(option.value);
1803
- return label.toLowerCase().includes(input.toLowerCase());
1804
- }
1805
- function normalisedValue(multiple, values) {
1806
- if (!values) {
1807
- return;
1808
- }
1809
- if (multiple) {
1810
- return values;
1811
- }
1812
- return values[0];
1813
- }
1814
-
1815
- class AutocompletePrompt extends Prompt {
1816
- filteredOptions;
1817
- multiple;
1818
- isNavigating = false;
1819
- selectedValues = [];
1820
- focusedValue;
1821
- #cursor = 0;
1822
- #lastUserInput = "";
1823
- #filterFn;
1824
- #options;
1825
- get cursor() {
1826
- return this.#cursor;
1827
- }
1828
- get userInputWithCursor() {
1829
- if (!this.userInput) {
1830
- return colors_default.inverse(colors_default.hidden("_"));
1831
- }
1832
- if (this._cursor >= this.userInput.length) {
1833
- return `${this.userInput}\u2588`;
1834
- }
1835
- const s1 = this.userInput.slice(0, this._cursor);
1836
- const [s2, ...s3] = this.userInput.slice(this._cursor);
1837
- return `${s1}${colors_default.inverse(s2)}${s3.join("")}`;
1838
- }
1839
- get options() {
1840
- if (typeof this.#options === "function") {
1841
- return this.#options();
1842
- }
1843
- return this.#options;
1844
- }
1845
- constructor(opts) {
1846
- super(opts);
1847
- this.#options = opts.options;
1848
- const options = this.options;
1849
- this.filteredOptions = [...options];
1850
- this.multiple = opts.multiple === true;
1851
- this.#filterFn = opts.filter ?? defaultFilter;
1852
- let initialValues;
1853
- if (opts.initialValue && Array.isArray(opts.initialValue)) {
1854
- if (this.multiple) {
1855
- initialValues = opts.initialValue;
1856
- } else {
1857
- initialValues = opts.initialValue.slice(0, 1);
1858
- }
1859
- } else {
1860
- if (!this.multiple && this.options.length > 0) {
1861
- initialValues = [this.options[0].value];
1862
- }
1863
- }
1864
- if (initialValues) {
1865
- for (const selectedValue of initialValues) {
1866
- const selectedIndex = options.findIndex((opt) => opt.value === selectedValue);
1867
- if (selectedIndex !== -1) {
1868
- this.toggleSelected(selectedValue);
1869
- this.#cursor = selectedIndex;
1870
- }
1871
- }
1872
- }
1873
- this.focusedValue = this.options[this.#cursor]?.value;
1874
- this.on("key", (char, key) => this.#onKey(char, key));
1875
- this.on("userInput", (value) => this.#onUserInputChanged(value));
1876
- }
1877
- _isActionKey(char, key) {
1878
- return char === "\t" || this.multiple && this.isNavigating && key.name === "space" && char !== undefined && char !== "";
1879
- }
1880
- #onKey(_char, key) {
1881
- const isUpKey = key.name === "up";
1882
- const isDownKey = key.name === "down";
1883
- const isReturnKey = key.name === "return";
1884
- if (isUpKey || isDownKey) {
1885
- this.#cursor = Math.max(0, Math.min(this.#cursor + (isUpKey ? -1 : 1), this.filteredOptions.length - 1));
1886
- this.focusedValue = this.filteredOptions[this.#cursor]?.value;
1887
- if (!this.multiple) {
1888
- this.selectedValues = [this.focusedValue];
1889
- }
1890
- this.isNavigating = true;
1891
- } else if (isReturnKey) {
1892
- this.value = normalisedValue(this.multiple, this.selectedValues);
1893
- } else {
1894
- if (this.multiple) {
1895
- if (this.focusedValue !== undefined && (key.name === "tab" || this.isNavigating && key.name === "space")) {
1896
- this.toggleSelected(this.focusedValue);
1897
- } else {
1898
- this.isNavigating = false;
1899
- }
1900
- } else {
1901
- if (this.focusedValue) {
1902
- this.selectedValues = [this.focusedValue];
1903
- }
1904
- this.isNavigating = false;
1905
- }
1906
- }
1907
- }
1908
- deselectAll() {
1909
- this.selectedValues = [];
1910
- }
1911
- toggleSelected(value) {
1912
- if (this.filteredOptions.length === 0) {
1913
- return;
1914
- }
1915
- if (this.multiple) {
1916
- if (this.selectedValues.includes(value)) {
1917
- this.selectedValues = this.selectedValues.filter((v) => v !== value);
1918
- } else {
1919
- this.selectedValues = [...this.selectedValues, value];
1920
- }
1921
- } else {
1922
- this.selectedValues = [value];
1923
- }
1924
- }
1925
- #onUserInputChanged(value) {
1926
- if (value !== this.#lastUserInput) {
1927
- this.#lastUserInput = value;
1928
- const options = this.options;
1929
- if (value) {
1930
- this.filteredOptions = options.filter((opt) => this.#filterFn(value, opt));
1931
- } else {
1932
- this.filteredOptions = [...options];
1933
- }
1934
- this.#cursor = getCursorForValue(this.focusedValue, this.filteredOptions);
1935
- this.focusedValue = this.filteredOptions[this.#cursor]?.value;
1936
- if (!this.multiple) {
1937
- if (this.focusedValue !== undefined) {
1938
- this.toggleSelected(this.focusedValue);
1939
- } else {
1940
- this.deselectAll();
1941
- }
1942
- }
1943
- }
1944
- }
1945
- }
1946
- class GroupMultiSelectPrompt extends Prompt {
1947
- options;
1948
- cursor = 0;
1949
- #selectableGroups;
1950
- getGroupItems(group) {
1951
- return this.options.filter((o) => o.group === group);
1952
- }
1953
- isGroupSelected(group) {
1954
- const items = this.getGroupItems(group);
1955
- const value = this.value;
1956
- if (value === undefined) {
1957
- return false;
1958
- }
1959
- return items.every((i) => value.includes(i.value));
1960
- }
1961
- toggleValue() {
1962
- const item = this.options[this.cursor];
1963
- if (this.value === undefined) {
1964
- this.value = [];
1965
- }
1966
- if (item.group === true) {
1967
- const group = String(item.value);
1968
- const groupedItems = this.getGroupItems(group);
1969
- if (this.isGroupSelected(group)) {
1970
- this.value = this.value.filter((v) => groupedItems.findIndex((i) => i.value === v) === -1);
1971
- } else {
1972
- this.value = [...this.value, ...groupedItems.map((i) => i.value)];
1973
- }
1974
- this.value = Array.from(new Set(this.value));
1975
- } else {
1976
- const selected = this.value.includes(item.value);
1977
- this.value = selected ? this.value.filter((v) => v !== item.value) : [...this.value, item.value];
1978
- }
1979
- }
1980
- constructor(opts) {
1981
- super(opts, false);
1982
- const { options } = opts;
1983
- this.#selectableGroups = opts.selectableGroups !== false;
1984
- this.options = Object.entries(options).flatMap(([key, option]) => [
1985
- { value: key, group: true, label: key },
1986
- ...option.map((opt) => ({ ...opt, group: key }))
1987
- ]);
1988
- this.value = [...opts.initialValues ?? []];
1989
- this.cursor = Math.max(this.options.findIndex(({ value }) => value === opts.cursorAt), this.#selectableGroups ? 0 : 1);
1990
- this.on("cursor", (key) => {
1991
- switch (key) {
1992
- case "left":
1993
- case "up": {
1994
- this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;
1995
- const currentIsGroup = this.options[this.cursor]?.group === true;
1996
- if (!this.#selectableGroups && currentIsGroup) {
1997
- this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;
1998
- }
1999
- break;
2000
- }
2001
- case "down":
2002
- case "right": {
2003
- this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;
2004
- const currentIsGroup = this.options[this.cursor]?.group === true;
2005
- if (!this.#selectableGroups && currentIsGroup) {
2006
- this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;
2007
- }
2008
- break;
2009
- }
2010
- case "space":
2011
- this.toggleValue();
2012
- break;
2013
- }
2014
- });
2015
- }
2016
- }
2017
- var unicode = isUnicodeSupported();
2018
- var unicodeOr = (c, fallback) => unicode ? c : fallback;
2019
- var S_STEP_ACTIVE = unicodeOr("\u25C6", "*");
2020
- var S_STEP_CANCEL = unicodeOr("\u25A0", "x");
2021
- var S_STEP_ERROR = unicodeOr("\u25B2", "x");
2022
- var S_STEP_SUBMIT = unicodeOr("\u25C7", "o");
2023
- var S_BAR_START = unicodeOr("\u250C", "T");
2024
- var S_BAR = unicodeOr("\u2502", "|");
2025
- var S_BAR_END = unicodeOr("\u2514", "\u2014");
2026
- var S_RADIO_ACTIVE = unicodeOr("\u25CF", ">");
2027
- var S_RADIO_INACTIVE = unicodeOr("\u25CB", " ");
2028
- var S_CHECKBOX_ACTIVE = unicodeOr("\u25FB", "[\u2022]");
2029
- var S_CHECKBOX_SELECTED = unicodeOr("\u25FC", "[+]");
2030
- var S_CHECKBOX_INACTIVE = unicodeOr("\u25FB", "[ ]");
2031
- var S_PASSWORD_MASK = unicodeOr("\u25AA", "\u2022");
2032
- var S_BAR_H = unicodeOr("\u2500", "-");
2033
- var S_CORNER_TOP_RIGHT = unicodeOr("\u256E", "+");
2034
- var S_CONNECT_LEFT = unicodeOr("\u251C", "+");
2035
- var S_CORNER_BOTTOM_RIGHT = unicodeOr("\u256F", "+");
2036
- var S_INFO = unicodeOr("\u25CF", "\u2022");
2037
- var S_SUCCESS = unicodeOr("\u25C6", "*");
2038
- var S_WARN = unicodeOr("\u25B2", "!");
2039
- var S_ERROR = unicodeOr("\u25A0", "x");
2040
- var S_PROGRESS_CHAR = {
2041
- light: unicodeOr("\u2500", "-"),
2042
- heavy: unicodeOr("\u2501", "="),
2043
- block: unicodeOr("\u2588", "#")
2044
- };
2045
- function getPrefix() {
2046
- return `${colors_default.gray(S_BAR)} `;
2047
- }
2048
- var prefix = getPrefix();
2049
- // package.json
2050
- var version = "0.0.27";
2051
-
2052
- // src/cli/middleware.ts
2053
- import fs2 from "fs/promises";
2054
- import path2 from "path";
2055
- import process6 from "process";
2056
-
2057
- // src/cli/colors.ts
2058
- var colors2 = {
2059
- reset: "\x1B[0m",
2060
- bold: "\x1B[1m",
2061
- dim: "\x1B[2m",
2062
- red: "\x1B[31m",
2063
- green: "\x1B[32m",
2064
- yellow: "\x1B[33m",
2065
- blue: "\x1B[34m",
2066
- cyan: "\x1B[36m",
2067
- white: "\x1B[37m",
2068
- gray: "\x1B[90m"
2069
- };
2070
- var chalk = {
2071
- red: (text) => `${colors2.red}${text}${colors2.reset}`,
2072
- green: (text) => `${colors2.green}${text}${colors2.reset}`,
2073
- yellow: (text) => `${colors2.yellow}${text}${colors2.reset}`,
2074
- blue: (text) => `${colors2.blue}${text}${colors2.reset}`,
2075
- cyan: (text) => `${colors2.cyan}${text}${colors2.reset}`,
2076
- white: (text) => `${colors2.white}${text}${colors2.reset}`,
2077
- gray: (text) => `${colors2.gray}${text}${colors2.reset}`,
2078
- bold: (text) => `${colors2.bold}${text}${colors2.reset}`,
2079
- dim: (text) => `${colors2.dim}${text}${colors2.reset}`,
2080
- hex: (_color) => (text) => text
2081
- };
2082
-
2083
- // src/cli/middleware.ts
2084
- async function generateMiddlewareTypes(outputPath) {
2085
- const middlewareInfo = Object.entries(middleware).map(([key, instance]) => ({
2086
- name: key,
2087
- className: instance.constructor.name
2088
- }));
2089
- const typeContent = `/**
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.1";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=`/**
2090
33
  * This file is auto-generated.
2091
34
  * DO NOT EDIT THIS FILE DIRECTLY.
2092
35
  * To update, run 'bun router middleware:types'
2093
36
  */
2094
- import type { ${middlewareInfo.map((m) => m.className).join(", ")} } from './middleware'
37
+ import type { ${t.map((r)=>r.className).join(", ")} } from './middleware'
2095
38
 
2096
39
  /**
2097
40
  * Available middleware map with middleware names as keys
2098
41
  */
2099
42
  export interface MiddlewareMap {
2100
- ${middlewareInfo.map((m) => ` '${m.name}': ${m.className}`).join(`
43
+ ${t.map((r)=>` '${r.name}': ${r.className}`).join(`
2101
44
  `)}
2102
45
  }
2103
46
 
2104
47
  /**
2105
48
  * String literal type of available middleware names
2106
49
  */
2107
- export type MiddlewareName = ${middlewareInfo.map((m) => `'${m.name}'`).join(" | ")}
50
+ export type MiddlewareName = ${t.map((r)=>`'${r.name}'`).join(" | ")}
2108
51
 
2109
52
  /**
2110
53
  * Middleware configuration type for router setup
2111
54
  */
2112
- export type MiddlewareConfig = MiddlewareName | ${middlewareInfo.map((m) => m.className).join(" | ")}
55
+ export type MiddlewareConfig = MiddlewareName | ${t.map((r)=>r.className).join(" | ")}
2113
56
 
2114
57
  /**
2115
58
  * Function to check if a middleware name is valid
2116
59
  */
2117
60
  export function isValidMiddleware(name: string): name is MiddlewareName {
2118
- return [${middlewareInfo.map((m) => `'${m.name}'`).join(", ")}].includes(name)
2119
- }
2120
- `;
2121
- await fs2.writeFile(outputPath, typeContent);
2122
- }
2123
- async function findTsFiles(dir) {
2124
- const files = [];
2125
- const entries = await fs2.readdir(dir, { withFileTypes: true });
2126
- for (const entry of entries) {
2127
- const fullPath = path2.join(dir, entry.name);
2128
- if (entry.isDirectory()) {
2129
- files.push(...await findTsFiles(fullPath));
2130
- } else if (entry.isFile() && entry.name.endsWith(".ts")) {
2131
- files.push(fullPath);
2132
- }
2133
- }
2134
- return files;
2135
- }
2136
- async function scanFileForMiddleware(filePath) {
2137
- const middlewareClasses = [];
2138
- try {
2139
- const content = await fs2.readFile(filePath, "utf-8");
2140
- const classRegex = /export\s+(?:default\s+)?class\s+(\w+)\s+(?:implements\s+Middleware|\{[\s\S]*?handle\s*\([\s\S]*?\))/g;
2141
- let match = null;
2142
- while (match = classRegex.exec(content)) {
2143
- const className = match[1];
2144
- if (className.includes("Middleware") || match[0].includes("implements Middleware")) {
2145
- const relativePath = path2.relative(process6.cwd(), filePath);
2146
- const importPath = relativePath.replace(/\.ts$/, "");
2147
- middlewareClasses.push({
2148
- name: className,
2149
- path: importPath
2150
- });
2151
- }
2152
- }
2153
- } catch (error) {
2154
- console.warn(chalk.yellow(`Error scanning file ${filePath}: ${error}`));
2155
- }
2156
- return middlewareClasses;
61
+ return [${t.map((r)=>`'${r.name}'`).join(", ")}].includes(name)
2157
62
  }
2158
- async function generateMiddlewareMap(directoryPath, outputPath) {
2159
- console.log(chalk.blue(`Scanning directory: ${directoryPath} for middleware classes...`));
2160
- try {
2161
- const tsFiles = await findTsFiles(directoryPath);
2162
- const allMiddleware = [];
2163
- for (const file of tsFiles) {
2164
- const middlewareInFile = await scanFileForMiddleware(file);
2165
- allMiddleware.push(...middlewareInFile);
2166
- }
2167
- if (allMiddleware.length === 0) {
2168
- console.warn(chalk.yellow("No middleware classes found in the specified directory."));
2169
- return;
2170
- }
2171
- const imports = allMiddleware.map((m) => `import { ${m.name} } from '${m.path}'`).join(`
2172
- `);
2173
- const interfaceMembers = allMiddleware.map((m) => ` ${m.name}: typeof ${m.name}`).join(`
2174
- `);
2175
- const typeNames = allMiddleware.map((m) => m.name).join(" | ");
2176
- const typeContent = `/**
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=`/**
2177
66
  * This file is auto-generated.
2178
67
  * DO NOT EDIT THIS FILE DIRECTLY.
2179
68
  * To update, run 'bun router middleware:map'
2180
69
  */
2181
70
 
2182
- ${imports}
71
+ ${n}
2183
72
 
2184
73
  /**
2185
74
  * Map of all available middleware in the project
2186
75
  */
2187
76
  export interface MiddlewareMap {
2188
- ${interfaceMembers}
77
+ ${o}
2189
78
  }
2190
79
 
2191
80
  /**
2192
81
  * Type representing all available middleware classes in the project
2193
82
  */
2194
- export type MiddlewareType = ${typeNames}
83
+ export type MiddlewareType = ${l}
2195
84
 
2196
85
  /**
2197
86
  * Type for a middleware handler function
@@ -2202,377 +91,10 @@ export type MiddlewareHandler = (req: any, next: () => Promise<Response>) => Pro
2202
91
  * Ensure the middleware module exports all the middleware classes used in the project
2203
92
  */
2204
93
  export const middlewareMap: MiddlewareMap = {
2205
- ${allMiddleware.map((m) => ` ${m.name}: ${m.name}`).join(`,
94
+ ${r.map((i)=>` ${i.name}: ${i.name}`).join(`,
2206
95
  `)}
2207
96
  }
2208
- `;
2209
- await fs2.writeFile(outputPath, typeContent);
2210
- console.log(chalk.green(`\u2728 Middleware map generated at ${outputPath} with ${allMiddleware.length} middleware classes`));
2211
- console.log(chalk.blue("Found middleware classes:"));
2212
- for (const m of allMiddleware) {
2213
- console.log(chalk.cyan(` - ${m.name} (${m.path})`));
2214
- }
2215
- } catch (error) {
2216
- console.error(chalk.red(`Error generating middleware map: ${error}`));
2217
- throw error;
2218
- }
2219
- }
2220
- async function watchDirectoryForMiddleware(directoryPath, outputPath) {
2221
- try {
2222
- await fs2.access(directoryPath);
2223
- } catch {
2224
- console.error(chalk.red(`Directory not found at ${directoryPath}`));
2225
- process6.exit(1);
2226
- }
2227
- await generateMiddlewareMap(directoryPath, outputPath);
2228
- console.log(chalk.blue(`Watching for changes in ${directoryPath}...`));
2229
- let timeoutId = null;
2230
- const watcher = fs2.watch(directoryPath, { recursive: true });
2231
- for await (const _event of watcher) {
2232
- if (timeoutId) {
2233
- clearTimeout(timeoutId);
2234
- }
2235
- timeoutId = setTimeout(async () => {
2236
- console.log(chalk.yellow(`Changes detected. Regenerating middleware map...`));
2237
- try {
2238
- await generateMiddlewareMap(directoryPath, outputPath);
2239
- } catch (error) {
2240
- console.error(chalk.red(`Error regenerating middleware map: ${error.message}`));
2241
- }
2242
- timeoutId = null;
2243
- }, 500);
2244
- }
2245
- }
2246
- async function watchMiddlewareDirectory(outputPath) {
2247
- const middlewarePath = path2.join(process6.cwd(), "src", "middleware");
2248
- try {
2249
- await fs2.access(middlewarePath);
2250
- } catch {
2251
- console.error(chalk.red(`Middleware directory not found at ${middlewarePath}`));
2252
- process6.exit(1);
2253
- }
2254
- await generateMiddlewareTypes(outputPath);
2255
- console.log(chalk.green(`\u2728 Middleware types generated at ${outputPath}`));
2256
- console.log(chalk.blue(`Watching for changes in ${middlewarePath}...`));
2257
- let timeoutId = null;
2258
- const watcher = fs2.watch(middlewarePath, { recursive: true });
2259
- for await (const _event of watcher) {
2260
- if (timeoutId) {
2261
- clearTimeout(timeoutId);
2262
- }
2263
- timeoutId = setTimeout(async () => {
2264
- console.log(chalk.yellow(`Changes detected in middleware directory. Regenerating types...`));
2265
- try {
2266
- await generateMiddlewareTypes(outputPath);
2267
- console.log(chalk.green(`\u2728 Middleware types regenerated at ${outputPath}`));
2268
- } catch (error) {
2269
- console.error(chalk.red(`Error regenerating types: ${error.message}`));
2270
- }
2271
- timeoutId = null;
2272
- }, 500);
2273
- }
2274
- }
2275
-
2276
- // src/cli/openapi.ts
2277
- import fs3 from "fs/promises";
2278
- import process10 from "process";
2279
- async function generateOpenAPISpec(options) {
2280
- try {
2281
- const routesFile = `${process10.cwd()}/routes/index.ts`;
2282
- const { router } = await import(routesFile);
2283
- if (!router) {
2284
- console.error(chalk.red(`Could not find router instance in ${routesFile}.`));
2285
- process10.exit(1);
2286
- }
2287
- const routes = router.routes || [];
2288
- if (routes.length === 0) {
2289
- console.log(chalk.yellow("No routes defined. Creating empty OpenAPI specification."));
2290
- }
2291
- const apiRoutes = routes.filter((route) => {
2292
- return route.type === "api" || route.path.startsWith("/api");
2293
- });
2294
- const openapi = {
2295
- openapi: "3.0.3",
2296
- info: {
2297
- title: options.title || "API Documentation",
2298
- version: options.version || "1.0.0",
2299
- description: options.description || "Generated API documentation"
2300
- },
2301
- servers: generateServers(options),
2302
- paths: {},
2303
- components: {
2304
- schemas: {},
2305
- securitySchemes: {}
2306
- },
2307
- tags: []
2308
- };
2309
- const uniqueTags = new Set;
2310
- for (const route of apiRoutes) {
2311
- const pathItem = openapi.paths[route.path] || {};
2312
- let tag = "";
2313
- if (options.tags !== false) {
2314
- tag = route.tag || extractTagFromPath(route.path);
2315
- uniqueTags.add(tag);
2316
- }
2317
- const operation = {
2318
- summary: route.summary || `${route.method.toUpperCase()} ${route.path}`,
2319
- description: route.description || "",
2320
- operationId: route.name || generateOperationId(route.method, route.path),
2321
- parameters: generateParameters(route),
2322
- responses: generateResponses(route)
2323
- };
2324
- if (tag) {
2325
- operation.tags = [tag];
2326
- }
2327
- if (["post", "put", "patch"].includes(route.method.toLowerCase())) {
2328
- operation.requestBody = generateRequestBody(route);
2329
- }
2330
- if (options.security !== false && route.middleware) {
2331
- const securityItems = extractSecurityFromMiddleware(route.middleware);
2332
- if (securityItems.length > 0) {
2333
- operation.security = securityItems;
2334
- }
2335
- }
2336
- pathItem[route.method.toLowerCase()] = operation;
2337
- openapi.paths[route.path] = pathItem;
2338
- }
2339
- if (options.tags !== false) {
2340
- openapi.tags = Array.from(uniqueTags).map((tag) => ({
2341
- name: tag,
2342
- description: `Operations related to ${tag}`
2343
- }));
2344
- }
2345
- const outputPath = options.output || "openapi.json";
2346
- await fs3.writeFile(outputPath, JSON.stringify(openapi, null, 2));
2347
- console.log(chalk.green(`\u2728 OpenAPI specification generated at ${outputPath}`));
2348
- console.log(chalk.blue(`Import this file into Postman, Swagger UI, or other API tools to explore your API.`));
2349
- } catch (error) {
2350
- if (error.code === "ERR_MODULE_NOT_FOUND") {
2351
- console.error(chalk.red(`Routes file not found at ${process10.cwd()}/routes/index.ts`));
2352
- console.error(chalk.yellow('Make sure your routes are defined and exported as "router" in routes/index.ts'));
2353
- } else {
2354
- console.error(chalk.red(`Error generating OpenAPI specification: ${error.message}`));
2355
- }
2356
- throw error;
2357
- }
2358
- }
2359
- function generateServers(options) {
2360
- const servers = [];
2361
- if (options.servers) {
2362
- const serverUrls = options.servers.split(",").map((url) => url.trim());
2363
- for (const url of serverUrls) {
2364
- servers.push({
2365
- url,
2366
- description: `Server ${servers.length + 1}`
2367
- });
2368
- }
2369
- }
2370
- if (servers.length === 0) {
2371
- servers.push({
2372
- url: options.basePath || "/",
2373
- description: "Default server"
2374
- });
2375
- }
2376
- return servers;
2377
- }
2378
- function extractTagFromPath(path3) {
2379
- const segments = path3.split("/").filter(Boolean);
2380
- if (segments.length > 0) {
2381
- if (segments[0].toLowerCase() === "api" && segments.length > 1) {
2382
- return segments[1];
2383
- }
2384
- return segments[0];
2385
- }
2386
- return "default";
2387
- }
2388
- function generateOperationId(method, path3) {
2389
- const pathWithoutParams = path3.replace(/\{([^}]+)\}/g, "_$1");
2390
- const segments = pathWithoutParams.split("/").filter(Boolean);
2391
- if (segments.length === 0) {
2392
- return method.toLowerCase();
2393
- }
2394
- let operationId = method.toLowerCase();
2395
- for (const segment of segments) {
2396
- operationId += segment.charAt(0).toUpperCase() + segment.slice(1);
2397
- }
2398
- return operationId;
2399
- }
2400
- function generateParameters(route) {
2401
- const parameters = [];
2402
- const pathParams = route.path.match(/\{([^}]+)\}/g);
2403
- if (pathParams) {
2404
- for (const param of pathParams) {
2405
- const paramName = param.slice(1, -1);
2406
- parameters.push({
2407
- name: paramName,
2408
- in: "path",
2409
- required: true,
2410
- schema: {
2411
- type: "string"
2412
- },
2413
- description: `Path parameter: ${paramName}`
2414
- });
2415
- }
2416
- }
2417
- if (route.params && route.params.query) {
2418
- for (const [name, schema] of Object.entries(route.params.query)) {
2419
- parameters.push({
2420
- name,
2421
- in: "query",
2422
- schema: mapSchemaType(schema),
2423
- required: schema.required === true,
2424
- description: schema.description || `Query parameter: ${name}`
2425
- });
2426
- }
2427
- }
2428
- return parameters;
2429
- }
2430
- function mapSchemaType(schema) {
2431
- if (!schema || typeof schema !== "object") {
2432
- return { type: "string" };
2433
- }
2434
- const openApiSchema = {};
2435
- if (schema.type) {
2436
- openApiSchema.type = schema.type;
2437
- }
2438
- if (schema.format) {
2439
- openApiSchema.format = schema.format;
2440
- }
2441
- if (schema.enum) {
2442
- openApiSchema.enum = schema.enum;
2443
- }
2444
- if (schema.default !== undefined) {
2445
- openApiSchema.default = schema.default;
2446
- }
2447
- return openApiSchema;
2448
- }
2449
- function generateResponses(route) {
2450
- const responses = {
2451
- 200: {
2452
- description: "Successful response",
2453
- content: {
2454
- "application/json": {
2455
- schema: {}
2456
- }
2457
- }
2458
- }
2459
- };
2460
- responses["400"] = {
2461
- description: "Bad request",
2462
- content: {
2463
- "application/json": {
2464
- schema: {
2465
- type: "object",
2466
- properties: {
2467
- error: { type: "string" }
2468
- }
2469
- }
2470
- }
2471
- }
2472
- };
2473
- responses["401"] = {
2474
- description: "Unauthorized",
2475
- content: {
2476
- "application/json": {
2477
- schema: {
2478
- type: "object",
2479
- properties: {
2480
- error: { type: "string" }
2481
- }
2482
- }
2483
- }
2484
- }
2485
- };
2486
- responses["404"] = {
2487
- description: "Not found",
2488
- content: {
2489
- "application/json": {
2490
- schema: {
2491
- type: "object",
2492
- properties: {
2493
- error: { type: "string" }
2494
- }
2495
- }
2496
- }
2497
- }
2498
- };
2499
- responses["500"] = {
2500
- description: "Server error",
2501
- content: {
2502
- "application/json": {
2503
- schema: {
2504
- type: "object",
2505
- properties: {
2506
- error: { type: "string" }
2507
- }
2508
- }
2509
- }
2510
- }
2511
- };
2512
- if (route.responses) {
2513
- for (const [status, response] of Object.entries(route.responses)) {
2514
- responses[status] = {
2515
- description: response.description || `Response with status ${status}`,
2516
- content: {
2517
- "application/json": {
2518
- schema: response.schema || {}
2519
- }
2520
- }
2521
- };
2522
- }
2523
- }
2524
- return responses;
2525
- }
2526
- function generateRequestBody(route) {
2527
- const requestBody = {
2528
- required: true,
2529
- content: {
2530
- "application/json": {
2531
- schema: {
2532
- type: "object"
2533
- }
2534
- }
2535
- }
2536
- };
2537
- if (route.params && route.params.body) {
2538
- requestBody.content["application/json"].schema = route.params.body;
2539
- }
2540
- return requestBody;
2541
- }
2542
- function extractSecurityFromMiddleware(middleware2) {
2543
- const securityItems = [];
2544
- for (const mw of middleware2) {
2545
- const name = typeof mw === "string" ? mw : mw.name;
2546
- if (name && name.toLowerCase().includes("auth")) {
2547
- if (name.toLowerCase().includes("jwt")) {
2548
- securityItems.push({ BearerAuth: [] });
2549
- } else if (name.toLowerCase().includes("apikey")) {
2550
- securityItems.push({ ApiKeyAuth: [] });
2551
- } else if (name.toLowerCase().includes("basic")) {
2552
- securityItems.push({ BasicAuth: [] });
2553
- } else {
2554
- securityItems.push({ [name]: [] });
2555
- }
2556
- }
2557
- }
2558
- return securityItems;
2559
- }
2560
-
2561
- // src/cli/router.ts
2562
- import fs4 from "fs/promises";
2563
- import path3 from "path";
2564
- import process12 from "process";
2565
- async function generateRouterTypes(outputPath) {
2566
- try {
2567
- const routesFile = `${process12.cwd()}/routes/index.ts`;
2568
- const { router } = await import(routesFile);
2569
- if (!router) {
2570
- console.error(chalk.red(`Could not find router instance in ${routesFile}.`));
2571
- process12.exit(1);
2572
- }
2573
- const routerMethods = Object.getOwnPropertyNames(Object.getPrototypeOf(router)).filter((method) => !method.startsWith("_") && method !== "constructor" && typeof router[method] === "function");
2574
- const extendedProperties = Object.keys(router).filter((prop) => !["routes", "middleware", "hooks", "config"].includes(prop) && typeof prop === "string" && !prop.startsWith("_"));
2575
- const typeContent = `/**
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=`/**
2576
98
  * This file is auto-generated.
2577
99
  * DO NOT EDIT THIS FILE DIRECTLY.
2578
100
  * To update, run 'bun router router:types'
@@ -2583,23 +105,10 @@ import type { Router, RouteHandler, MiddlewareHandler, RouteDefinition } from '.
2583
105
  * Extended Router interface with all available methods and properties
2584
106
  */
2585
107
  export interface ExtendedRouter extends Router {
2586
- ${routerMethods.map((method) => {
2587
- if (["get", "post", "put", "delete", "patch", "options", "head"].includes(method)) {
2588
- return `${method}(path: string, handler: RouteHandler, options?: any): Router`;
2589
- } else if (method === "use") {
2590
- return `${method}(middleware: MiddlewareHandler | MiddlewareHandler[]): Router`;
2591
- } else if (method === "group") {
2592
- return `${method}(prefix: string, callback: (router: Router) => void): Router`;
2593
- } else {
2594
- return `${method}: Function`;
2595
- }
2596
- }).join(`
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(`
2597
109
  `)}
2598
110
 
2599
- ${extendedProperties.map((prop) => {
2600
- const propType = typeof router[prop];
2601
- return `${prop}: ${propType}`;
2602
- }).join(`
111
+ ${n.map((l)=>{let a=typeof s[l];return`${l}: ${a}`}).join(`
2603
112
  `)}
2604
113
  }
2605
114
 
@@ -2630,138 +139,9 @@ export type RouterExtension = {
2630
139
  * \`\`\`
2631
140
  */
2632
141
  export type ExtendRouter<T extends RouterExtension> = Router & T
2633
- `;
2634
- await fs4.writeFile(outputPath, typeContent);
2635
- console.log(chalk.green(`\u2728 Router types generated at ${outputPath}`));
2636
- } catch (error) {
2637
- if (error.code === "ERR_MODULE_NOT_FOUND") {
2638
- console.error(chalk.red(`Routes file not found at ${process12.cwd()}/routes/index.ts`));
2639
- console.error(chalk.yellow('Make sure your routes are defined and exported as "router" in routes/index.ts'));
2640
- } else {
2641
- console.error(chalk.red(`Error generating router types: ${error.message}`));
2642
- }
2643
- throw error;
2644
- }
2645
- }
2646
- async function watchRouterFiles(outputPath) {
2647
- const routerFiles = [
2648
- path3.join(process12.cwd(), "routes"),
2649
- path3.join(process12.cwd(), "src")
2650
- ];
2651
- let validPath = false;
2652
- for (const dirPath of routerFiles) {
2653
- try {
2654
- await fs4.access(dirPath);
2655
- validPath = true;
2656
- break;
2657
- } catch {}
2658
- }
2659
- if (!validPath) {
2660
- console.error(chalk.red(`No valid source directories found to watch.`));
2661
- process12.exit(1);
2662
- }
2663
- await generateRouterTypes(outputPath);
2664
- console.log(chalk.green(`\u2728 Router types generated at ${outputPath}`));
2665
- console.log(chalk.blue(`Watching for changes in router files...`));
2666
- let timeoutId = null;
2667
- for (const dirPath of routerFiles) {
2668
- try {
2669
- const watcher = fs4.watch(dirPath, { recursive: true });
2670
- (async () => {
2671
- for await (const _event of watcher) {
2672
- if (timeoutId) {
2673
- clearTimeout(timeoutId);
2674
- }
2675
- timeoutId = setTimeout(async () => {
2676
- console.log(chalk.yellow(`Changes detected in router files. Regenerating types...`));
2677
- try {
2678
- await generateRouterTypes(outputPath);
2679
- console.log(chalk.green(`\u2728 Router types regenerated at ${outputPath}`));
2680
- } catch (error) {
2681
- console.error(chalk.red(`Error regenerating types: ${error.message}`));
2682
- }
2683
- timeoutId = null;
2684
- }, 500);
2685
- }
2686
- })();
2687
- } catch {}
2688
- }
2689
- }
2690
-
2691
- // src/cli/routes.ts
2692
- import fs5 from "fs/promises";
2693
- import path4 from "path";
2694
- import process13 from "process";
2695
- async function displayRoutes(options) {
2696
- try {
2697
- const routesFile = `${process13.cwd()}/routes/index.ts`;
2698
- const { router } = await import(routesFile);
2699
- if (!router) {
2700
- console.error(chalk.red(`Could not find router instance in ${routesFile}.`));
2701
- process13.exit(1);
2702
- }
2703
- const routes = router.routes || [];
2704
- if (routes.length === 0) {
2705
- console.log(chalk.yellow("No routes defined."));
2706
- return;
2707
- }
2708
- let filteredRoutes = routes;
2709
- if (options.path) {
2710
- filteredRoutes = filteredRoutes.filter((route) => route.path.startsWith(options.path));
2711
- }
2712
- console.log(chalk.bold(`
2713
- Routes:`));
2714
- console.log(chalk.dim("+-----------------+-------------------------+------------------+----------------+"));
2715
- console.log(chalk.dim("| ") + chalk.bold("Method") + chalk.dim(" | ") + chalk.bold("URI") + chalk.dim(" | ") + chalk.bold("Name") + chalk.dim(" | ") + chalk.bold("Handler") + chalk.dim(" |"));
2716
- console.log(chalk.dim("+-----------------+-------------------------+------------------+----------------+"));
2717
- filteredRoutes.forEach((route) => {
2718
- const method = padString(route.method, 15);
2719
- const path5 = padString(route.path, 23);
2720
- const name = padString(route.name || "", 16);
2721
- let handler;
2722
- if (typeof route.handler === "string") {
2723
- handler = route.handler;
2724
- } else if (typeof route.handler === "function") {
2725
- handler = route.handler.name ? `${route.handler.name}()` : "Anonymous Function";
2726
- } else {
2727
- handler = "Class Handler";
2728
- }
2729
- handler = padString(handler, 14);
2730
- console.log(chalk.dim("| ") + getMethodColor(route.method)(method) + chalk.dim(" | ") + chalk.green(path5) + chalk.dim(" | ") + chalk.yellow(name) + chalk.dim(" | ") + chalk.blue(handler) + chalk.dim(" |"));
2731
- if (options.verbose && route.middleware && route.middleware.length > 0) {
2732
- console.log(chalk.dim("| | ") + chalk.dim("Middleware: ") + route.middleware.map((m) => typeof m === "string" ? m : m.name || "Anonymous").join(", ") + chalk.dim(" |"));
2733
- }
2734
- });
2735
- console.log(chalk.dim("+-----------------+-------------------------+------------------+----------------+"));
2736
- console.log(`
2737
- Showing ${filteredRoutes.length} routes`);
2738
- } catch (error) {
2739
- console.error(chalk.red(`Error: ${error.message}`));
2740
- console.error(chalk.yellow(`Make sure your routes are defined in ${process13.cwd()}/routes/index.ts and export a 'router' instance.`));
2741
- throw error;
2742
- }
2743
- }
2744
- async function generateRouteTypes(outputPath) {
2745
- try {
2746
- const routesFile = `${process13.cwd()}/routes/index.ts`;
2747
- const { router } = await import(routesFile);
2748
- if (!router) {
2749
- console.error(chalk.red(`Could not find router instance in ${routesFile}.`));
2750
- process13.exit(1);
2751
- }
2752
- const routes = router.routes || [];
2753
- if (routes.length === 0) {
2754
- console.log(chalk.yellow("No routes defined. Creating empty types file."));
2755
- }
2756
- const routeNames = routes.map((route) => {
2757
- if (route.name)
2758
- return route.name;
2759
- const methodLower = route.method.toLowerCase();
2760
- const pathFormatted = route.path.replace(/^\//, "").replace(/\//g, ".").replace(/\{([^}]+)\}/g, ":$1");
2761
- return pathFormatted ? `${methodLower}.${pathFormatted}` : methodLower;
2762
- });
2763
- const uniqueRouteNames = [...new Set(routeNames)];
2764
- const typeContent = `/**
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=`/**
2765
145
  * This file is auto-generated.
2766
146
  * DO NOT EDIT THIS FILE DIRECTLY.
2767
147
  * To update, run 'bun router route:types'
@@ -2770,13 +150,13 @@ async function generateRouteTypes(outputPath) {
2770
150
  /**
2771
151
  * String literal type for all available route names
2772
152
  */
2773
- export type RouteName = ${uniqueRouteNames.length > 0 ? uniqueRouteNames.map((name) => `'${name}'`).join(" | ") : "string"}
153
+ export type RouteName = ${o.length>0?o.map((a)=>`'${a}'`).join(" | "):"string"}
2774
154
 
2775
155
  /**
2776
156
  * Object type with route names as keys and string (for path generation) as values
2777
157
  */
2778
158
  export interface RouteNameMap {
2779
- ${uniqueRouteNames.map((name) => ` '${name}': string`).join(`
159
+ ${o.map((a)=>` '${a}': string`).join(`
2780
160
  `)}
2781
161
  }
2782
162
 
@@ -2789,575 +169,13 @@ export type RouteFunction = <T extends RouteName>(name: T, params?: Record<strin
2789
169
  * Validate that a string is a valid route name
2790
170
  */
2791
171
  export function isValidRouteName(name: string): name is RouteName {
2792
- return [${uniqueRouteNames.map((name) => `'${name}'`).join(", ")}].includes(name)
2793
- }
2794
- `;
2795
- await fs5.writeFile(outputPath, typeContent);
2796
- console.log(chalk.green(`\u2728 Route types generated at ${outputPath}`));
2797
- } catch (error) {
2798
- if (error.code === "ERR_MODULE_NOT_FOUND") {
2799
- console.error(chalk.red(`Routes file not found at ${process13.cwd()}/routes/index.ts`));
2800
- console.error(chalk.yellow('Make sure your routes are defined and exported as "router" in routes/index.ts'));
2801
- } else {
2802
- console.error(chalk.red(`Error generating route types: ${error.message}`));
2803
- }
2804
- throw error;
2805
- }
2806
- }
2807
- async function watchRoutesDirectory(outputPath) {
2808
- const routesPath = path4.join(process13.cwd(), "routes");
2809
- try {
2810
- await fs5.access(routesPath);
2811
- } catch {
2812
- console.error(chalk.red(`Routes directory not found at ${routesPath}`));
2813
- process13.exit(1);
2814
- }
2815
- await generateRouteTypes(outputPath);
2816
- console.log(chalk.green(`\u2728 Route types generated at ${outputPath}`));
2817
- console.log(chalk.blue(`Watching for changes in ${routesPath}...`));
2818
- let timeoutId = null;
2819
- const watcher = fs5.watch(routesPath, { recursive: true });
2820
- for await (const _event of watcher) {
2821
- if (timeoutId) {
2822
- clearTimeout(timeoutId);
2823
- }
2824
- timeoutId = setTimeout(async () => {
2825
- console.log(chalk.yellow(`Changes detected in routes directory. Regenerating types...`));
2826
- try {
2827
- await generateRouteTypes(outputPath);
2828
- console.log(chalk.green(`\u2728 Route types regenerated at ${outputPath}`));
2829
- } catch (error) {
2830
- console.error(chalk.red(`Error regenerating types: ${error.message}`));
2831
- }
2832
- timeoutId = null;
2833
- }, 500);
2834
- }
2835
- }
2836
- function padString(str, length) {
2837
- return (str + " ".repeat(length)).substring(0, length);
2838
- }
2839
- function getMethodColor(method) {
2840
- switch (method.toUpperCase()) {
2841
- case "GET":
2842
- return chalk.cyan;
2843
- case "POST":
2844
- return chalk.green;
2845
- case "PUT":
2846
- return chalk.yellow;
2847
- case "PATCH":
2848
- return chalk.yellow;
2849
- case "DELETE":
2850
- return chalk.red;
2851
- case "OPTIONS":
2852
- return chalk.gray;
2853
- default:
2854
- return chalk.white;
2855
- }
2856
- }
2857
-
2858
- // src/cli/utils.ts
2859
- import process14 from "process";
2860
- var format = {
2861
- success: (message) => chalk.green(`\u2728 ${message}`),
2862
- info: (message) => chalk.blue(message),
2863
- warning: (message) => chalk.yellow(message),
2864
- error: (message) => chalk.red(message),
2865
- dim: (message) => chalk.dim(message),
2866
- bold: (message) => chalk.bold(message)
2867
- };
2868
- var logger = {
2869
- success: (message) => console.log(format.success(message)),
2870
- info: (message) => console.log(format.info(message)),
2871
- warning: (message) => console.log(format.warning(message)),
2872
- error: (message) => console.error(format.error(message)),
2873
- debug: (message) => console.debug(format.dim(message))
2874
- };
2875
- async function loadRouter() {
2876
- try {
2877
- const routesFile = `${process14.cwd()}/routes/index.ts`;
2878
- const { router } = await import(routesFile);
2879
- if (!router) {
2880
- logger.error(`Could not find router instance in ${routesFile}.`);
2881
- process14.exit(1);
2882
- }
2883
- return router;
2884
- } catch (error) {
2885
- if (error.code === "ERR_MODULE_NOT_FOUND") {
2886
- logger.error(`Routes file not found at ${process14.cwd()}/routes/index.ts`);
2887
- logger.warning('Make sure your routes are defined and exported as "router" in routes/index.ts');
2888
- } else {
2889
- logger.error(`Error loading router: ${error.message}`);
2890
- }
2891
- throw error;
2892
- }
2893
- }
2894
- function getMethodColor2(method) {
2895
- switch (method.toUpperCase()) {
2896
- case "GET":
2897
- return chalk.cyan.toString();
2898
- case "POST":
2899
- return chalk.green.toString();
2900
- case "PUT":
2901
- return chalk.yellow.toString();
2902
- case "PATCH":
2903
- return chalk.yellow.toString();
2904
- case "DELETE":
2905
- return chalk.red.toString();
2906
- case "OPTIONS":
2907
- return chalk.gray.toString();
2908
- default:
2909
- return chalk.white.toString();
2910
- }
2911
- }
2912
- async function checkRouterHealth(options) {
2913
- logger.info("\uD83D\uDD0D Checking router health...");
2914
- try {
2915
- const router = await loadRouter();
2916
- const routes = router.routes || [];
2917
- const globalMiddleware = router.globalMiddleware || [];
2918
- const namedRoutes = router.namedRoutes || new Map;
2919
- const health = {
2920
- totalRoutes: routes.length,
2921
- namedRoutes: namedRoutes.size,
2922
- globalMiddleware: globalMiddleware.length,
2923
- routesByMethod: {},
2924
- duplicateRoutes: [],
2925
- routesWithMiddleware: 0,
2926
- staticRoutes: 0,
2927
- dynamicRoutes: 0
2928
- };
2929
- const routeMap = new Map;
2930
- for (const route of routes) {
2931
- const key = `${route.method}:${route.path}`;
2932
- health.routesByMethod[route.method] = (health.routesByMethod[route.method] || 0) + 1;
2933
- if (!routeMap.has(key)) {
2934
- routeMap.set(key, []);
2935
- }
2936
- routeMap.get(key).push(route.path);
2937
- if (routeMap.get(key).length > 1) {
2938
- health.duplicateRoutes.push({ path: route.path, method: route.method });
2939
- }
2940
- if (route.middleware && route.middleware.length > 0) {
2941
- health.routesWithMiddleware++;
2942
- }
2943
- if (route.path.includes("{") || route.path.includes("*")) {
2944
- health.dynamicRoutes++;
2945
- } else {
2946
- health.staticRoutes++;
2947
- }
2948
- }
2949
- logger.success(`Router health check completed`);
2950
- console.log(`\uD83D\uDCCA Routes: ${health.totalRoutes} total (${health.staticRoutes} static, ${health.dynamicRoutes} dynamic)`);
2951
- console.log(`\uD83D\uDCDB Named routes: ${health.namedRoutes}`);
2952
- console.log(`\uD83D\uDEE1\uFE0F Global middleware: ${health.globalMiddleware}`);
2953
- console.log(`\uD83D\uDD27 Routes with middleware: ${health.routesWithMiddleware}`);
2954
- if (options.verbose) {
2955
- console.log(`
2956
- \uD83D\uDCC8 Routes by method:`);
2957
- for (const [method, count] of Object.entries(health.routesByMethod)) {
2958
- const color = getMethodColor2(method);
2959
- console.log(` ${chalk.hex(color)(method.padEnd(8))}: ${count}`);
2960
- }
2961
- if (health.duplicateRoutes.length > 0) {
2962
- logger.warning(`
2963
- \u26A0\uFE0F Found ${health.duplicateRoutes.length} duplicate route(s):`);
2964
- for (const duplicate of health.duplicateRoutes) {
2965
- console.log(` ${duplicate.method} ${duplicate.path}`);
2966
- }
2967
- }
2968
- const issues = [];
2969
- if (health.totalRoutes === 0) {
2970
- issues.push("No routes defined");
2971
- }
2972
- if (health.duplicateRoutes.length > 0) {
2973
- issues.push(`${health.duplicateRoutes.length} duplicate routes`);
2974
- }
2975
- if (health.routesWithMiddleware === 0 && health.globalMiddleware === 0) {
2976
- issues.push("No middleware configured");
2977
- }
2978
- if (issues.length > 0) {
2979
- logger.warning(`
2980
- \u26A0\uFE0F Potential issues:`);
2981
- for (const issue of issues) {
2982
- console.log(` \u2022 ${issue}`);
2983
- }
2984
- } else {
2985
- logger.success(`
2986
- \u2705 No issues detected`);
2987
- }
2988
- }
2989
- } catch (error) {
2990
- logger.error(`Health check failed: ${error.message}`);
2991
- throw error;
2992
- }
2993
- }
2994
- async function testRoutes(options) {
2995
- const baseUrl = options.baseUrl || "http://localhost:3000";
2996
- const timeout = options.timeout || 5000;
2997
- const allowedMethods = options.method ? options.method.split(",").map((m) => m.trim().toUpperCase()) : null;
2998
- logger.info(`\uD83E\uDDEA Testing routes at ${baseUrl}...`);
2999
- try {
3000
- const router = await loadRouter();
3001
- const routes = router.routes || [];
3002
- let filteredRoutes = routes;
3003
- if (options.filter) {
3004
- const pattern = new RegExp(options.filter.replace(/\*/g, ".*"));
3005
- filteredRoutes = routes.filter((route) => pattern.test(route.path));
3006
- }
3007
- if (allowedMethods) {
3008
- filteredRoutes = filteredRoutes.filter((route) => allowedMethods.includes(route.method));
3009
- }
3010
- if (filteredRoutes.length === 0) {
3011
- logger.warning("No routes match the specified filters");
3012
- return;
3013
- }
3014
- logger.info(`Testing ${filteredRoutes.length} routes...`);
3015
- const results = {
3016
- total: 0,
3017
- passed: 0,
3018
- failed: 0,
3019
- errors: []
3020
- };
3021
- for (const route of filteredRoutes) {
3022
- results.total++;
3023
- if (route.path.includes("{")) {
3024
- logger.debug(`Skipping parameterized route: ${route.method} ${route.path}`);
3025
- continue;
3026
- }
3027
- try {
3028
- const url = `${baseUrl}${route.path}`;
3029
- const response = await fetch(url, {
3030
- method: route.method,
3031
- signal: AbortSignal.timeout(timeout)
3032
- });
3033
- if (response.status < 500) {
3034
- results.passed++;
3035
- logger.debug(`\u2705 ${route.method} ${route.path} \u2192 ${response.status}`);
3036
- } else {
3037
- results.failed++;
3038
- results.errors.push({
3039
- route: `${route.method} ${route.path}`,
3040
- error: `HTTP ${response.status}`
3041
- });
3042
- }
3043
- } catch (error) {
3044
- results.failed++;
3045
- results.errors.push({
3046
- route: `${route.method} ${route.path}`,
3047
- error: error.message
3048
- });
3049
- }
3050
- }
3051
- console.log(`
3052
- \uD83D\uDCCA Test Results:`);
3053
- console.log(` Total: ${results.total}`);
3054
- console.log(` Passed: ${chalk.green(String(results.passed))}`);
3055
- console.log(` Failed: ${chalk.red(String(results.failed))}`);
3056
- if (results.errors.length > 0) {
3057
- console.log(`
3058
- \u274C Failures:`);
3059
- for (const error of results.errors) {
3060
- console.log(` ${error.route}: ${error.error}`);
3061
- }
3062
- }
3063
- if (results.failed > 0) {
3064
- process14.exit(1);
3065
- } else {
3066
- logger.success("All tests passed!");
3067
- }
3068
- } catch (error) {
3069
- logger.error(`Route testing failed: ${error.message}`);
3070
- throw error;
3071
- }
3072
- }
3073
- async function debugRoute(path5, options) {
3074
- const method = options.method?.toUpperCase() || "GET";
3075
- logger.info(`\uD83D\uDD0D Debugging route matching for: ${method} ${path5}`);
3076
- try {
3077
- const router = await loadRouter();
3078
- const match = router.matchRoute ? router.matchRoute(path5, method) : null;
3079
- if (match) {
3080
- logger.success(`\u2705 Route matched!`);
3081
- console.log(` Route: ${match.route.method} ${match.route.path}`);
3082
- console.log(` Handler: ${typeof match.route.handler}`);
3083
- if (Object.keys(match.params || {}).length > 0) {
3084
- console.log(` Parameters:`);
3085
- for (const [key, value] of Object.entries(match.params)) {
3086
- console.log(` ${key}: ${value}`);
3087
- }
3088
- }
3089
- if (match.route.middleware && match.route.middleware.length > 0) {
3090
- console.log(` Middleware: ${match.route.middleware.length} handler(s)`);
3091
- }
3092
- if (match.route.name) {
3093
- console.log(` Named route: ${match.route.name}`);
3094
- }
3095
- } else {
3096
- logger.error(`\u274C No route matched for ${method} ${path5}`);
3097
- if (options.verbose) {
3098
- console.log(`
3099
- \uD83D\uDCCB Available routes:`);
3100
- const routes = router.routes || [];
3101
- const methodRoutes = routes.filter((r) => r.method === method);
3102
- if (methodRoutes.length === 0) {
3103
- console.log(` No routes defined for ${method} method`);
3104
- } else {
3105
- for (const route of methodRoutes) {
3106
- console.log(` ${route.method} ${route.path}`);
3107
- }
3108
- }
3109
- }
3110
- }
3111
- } catch (error) {
3112
- logger.error(`Route debugging failed: ${error.message}`);
3113
- throw error;
3114
- }
3115
- }
3116
- async function clearCaches(options) {
3117
- logger.info("\uD83D\uDDD1\uFE0F Clearing route caches...");
3118
- try {
3119
- const router = await loadRouter();
3120
- if (options.stats) {
3121
- if (router.getCacheStats) {
3122
- const stats = router.getCacheStats();
3123
- console.log("\uD83D\uDCCA Cache statistics before clearing:");
3124
- console.log(` Hit rate: ${stats.hitRate}%`);
3125
- console.log(` Total hits: ${stats.hits}`);
3126
- console.log(` Total misses: ${stats.misses}`);
3127
- console.log(` Cache size: ${stats.size}`);
3128
- }
3129
- if (router.routeCache) {
3130
- console.log(` Route cache entries: ${router.routeCache.size}`);
3131
- }
3132
- if (router.templateCache) {
3133
- console.log(` Template cache entries: ${router.templateCache.size}`);
3134
- }
3135
- }
3136
- if (router.clearRouteCache) {
3137
- router.clearRouteCache();
3138
- }
3139
- if (router.routeCache && router.routeCache.clear) {
3140
- router.routeCache.clear();
3141
- }
3142
- if (router.templateCache && router.templateCache.clear) {
3143
- router.templateCache.clear();
3144
- }
3145
- if (router.clearModelCache) {
3146
- router.clearModelCache();
3147
- }
3148
- logger.success("\u2705 Caches cleared successfully");
3149
- } catch (error) {
3150
- logger.error(`Cache clearing failed: ${error.message}`);
3151
- throw error;
3152
- }
3153
- }
3154
- async function validateRoutes(options) {
3155
- logger.info("\uD83D\uDD0D Validating route definitions...");
3156
- try {
3157
- const router = await loadRouter();
3158
- const routes = router.routes || [];
3159
- const issues = [];
3160
- const warnings = [];
3161
- for (const route of routes) {
3162
- if (!route.method) {
3163
- issues.push(`Route missing method: ${route.path}`);
3164
- }
3165
- if (!route.path) {
3166
- issues.push(`Route missing path: ${route.method || "UNKNOWN"}`);
3167
- }
3168
- if (!route.handler) {
3169
- issues.push(`Route missing handler: ${route.method} ${route.path}`);
3170
- }
3171
- if (route.path && !route.path.startsWith("/")) {
3172
- issues.push(`Route path should start with '/': ${route.method} ${route.path}`);
3173
- }
3174
- if (route.path && route.path.includes("{")) {
3175
- const params = route.path.match(/\{[^}]+\}/g) || [];
3176
- for (const param of params) {
3177
- if (!param.match(/^\{[a-z_]\w*(\?|:[^}]+)?\}$/i)) {
3178
- issues.push(`Invalid parameter syntax in ${route.method} ${route.path}: ${param}`);
3179
- }
3180
- }
3181
- }
3182
- if (options.strict) {
3183
- if (!route.name && !route.path.includes("{") && route.path !== "/") {
3184
- warnings.push(`Consider adding a name to route: ${route.method} ${route.path}`);
3185
- }
3186
- if (route.path.includes("/admin") && (!route.middleware || route.middleware.length === 0)) {
3187
- warnings.push(`Admin route missing middleware: ${route.method} ${route.path}`);
3188
- }
3189
- }
3190
- }
3191
- const routeMap = new Map;
3192
- for (const route of routes) {
3193
- const key = `${route.method}:${route.path}`;
3194
- routeMap.set(key, (routeMap.get(key) || 0) + 1);
3195
- }
3196
- for (const [key, count] of routeMap.entries()) {
3197
- if (count > 1) {
3198
- issues.push(`Duplicate route detected: ${key} (${count} times)`);
3199
- }
3200
- }
3201
- if (issues.length === 0 && warnings.length === 0) {
3202
- logger.success("\u2705 All route definitions are valid");
3203
- return;
3204
- }
3205
- if (issues.length > 0) {
3206
- logger.error(`\u274C Found ${issues.length} validation error(s):`);
3207
- for (const issue of issues) {
3208
- console.log(` \u2022 ${issue}`);
3209
- }
3210
- }
3211
- if (warnings.length > 0) {
3212
- logger.warning(`\u26A0\uFE0F Found ${warnings.length} warning(s):`);
3213
- for (const warning of warnings) {
3214
- console.log(` \u2022 ${warning}`);
3215
- }
3216
- }
3217
- if (options.fix) {
3218
- logger.info("\uD83D\uDD27 Auto-fixing is not yet implemented");
3219
- }
3220
- if (issues.length > 0) {
3221
- process14.exit(1);
3222
- }
3223
- } catch (error) {
3224
- logger.error(`Route validation failed: ${error.message}`);
3225
- throw error;
3226
- }
3227
- }
3228
-
3229
- // src/cli/index.ts
3230
- function createCLI() {
3231
- const cli = new CLI("router");
3232
- cli.version(version);
3233
- registerRouteCommands(cli);
3234
- registerMiddlewareCommands(cli);
3235
- registerRouterCommands(cli);
3236
- registerOpenAPICommands(cli);
3237
- registerUtilityCommands(cli);
3238
- cli.help();
3239
- return cli;
3240
- }
3241
- function registerRouteCommands(cli) {
3242
- cli.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 (options) => {
3243
- try {
3244
- await displayRoutes(options);
3245
- } catch (error) {
3246
- console.error(`Failed to list routes: ${error.message}`);
3247
- process15.exit(1);
3248
- }
3249
- });
3250
- cli.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 (options) => {
3251
- try {
3252
- const outputPath = options.output || "route-types.ts";
3253
- if (options.watch) {
3254
- await watchRoutesDirectory(outputPath);
3255
- } else {
3256
- await generateRouteTypes(outputPath);
3257
- }
3258
- } catch (error) {
3259
- console.error(`Failed to generate route types: ${error.message}`);
3260
- process15.exit(1);
3261
- }
3262
- });
3263
- }
3264
- function registerMiddlewareCommands(cli) {
3265
- cli.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 (options) => {
3266
- try {
3267
- const outputPath = options.output || "middleware-types.ts";
3268
- if (options.watch) {
3269
- await watchMiddlewareDirectory(outputPath);
3270
- } else {
3271
- await generateMiddlewareTypes(outputPath);
3272
- }
3273
- } catch (error) {
3274
- console.error(`Failed to generate middleware types: ${error.message}`);
3275
- process15.exit(1);
3276
- }
3277
- });
3278
- cli.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 (options) => {
3279
- try {
3280
- const outputPath = options.output || "middleware-map.ts";
3281
- const directoryPath = options.dir || "src";
3282
- if (options.watch) {
3283
- await watchDirectoryForMiddleware(directoryPath, outputPath);
3284
- } else {
3285
- await generateMiddlewareMap(directoryPath, outputPath);
3286
- }
3287
- } catch (error) {
3288
- console.error(`Failed to generate middleware map: ${error.message}`);
3289
- process15.exit(1);
3290
- }
3291
- });
3292
- }
3293
- function registerRouterCommands(cli) {
3294
- cli.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 (options) => {
3295
- try {
3296
- const outputPath = options.output || "router-types.ts";
3297
- if (options.watch) {
3298
- await watchRouterFiles(outputPath);
3299
- } else {
3300
- await generateRouterTypes(outputPath);
3301
- }
3302
- } catch (error) {
3303
- console.error(`Failed to generate router types: ${error.message}`);
3304
- process15.exit(1);
3305
- }
3306
- });
3307
- }
3308
- function registerOpenAPICommands(cli) {
3309
- cli.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: true }).option("--security", "Include security schemes if available", { default: true }).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 (options) => {
3310
- try {
3311
- await generateOpenAPISpec(options);
3312
- } catch (error) {
3313
- console.error(`Failed to generate OpenAPI specification: ${error.message}`);
3314
- process15.exit(1);
3315
- }
3316
- });
3317
- }
3318
- function registerUtilityCommands(cli) {
3319
- cli.command("health", "Check router health and configuration").option("--verbose", "Show detailed health information").example("router health").example("router health --verbose").action(async (options) => {
3320
- try {
3321
- await checkRouterHealth(options);
3322
- } catch (error) {
3323
- console.error(`Health check failed: ${error.message}`);
3324
- process15.exit(1);
3325
- }
3326
- });
3327
- cli.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 (options) => {
3328
- try {
3329
- await testRoutes(options);
3330
- } catch (error) {
3331
- console.error(`Route testing failed: ${error.message}`);
3332
- process15.exit(1);
3333
- }
3334
- });
3335
- cli.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 (path5, options) => {
3336
- try {
3337
- await debugRoute(path5, options);
3338
- } catch (error) {
3339
- console.error(`Route debugging failed: ${error.message}`);
3340
- process15.exit(1);
3341
- }
3342
- });
3343
- cli.command("cache:clear", "Clear route caches").option("--stats", "Show cache statistics before clearing").example("router cache:clear").example("router cache:clear --stats").action(async (options) => {
3344
- try {
3345
- await clearCaches(options);
3346
- } catch (error) {
3347
- console.error(`Cache clearing failed: ${error.message}`);
3348
- process15.exit(1);
3349
- }
3350
- });
3351
- cli.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 (options) => {
3352
- try {
3353
- await validateRoutes(options);
3354
- } catch (error) {
3355
- console.error(`Route validation failed: ${error.message}`);
3356
- process15.exit(1);
3357
- }
3358
- });
3359
- }
3360
-
3361
- // src/cli.ts
3362
- var cli = createCLI();
3363
- cli.parse();
172
+ return [${o.map((a)=>`'${a}'`).join(", ")}].includes(name)
173
+ }
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();