@h3ravel/console 11.0.1 → 11.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/run.js ADDED
@@ -0,0 +1,874 @@
1
+ #!/usr/bin/env node
2
+ import { EventEmitter } from 'events';
3
+ import { ServiceProvider, Application } from '@h3ravel/core';
4
+ import { access, readFile, writeFile, mkdir } from 'fs/promises';
5
+ import chalk from 'chalk';
6
+ import nodepath, { resolve, dirname } from 'path';
7
+ import { existsSync, statSync, readdirSync } from 'fs';
8
+ import dayjs from 'dayjs';
9
+ import { arquebus } from '@h3ravel/arquebus';
10
+ import { spawn } from 'child_process';
11
+ import { program } from 'commander';
12
+ import { ConfigServiceProvider } from '@h3ravel/config';
13
+ import { DatabaseServiceProvider } from '@h3ravel/database';
14
+
15
+ var __defProp = Object.defineProperty;
16
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
17
+ function sync_default(start, callback) {
18
+ let dir = resolve(".", start);
19
+ let tmp, stats = statSync(dir);
20
+ if (!stats.isDirectory()) {
21
+ dir = dirname(dir);
22
+ }
23
+ while (true) {
24
+ tmp = callback(dir, readdirSync(dir));
25
+ if (tmp) return resolve(dir, tmp);
26
+ dir = dirname(tmp = dir);
27
+ if (tmp === dir) break;
28
+ }
29
+ }
30
+ __name(sync_default, "default");
31
+ var join = nodepath.join;
32
+ var Utils = class {
33
+ static {
34
+ __name(this, "Utils");
35
+ }
36
+ /**
37
+ * Wraps text with chalk
38
+ *
39
+ * @param txt
40
+ * @param color
41
+ * @returns
42
+ */
43
+ static textFormat(txt, color) {
44
+ return String(txt).split(":").map((e, i, a) => i == 0 && a.length > 1 ? color(" " + e + ": ") : e).join("");
45
+ }
46
+ /**
47
+ * Ouput formater object
48
+ *
49
+ * @returns
50
+ */
51
+ static output() {
52
+ return {
53
+ success: /* @__PURE__ */ __name((msg, exit = false) => {
54
+ console.log(chalk.green("\u2713"), this.textFormat(msg, chalk.bgGreen), "\n");
55
+ if (exit) process.exit(0);
56
+ }, "success"),
57
+ info: /* @__PURE__ */ __name((msg, exit = false) => {
58
+ console.log(chalk.blue("\u2139"), this.textFormat(msg, chalk.bgBlue), "\n");
59
+ if (exit) process.exit(0);
60
+ }, "info"),
61
+ error: /* @__PURE__ */ __name((msg, exit = true) => {
62
+ if (msg instanceof Error) {
63
+ if (msg.message) {
64
+ console.error(chalk.red("\u2716"), this.textFormat("ERROR:" + msg.message, chalk.bgRed));
65
+ }
66
+ console.error(chalk.red(`${msg.detail ? `${msg.detail}
67
+ ` : ""}${msg.stack}`), "\n");
68
+ } else {
69
+ console.error(chalk.red("\u2716"), this.textFormat(msg, chalk.bgRed), "\n");
70
+ }
71
+ if (exit) process.exit(1);
72
+ }, "error"),
73
+ split: /* @__PURE__ */ __name((name, value, status, exit = false) => {
74
+ status ??= "info";
75
+ const color = {
76
+ success: chalk.bgGreen,
77
+ info: chalk.bgBlue,
78
+ error: chalk.bgRed
79
+ };
80
+ const regex = /\x1b\[\d+m/g;
81
+ const width = Math.min(process.stdout.columns, 100);
82
+ const dots = Math.max(width - name.replace(regex, "").length - value.replace(regex, "").length - 10, 0);
83
+ console.log(this.textFormat(name, color[status]), chalk.gray(".".repeat(dots)), value);
84
+ if (exit) process.exit(0);
85
+ }, "split"),
86
+ quiet: /* @__PURE__ */ __name(() => {
87
+ process.exit(0);
88
+ }, "quiet")
89
+ };
90
+ }
91
+ static findModulePkg(moduleId, cwd) {
92
+ const parts = moduleId.replace(/\\/g, "/").split("/");
93
+ let packageName = "";
94
+ if (parts.length > 0 && parts[0][0] === "@") {
95
+ packageName += parts.shift() + "/";
96
+ }
97
+ packageName += parts.shift();
98
+ const packageJson = nodepath.join(cwd ?? process.cwd(), "node_modules", packageName);
99
+ const resolved = this.findUpConfig(packageJson, "package", [
100
+ "json"
101
+ ]);
102
+ if (!resolved) {
103
+ return;
104
+ }
105
+ return nodepath.join(nodepath.dirname(resolved), parts.join("/"));
106
+ }
107
+ static async getMigrationPaths(cwd, migrator, defaultPath, path3) {
108
+ if (path3) {
109
+ return [
110
+ join(cwd, path3)
111
+ ];
112
+ }
113
+ return [
114
+ ...migrator.getPaths(),
115
+ join(cwd, defaultPath)
116
+ ];
117
+ }
118
+ static twoColumnDetail(name, value) {
119
+ const regex = /\x1b\[\d+m/g;
120
+ const width = Math.min(process.stdout.columns, 100);
121
+ const dots = Math.max(width - name.replace(regex, "").length - value.replace(regex, "").length - 10, 0);
122
+ return console.log(name, chalk.gray(".".repeat(dots)), value);
123
+ }
124
+ /**
125
+ * Check if file exists
126
+ *
127
+ * @param path
128
+ * @returns
129
+ */
130
+ static async fileExists(path3) {
131
+ try {
132
+ await access(path3);
133
+ return true;
134
+ } catch {
135
+ return false;
136
+ }
137
+ }
138
+ static findUpConfig(cwd, name, extensions) {
139
+ return sync_default(cwd, (_dir, names) => {
140
+ for (const ext of extensions) {
141
+ const filename = `${name}.${ext}`;
142
+ if (names.includes(filename)) {
143
+ return filename;
144
+ }
145
+ }
146
+ return false;
147
+ });
148
+ }
149
+ };
150
+ var TableGuesser = class TableGuesser2 {
151
+ static {
152
+ __name(this, "TableGuesser");
153
+ }
154
+ static CREATE_PATTERNS = [
155
+ /^create_(\w+)_table$/,
156
+ /^create_(\w+)$/
157
+ ];
158
+ static CHANGE_PATTERNS = [
159
+ /.+_(to|from|in)_(\w+)_table$/,
160
+ /.+_(to|from|in)_(\w+)$/
161
+ ];
162
+ static guess(migration) {
163
+ for (const pattern of TableGuesser2.CREATE_PATTERNS) {
164
+ const matches = migration.match(pattern);
165
+ if (matches) {
166
+ return [
167
+ matches[1],
168
+ true
169
+ ];
170
+ }
171
+ }
172
+ for (const pattern of TableGuesser2.CHANGE_PATTERNS) {
173
+ const matches = migration.match(pattern);
174
+ if (matches) {
175
+ return [
176
+ matches[2],
177
+ false
178
+ ];
179
+ }
180
+ }
181
+ return [];
182
+ }
183
+ };
184
+
185
+ // src/Commands/Command.ts
186
+ var Command = class {
187
+ static {
188
+ __name(this, "Command");
189
+ }
190
+ app;
191
+ kernel;
192
+ constructor(app, kernel) {
193
+ this.app = app;
194
+ this.kernel = kernel;
195
+ }
196
+ /**
197
+ * The name and signature of the console command.
198
+ *
199
+ * @var string
200
+ */
201
+ signature;
202
+ /**
203
+ * A dictionary of signatures or what not.
204
+ *
205
+ * @var object
206
+ */
207
+ dictionary = {};
208
+ /**
209
+ * The console command description.
210
+ *
211
+ * @var string
212
+ */
213
+ description;
214
+ /**
215
+ * The console command input.
216
+ *
217
+ * @var object
218
+ */
219
+ input = {
220
+ options: {},
221
+ arguments: {}
222
+ };
223
+ /**
224
+ * Execute the console command.
225
+ */
226
+ async handle(..._args) {
227
+ }
228
+ setApplication(app) {
229
+ this.app = app;
230
+ }
231
+ setInput(options, args, regArgs, dictionary) {
232
+ this.dictionary = dictionary;
233
+ this.input.options = options;
234
+ this.input.arguments = regArgs.map((e, i) => ({
235
+ [e.name()]: args[i]
236
+ })).reduce((e, x) => Object.assign(e, x), {});
237
+ }
238
+ getSignature() {
239
+ return this.signature;
240
+ }
241
+ getDescription() {
242
+ return this.description;
243
+ }
244
+ option(key, def) {
245
+ return this.input.options[key] ?? def;
246
+ }
247
+ options(key) {
248
+ if (key) {
249
+ return this.input.options[key];
250
+ }
251
+ return this.input.options;
252
+ }
253
+ argument(key, def) {
254
+ return this.input.arguments[key] ?? def;
255
+ }
256
+ arguments() {
257
+ return this.input.arguments;
258
+ }
259
+ };
260
+ var MakeCommand = class extends Command {
261
+ static {
262
+ __name(this, "MakeCommand");
263
+ }
264
+ /**
265
+ * The name and signature of the console command.
266
+ *
267
+ * @var string
268
+ */
269
+ signature = `#make:
270
+ {controller : Generates a new controller class. | {--a|api : Generate an API resource controller} | {--force : Overide existing controller.} }
271
+ {resource : Generates a new API resource class.}
272
+ {migration : Generates a new database migration class. | {--l|type=ts : The file type to generate} | {--t|table : The table to migrate} | {--c|create : The table to be created} }
273
+ {factory : Generates a new database factory class.}
274
+ {seeder : Generates a new database seeder class.}
275
+ {model : Generates a new Arquebus model class. | {--t|type=ts : The file type to generate}}
276
+ {^name : The name of the [name] to generate}
277
+ `;
278
+ /**
279
+ * The console command description.
280
+ *
281
+ * @var string
282
+ */
283
+ description = "Generate component classes";
284
+ async handle() {
285
+ const command = this.dictionary.baseCommand;
286
+ const methods = {
287
+ controller: "makeController",
288
+ resource: "makeResource",
289
+ migration: "makeMigration",
290
+ factory: "makeFactory",
291
+ seeder: "makeSeeder",
292
+ model: "makeModel"
293
+ };
294
+ try {
295
+ await this?.[methods[command]]();
296
+ } catch (e) {
297
+ this.kernel.output.error(e);
298
+ }
299
+ }
300
+ /**
301
+ * Generate a new controller class.
302
+ */
303
+ async makeController() {
304
+ const type = this.option("api") ? "-resource" : "";
305
+ const name = this.argument("name");
306
+ const force = this.option("force");
307
+ const path3 = nodepath.join(app_path("Http/Controllers"), name + ".ts");
308
+ const dbPath = Utils.findModulePkg("@h3ravel/http", this.kernel.cwd) ?? "";
309
+ const stubPath = nodepath.join(dbPath, `dist/stubs/controller${type}.stub`);
310
+ if (!force && existsSync(path3)) {
311
+ this.kernel.output.error(`ERORR: ${name} controller already exists`);
312
+ }
313
+ let stub = await readFile(stubPath, "utf-8");
314
+ stub = stub.replace(/{{ name }}/g, name);
315
+ await writeFile(path3, stub);
316
+ this.kernel.output.split(`INFO: Controller Created`, chalk.gray(nodepath.basename(path3)));
317
+ }
318
+ makeResource() {
319
+ this.kernel.output.success(`Resource support is not yet available`);
320
+ }
321
+ /**
322
+ * Generate a new database migration class
323
+ */
324
+ async makeMigration() {
325
+ const name = this.argument("name");
326
+ const datePrefix = dayjs().format("YYYY_MM_DD_HHmmss");
327
+ const path3 = nodepath.join(database_path("migrations"), `${datePrefix}_${name}.ts`);
328
+ const dbPath = Utils.findModulePkg("@h3ravel/database", this.kernel.cwd) ?? "";
329
+ let create = this.option("create", false);
330
+ let table = this.option("table");
331
+ if (!table && typeof create === "string") {
332
+ table = create;
333
+ create = true;
334
+ }
335
+ if (!table) {
336
+ const guessed = TableGuesser.guess(name);
337
+ table = guessed[0];
338
+ create = !!guessed[1];
339
+ }
340
+ const stubPath = nodepath.join(dbPath, this.getMigrationStubName(table, create));
341
+ let stub = await readFile(stubPath, "utf-8");
342
+ if (table !== null) {
343
+ stub = stub.replace(/DummyTable|{{\s*table\s*}}/g, table);
344
+ }
345
+ this.kernel.output.info("INFO: Creating Migration");
346
+ await this.kernel.ensureDirectoryExists(nodepath.dirname(path3));
347
+ await writeFile(path3, stub);
348
+ this.kernel.output.split(`INFO: Migration Created`, chalk.gray(nodepath.basename(path3)));
349
+ }
350
+ makeFactory() {
351
+ this.kernel.output.success(`Factory support is not yet available`);
352
+ }
353
+ makeSeeder() {
354
+ this.kernel.output.success(`Seeder support is not yet available`);
355
+ }
356
+ /**
357
+ * Generate a new Arquebus model class
358
+ */
359
+ async makeModel() {
360
+ const type = this.option("type", "ts");
361
+ const name = this.argument("name");
362
+ const path3 = nodepath.join(app_path("Models"), name.toLowerCase() + "." + type);
363
+ const dbPath = Utils.findModulePkg("@h3ravel/database", this.kernel.cwd) ?? "";
364
+ const stubPath = nodepath.join(dbPath, `dist/stubs/model-${type}.stub`);
365
+ let stub = await readFile(stubPath, "utf-8");
366
+ stub = stub.replace(/{{ name }}/g, name);
367
+ await writeFile(path3, stub);
368
+ this.kernel.output.split(`INFO: Model Created`, chalk.gray(nodepath.basename(path3)));
369
+ }
370
+ /**
371
+ * Ge the database migration file name
372
+ *
373
+ * @param table
374
+ * @param create
375
+ * @param type
376
+ * @returns
377
+ */
378
+ getMigrationStubName(table, create = false, type = "ts") {
379
+ let stub;
380
+ if (!table) {
381
+ stub = `migration-${type}.stub`;
382
+ } else if (create) {
383
+ stub = `migration.create-${type}.stub`;
384
+ } else {
385
+ stub = `migration.update-${type}.stub`;
386
+ }
387
+ return "dist/stubs/" + stub;
388
+ }
389
+ };
390
+ var MigrateCommand = class extends Command {
391
+ static {
392
+ __name(this, "MigrateCommand");
393
+ }
394
+ /**
395
+ * The name and signature of the console command.
396
+ *
397
+ * @var string
398
+ */
399
+ signature = `migrate:
400
+ {fresh : Drop all tables and re-run all migrations.}
401
+ {install : Create the migration repository.}
402
+ {refresh : Reset and re-run all migrations.}
403
+ {reset : Rollback all database migrations.}
404
+ {rollback : Rollback the last database migration.}
405
+ {status : Show the status of each migration.}
406
+ {publish : Publish any migration files from installed packages.}
407
+ {^--s|seed : Seed the database}
408
+ `;
409
+ /**
410
+ * The console command description.
411
+ *
412
+ * @var string
413
+ */
414
+ description = "Run all pending migrations.";
415
+ /**
416
+ * Execute the console command.
417
+ */
418
+ async handle() {
419
+ const command = this.dictionary.name ?? this.dictionary.baseCommand;
420
+ const methods = {
421
+ migrate: "migrateRun",
422
+ fresh: "migrateFresh",
423
+ install: "migrateInstall",
424
+ refresh: "migrateRefresh",
425
+ reset: "migrateReset",
426
+ rollback: "migrateRollback",
427
+ status: "migrateStatus",
428
+ publish: "migratePublish"
429
+ };
430
+ await this?.[methods[command]]();
431
+ }
432
+ /**
433
+ * Run all pending migrations.
434
+ */
435
+ async migrateRun() {
436
+ this.kernel.output.success(`Running migrations are not yet supported.`);
437
+ }
438
+ /**
439
+ * Drop all tables and re-run all migrations.
440
+ */
441
+ async migrateFresh() {
442
+ this.kernel.output.success(`Drop all tables and re-run all migrations.`);
443
+ }
444
+ /**
445
+ * Create the migration repository.
446
+ */
447
+ async migrateInstall() {
448
+ this.kernel.output.success(`Create the migration repository.`);
449
+ }
450
+ /**
451
+ * Reset and re-run all migrations.
452
+ */
453
+ async migrateRefresh() {
454
+ this.kernel.output.success(`Resetting and re-running migrations is not yet supported.`);
455
+ }
456
+ /**
457
+ * Rollback all database migrations.
458
+ */
459
+ async migrateReset() {
460
+ this.kernel.output.success(`Rolling back all migration is not yet supported.`);
461
+ }
462
+ /**
463
+ * Rollback the last database migration.
464
+ */
465
+ async migrateRollback() {
466
+ this.kernel.output.success(`Rolling back the last migration is not yet supported.`);
467
+ }
468
+ /**
469
+ * Show the status of each migration.
470
+ */
471
+ async migrateStatus() {
472
+ app_path();
473
+ console.log(arquebus.connection());
474
+ this.kernel.output.success(`Show the status of each migration.`);
475
+ }
476
+ /**
477
+ * Publish any migration files from installed packages.
478
+ */
479
+ async migratePublish() {
480
+ this.kernel.output.success(`Publish any migration files from installed packages.`);
481
+ }
482
+ };
483
+ var ServeCommand = class extends Command {
484
+ static {
485
+ __name(this, "ServeCommand");
486
+ }
487
+ /**
488
+ * The name and signature of the console command.
489
+ *
490
+ * @var string
491
+ */
492
+ signature = "serve";
493
+ /**
494
+ * The console command description.
495
+ *
496
+ * @var string
497
+ */
498
+ description = "Start the Developement Server";
499
+ async handle() {
500
+ try {
501
+ await this.serve();
502
+ } catch (e) {
503
+ this.kernel.output.error(e);
504
+ }
505
+ }
506
+ async serve() {
507
+ const child = spawn("tsup-node", {
508
+ stdio: "inherit",
509
+ shell: true,
510
+ env: Object.assign({}, process.env, {
511
+ NODE_ENV: "development"
512
+ }),
513
+ detached: true
514
+ });
515
+ const cleanup = /* @__PURE__ */ __name(() => {
516
+ console.log(111);
517
+ if (child.pid) {
518
+ process.kill(child.pid, "SIGTERM");
519
+ }
520
+ }, "cleanup");
521
+ process.on("SIGINT", () => child.kill("SIGINT"));
522
+ process.on("SIGTERM", () => child.kill("SIGTERM"));
523
+ process.on("SIGINT", () => {
524
+ cleanup();
525
+ process.exit(0);
526
+ });
527
+ process.on("SIGTERM", () => {
528
+ cleanup();
529
+ process.exit(0);
530
+ });
531
+ }
532
+ };
533
+
534
+ // src/Signature.ts
535
+ var Signature = class _Signature {
536
+ static {
537
+ __name(this, "Signature");
538
+ }
539
+ /**
540
+ * Helper to parse options inside a block of text
541
+ *
542
+ * @param block
543
+ * @returns
544
+ */
545
+ static parseOptions(block) {
546
+ const options = [];
547
+ const regex = /\{([^{}]+(?:\{[^{}]*\}[^{}]*)*)\}/g;
548
+ let match;
549
+ while ((match = regex.exec(block)) !== null) {
550
+ const shared = "^" === match[1][0] || /:[#^]/.test(match[1]);
551
+ const isHidden = ([
552
+ "#",
553
+ "^"
554
+ ].includes(match[1][0]) || /:[#^]/.test(match[1])) && !shared;
555
+ const content = match[1].trim().replace(/[#^]/, "");
556
+ const colonIndex = content.indexOf(":");
557
+ if (colonIndex === -1) {
558
+ options.push({
559
+ name: content
560
+ });
561
+ continue;
562
+ }
563
+ const namePart = content.substring(0, colonIndex).trim();
564
+ let rest = content.substring(colonIndex + 1).trim();
565
+ let description = rest;
566
+ let nestedOptions;
567
+ const pipeIndex = rest.indexOf("|");
568
+ if (pipeIndex !== -1) {
569
+ description = rest.substring(0, pipeIndex).trim();
570
+ const nestedText = rest.substring(pipeIndex + 1).trim();
571
+ const cleanedNestedText = nestedText.replace(/^\{/, "").trim();
572
+ nestedOptions = _Signature.parseOptions("{" + cleanedNestedText + "}");
573
+ } else {
574
+ description = description.trim();
575
+ }
576
+ let name = namePart;
577
+ let required = /[^a-zA-Z0-9_|-]/.test(name);
578
+ let multiple = false;
579
+ if (name.endsWith("?*")) {
580
+ required = false;
581
+ multiple = true;
582
+ name = name.slice(0, -2);
583
+ } else if (name.endsWith("*")) {
584
+ multiple = true;
585
+ name = name.slice(0, -1);
586
+ } else if (name.endsWith("?")) {
587
+ required = false;
588
+ name = name.slice(0, -1);
589
+ }
590
+ const isFlag = name.startsWith("--");
591
+ let flags;
592
+ let defaultValue;
593
+ if (isFlag) {
594
+ const flagParts = name.split("|").map((s) => s.trim());
595
+ flags = [];
596
+ for (let part of flagParts) {
597
+ if (part.startsWith("--") && part.slice(2).length === 1) {
598
+ part = "-" + part.slice(2);
599
+ } else if (part.startsWith("-") && !part.startsWith("--") && part.slice(1).length > 1) {
600
+ part = "--" + part.slice(1);
601
+ } else if (!part.startsWith("-") && part.slice(1).length > 1) {
602
+ part = "--" + part;
603
+ }
604
+ const eqIndex = part.indexOf("=");
605
+ if (eqIndex !== -1) {
606
+ flags.push(part.substring(0, eqIndex));
607
+ const val = part.substring(eqIndex + 1);
608
+ if (val === "*") {
609
+ defaultValue = [];
610
+ } else if (val === "true" || val === "false" || !val && !required) {
611
+ defaultValue = val === "true";
612
+ } else if (!isNaN(Number(val))) {
613
+ defaultValue = Number(val);
614
+ } else {
615
+ defaultValue = val;
616
+ }
617
+ } else {
618
+ flags.push(part);
619
+ }
620
+ }
621
+ }
622
+ options.push({
623
+ name: isFlag ? flags[flags.length - 1] : name,
624
+ required,
625
+ multiple,
626
+ description,
627
+ flags,
628
+ shared,
629
+ isFlag,
630
+ isHidden,
631
+ defaultValue,
632
+ nestedOptions
633
+ });
634
+ }
635
+ return options;
636
+ }
637
+ /**
638
+ * Helper to parse a command's signature
639
+ *
640
+ * @param signature
641
+ * @param commandClass
642
+ * @returns
643
+ */
644
+ static parseSignature(signature, commandClass) {
645
+ const lines = signature.split("\n").map((l) => l.trim()).filter((l) => l.length > 0);
646
+ const isHidden = [
647
+ "#",
648
+ "^"
649
+ ].includes(lines[0][0]) || /:[#^]/.test(lines[0]);
650
+ const baseCommand = lines[0].replace(/[^\w=:-]/g, "");
651
+ const description = commandClass.getDescription();
652
+ const isNamespaceCommand = baseCommand.endsWith(":");
653
+ const rest = lines.slice(1).join(" ");
654
+ const allOptions = _Signature.parseOptions(rest);
655
+ if (isNamespaceCommand) {
656
+ return {
657
+ baseCommand: baseCommand.slice(0, -1),
658
+ isNamespaceCommand,
659
+ subCommands: allOptions.filter((e) => !e.flags && !e.isHidden),
660
+ description,
661
+ commandClass,
662
+ options: allOptions.filter((e) => !!e.flags),
663
+ isHidden
664
+ };
665
+ } else {
666
+ return {
667
+ baseCommand,
668
+ isNamespaceCommand,
669
+ options: allOptions,
670
+ description,
671
+ commandClass,
672
+ isHidden
673
+ };
674
+ }
675
+ }
676
+ };
677
+ var Musket = class _Musket {
678
+ static {
679
+ __name(this, "Musket");
680
+ }
681
+ app;
682
+ kernel;
683
+ output = Utils.output();
684
+ commands = [];
685
+ constructor(app, kernel) {
686
+ this.app = app;
687
+ this.kernel = kernel;
688
+ }
689
+ async build() {
690
+ this.loadBaseCommands();
691
+ await this.loadDiscoveredCommands();
692
+ return this.initialize();
693
+ }
694
+ loadBaseCommands() {
695
+ const commands = [
696
+ new ServeCommand(this.app, this.kernel),
697
+ new MakeCommand(this.app, this.kernel),
698
+ new MigrateCommand(this.app, this.kernel)
699
+ ];
700
+ commands.forEach((e) => this.addCommand(e));
701
+ }
702
+ async loadDiscoveredCommands() {
703
+ const commands = [];
704
+ commands.forEach((e) => this.addCommand(e));
705
+ }
706
+ addCommand(command) {
707
+ this.commands.push(Signature.parseSignature(command.getSignature(), command));
708
+ }
709
+ initialize() {
710
+ const cliVersion = [
711
+ "H3ravel Version:",
712
+ chalk.green(this.kernel.consolePackage.version)
713
+ ].join(" ");
714
+ const localVersion = [
715
+ "Musket Version:",
716
+ chalk.green(this.kernel.modulePackage.version || "None")
717
+ ].join(" ");
718
+ program.name("musket").version(`${cliVersion}
719
+ ${localVersion}`);
720
+ program.command("init").description("Initialize H3ravel.").action(async () => {
721
+ this.output.success(`Initialized: H3ravel has been initialized!`);
722
+ });
723
+ for (let i = 0; i < this.commands.length; i++) {
724
+ const command = this.commands[i];
725
+ const instance = command.commandClass;
726
+ if (command.isNamespaceCommand && command.subCommands) {
727
+ const cmd = command.isHidden ? program : program.command(command.baseCommand).description(command.description ?? "").action(async () => {
728
+ instance.setInput(cmd.opts(), cmd.args, cmd.registeredArguments, command);
729
+ await instance.handle();
730
+ });
731
+ if ((command.options?.length ?? 0) > 0) {
732
+ command.options?.filter((v, i2, a) => a.findIndex((t) => t.name === v.name) === i2).forEach((opt) => {
733
+ this.makeOption(opt, cmd);
734
+ });
735
+ }
736
+ command.subCommands.filter((v, i2, a) => !v.shared && a.findIndex((t) => t.name === v.name) === i2).forEach((sub) => {
737
+ const cmd2 = program.command(`${command.baseCommand}:${sub.name}`).description(sub.description || "").action(async () => {
738
+ instance.setInput(cmd2.opts(), cmd2.args, cmd2.registeredArguments, sub);
739
+ await instance.handle();
740
+ });
741
+ command.subCommands?.filter((e) => e.shared).forEach((opt) => {
742
+ this.makeOption(opt, cmd2, false, sub);
743
+ });
744
+ command.options?.filter((e) => e.shared).forEach((opt) => {
745
+ this.makeOption(opt, cmd2, false, sub);
746
+ });
747
+ if (sub.nestedOptions) {
748
+ sub.nestedOptions.filter((v, i2, a) => a.findIndex((t) => t.name === v.name) === i2).forEach((opt) => {
749
+ this.makeOption(opt, cmd2);
750
+ });
751
+ }
752
+ });
753
+ } else {
754
+ const cmd = program.command(command.baseCommand).description(command.description ?? "");
755
+ command?.options?.filter((v, i2, a) => a.findIndex((t) => t.name === v.name) === i2).forEach((opt) => {
756
+ this.makeOption(opt, cmd, true);
757
+ });
758
+ cmd.action(async () => {
759
+ instance.setInput(cmd.opts(), cmd.args, cmd.registeredArguments, command);
760
+ await instance.handle();
761
+ });
762
+ }
763
+ }
764
+ return program;
765
+ }
766
+ makeOption(opt, cmd, parse, parent) {
767
+ const description = opt.description?.replace(/\[(\w+)\]/g, (_, k) => parent?.[k] ?? `[${k}]`) ?? "";
768
+ const type = opt.name.replaceAll("-", "");
769
+ if (opt.isFlag) {
770
+ if (parse) {
771
+ const flags = opt.flags?.map((f) => f.length === 1 ? `-${f}` : `--${f}`).join(", ");
772
+ cmd.option(flags || "", description, String(opt.defaultValue) || void 0);
773
+ } else {
774
+ cmd.option(opt.flags?.join(", ") + (opt.required ? ` <${type}>` : ""), description, opt.defaultValue);
775
+ }
776
+ } else {
777
+ cmd.argument(opt.required ? `<${opt.name}>` : `[${opt.name}]`, description, opt.defaultValue);
778
+ }
779
+ }
780
+ static async parse(kernel) {
781
+ return (await new _Musket(kernel.app, kernel).build()).parseAsync();
782
+ }
783
+ };
784
+ var Kernel = class _Kernel {
785
+ static {
786
+ __name(this, "Kernel");
787
+ }
788
+ app;
789
+ cwd;
790
+ output = Utils.output();
791
+ basePath = "";
792
+ modulePath;
793
+ consolePath;
794
+ modulePackage;
795
+ consolePackage;
796
+ constructor(app, basePath) {
797
+ this.app = app;
798
+ }
799
+ static init(app) {
800
+ const instance = new _Kernel(app);
801
+ Promise.all([
802
+ instance.loadRequirements()
803
+ ]).then(([e]) => e.run());
804
+ }
805
+ async run() {
806
+ await Musket.parse(this);
807
+ process.exit(0);
808
+ }
809
+ async ensureDirectoryExists(dir) {
810
+ await mkdir(dir, {
811
+ recursive: true
812
+ });
813
+ }
814
+ async loadRequirements() {
815
+ this.cwd = nodepath.join(process.cwd(), this.basePath);
816
+ this.modulePath = Utils.findModulePkg("@h3ravel/core", this.cwd) ?? "";
817
+ this.consolePath = Utils.findModulePkg("@h3ravel/console", this.cwd) ?? "";
818
+ try {
819
+ this.modulePackage = await import(nodepath.join(this.modulePath, "package.json"));
820
+ } catch {
821
+ this.modulePackage = {
822
+ version: "N/A"
823
+ };
824
+ }
825
+ try {
826
+ this.consolePackage = await import(nodepath.join(this.consolePath, "package.json"));
827
+ } catch {
828
+ this.consolePackage = {
829
+ version: "N/A"
830
+ };
831
+ }
832
+ return this;
833
+ }
834
+ };
835
+ var ConsoleServiceProvider = class extends ServiceProvider {
836
+ static {
837
+ __name(this, "ConsoleServiceProvider");
838
+ }
839
+ static priority = 992;
840
+ register() {
841
+ Kernel.init(this.app);
842
+ }
843
+ };
844
+
845
+ // src/IO/providers.ts
846
+ var providers_default = [
847
+ ConfigServiceProvider,
848
+ DatabaseServiceProvider,
849
+ ConsoleServiceProvider
850
+ ];
851
+
852
+ // src/IO/app.ts
853
+ var app_default = class {
854
+ static {
855
+ __name(this, "default");
856
+ }
857
+ async bootstrap() {
858
+ const app = new Application(process.cwd());
859
+ app.registerProviders(providers_default);
860
+ await app.registerConfiguredProviders();
861
+ await app.boot();
862
+ new EventEmitter().once("SIGINT", () => process.exit(0));
863
+ process.on("SIGINT", () => {
864
+ process.exit(0);
865
+ });
866
+ process.on("SIGTERM", () => {
867
+ process.exit(0);
868
+ });
869
+ }
870
+ };
871
+
872
+ // src/run.ts
873
+ new app_default().bootstrap();
874
+ new EventEmitter().once("SIGINT", () => process.exit(0));