UNPKG

@h3ravel/console

Version:

CLI utilities for scaffolding, running migrations, tasks and for H3ravel.

508 lines (498 loc) 16.8 kB
import { FileSystem, Logger, TaskManager } from "@h3ravel/shared"; import { Command, Kernel } from "@h3ravel/musket"; import { execa } from "execa"; import preferredPM from "preferred-pm"; import { copyFile, readFile, writeFile } from "fs/promises"; import crypto from "crypto"; import dotenv from "dotenv"; import { mkdir, readFile as readFile$1, rm, writeFile as writeFile$1 } from "node:fs/promises"; import { Str } from "@h3ravel/support"; import nodepath from "node:path"; import { ContainerResolver, ServiceProvider } from "@h3ravel/core"; import { existsSync } from "node:fs"; import { fork } from "child_process"; import { dirname, join, resolve } from "path"; //#region src/Commands/BuildCommand.ts var BuildCommand = class BuildCommand extends Command { /** * The name and signature of the console command. * * @var string */ signature = `build {--m|minify : Minify your bundle output} {--d|dev : Build for dev but don't watch for changes} `; /** * The console command description. * * @var string */ description = "Build the app for production"; async handle() { try { await this.fire(); } catch (e) { Logger.error(e); } } async fire() { const outDir$1 = this.option("dev") ? ".h3ravel/serve" : env("DIST_DIR", "dist"); const minify = this.option("minify"); const verbosity = this.getVerbosity(); const debug = verbosity > 0; this.newLine(); await BuildCommand.build({ outDir: outDir$1, minify, verbosity, debug, mute: false }); this.newLine(); } /** * build */ static async build({ debug, minify, mute, verbosity, outDir: outDir$1 } = { mute: false, debug: false, minify: false, verbosity: 0, outDir: "dist" }) { const pm = (await preferredPM(base_path()))?.name ?? "pnpm"; const ENV_VARS = { EXTENDED_DEBUG: debug ? "true" : "false", CLI_BUILD: "true", NODE_ENV: "production", DIST_DIR: outDir$1, DIST_MINIFY: minify, LOG_LEVEL: [ "silent", "info", "warn", "error" ][verbosity] }; const silent = ENV_VARS.LOG_LEVEL === "silent" ? "--silent" : null; if (mute) return await execa(pm, [ "tsdown", silent, "--config-loader", "unconfig", "-c", "tsdown.default.config.ts" ].filter((e) => e !== null), { stdout: "inherit", stderr: "inherit", cwd: base_path(), env: Object.assign({}, process.env, ENV_VARS) }); const type = outDir$1 === "dist" ? "Production" : "Development"; return await TaskManager.advancedTaskRunner([[`Creating ${type} Bundle`, "STARTED"], [`${type} Bundle Created`, "COMPLETED"]], async () => { await execa(pm, [ "tsdown", silent, "--config-loader", "unconfig", "-c", "tsdown.default.config.ts" ].filter((e) => e !== null), { stdout: "inherit", stderr: "inherit", cwd: base_path(), env: Object.assign({}, process.env, ENV_VARS) }); }); } }; //#endregion //#region src/Commands/KeyGenerateCommand.ts var KeyGenerateCommand = class extends Command { /** * The name and signature of the console command. * * @var string */ signature = `key:generate {--force: Force the operation to run when in production} {--show: Display the key instead of modifying files} `; /** * The console command description. * * @var string */ description = "Set the application key"; async handle() { const config$1 = { key: crypto.randomBytes(32).toString("base64"), envPath: base_path(".env"), egEnvPath: base_path(".env.example"), updated: false, show: this.option("show") }; this.newLine(); if (!await FileSystem.fileExists(config$1.envPath)) if (await FileSystem.fileExists(config$1.egEnvPath)) await copyFile(config$1.egEnvPath, config$1.envPath); else { this.error(".env file not found."); this.newLine(); process.exit(0); } let content = await readFile(config$1.envPath, "utf8"); const buf = Buffer.from(content); const env$2 = dotenv.parse(buf); if (config$1.show) { if (!env$2.APP_KEY || env$2.APP_KEY === "") { this.error("Application key not set."); this.newLine(); process.exit(0); } const [enc, key] = env$2.APP_KEY.split(":"); Logger.log([[enc, "yellow"], [key, "white"]], ":"); this.newLine(); process.exit(0); } else if (env$2.APP_ENV === "production" && !this.option("force")) { this.error("Application is currently in production, failed to set key."); this.newLine(); process.exit(1); } if (/^APP_KEY=.*$/m.test(content)) { config$1.updated = true; content = content.replace(/^APP_KEY=.*$/m, `APP_KEY=base64:${config$1.key}`); } else { config$1.updated = false; content = `APP_KEY=base64:${config$1.key}\n\n${content}`; } await writeFile(config$1.envPath, content, "utf8"); this.success("Application key set successfully."); this.newLine(); } }; //#endregion //#region src/Commands/MakeCommand.ts var MakeCommand = class extends Command { /** * The name and signature of the console command. * * @var string */ signature = `#make: {controller : Create a new controller class. | {--a|api : Exclude the create and edit methods from the controller} | {--m|model= : Generate a resource controller for the given model} | {--r|resource : Generate a resource controller class} | {--force : Create the controller even if it already exists} } {resource : Create a new resource. | {--c|collection : Create a resource collection} | {--force : Create the resource even if it already exists} } {command : Create a new Musket command. | {--command : The terminal command that will be used to invoke the class} | {--force : Create the class even if the console command already exists} } {view : Create a new view. | {--force : Create the view even if it already exists} } {^name : The name of the [name] to generate} `; /** * The console command description. * * @var string */ description = "Generate component classes"; async handle() { const command = this.dictionary.baseCommand ?? this.dictionary.name; if (!this.argument("name")) this.program.error("Please provide a valid name for the " + command); await this[{ controller: "makeController", resource: "makeResource", view: "makeView", command: "makeCommand" }[command]](); } /** * Create a new controller class. */ async makeController() { const type = this.option("api") ? "-resource" : ""; const name = this.argument("name"); const force = this.option("force"); const crtlrPath = FileSystem.findModulePkg("@h3ravel/http", this.kernel.cwd) ?? ""; const stubPath = nodepath.join(crtlrPath, `dist/stubs/controller${type}.stub`); const path = app_path(`Http/Controllers/${name}.ts`); /** The Controller is scoped to a path make sure to create the associated directories */ if (name.includes("/")) await mkdir(Str.beforeLast(path, "/"), { recursive: true }); /** Check if the controller already exists */ if (!force && await FileSystem.fileExists(path)) Logger.error(`ERORR: ${name} controller already exists`); let stub = await readFile$1(stubPath, "utf-8"); stub = stub.replace(/{{ name }}/g, name); await writeFile$1(path, stub); Logger.split("INFO: Controller Created", Logger.log(nodepath.basename(path), "gray", false)); } makeResource() { Logger.success("Resource support is not yet available"); } /** * Create a new Musket command */ makeCommand() { Logger.success("Musket command creation is not yet available"); } /** * Create a new view. */ async makeView() { const name = this.argument("name"); const force = this.option("force"); const path = base_path(`src/resources/views/${name}.edge`); /** The view is scoped to a path make sure to create the associated directories */ if (name.includes("/")) await mkdir(Str.beforeLast(path, "/"), { recursive: true }); /** Check if the view already exists */ if (!force && await FileSystem.fileExists(path)) Logger.error(`ERORR: ${name} view already exists`); await writeFile$1(path, `{{-- src/resources/views/${name}.edge --}}`); Logger.split("INFO: View Created", Logger.log(`src/resources/views/${name}.edge`, "gray", false)); } }; //#endregion //#region src/Commands/PostinstallCommand.ts var PostinstallCommand = class extends Command { /** * The name and signature of the console command. * * @var string */ signature = "postinstall"; /** * The console command description. * * @var string */ description = "Default post installation command"; async handle() { this.genEncryptionKey(); this.createSqliteDB(); } /** * Create sqlite database if none exist * * @returns */ async genEncryptionKey() { new KeyGenerateCommand(this.app, this.kernel).setProgram(this.program).setOption("force", true).setOption("silent", true).setOption("quiet", true).setInput({ force: true, silent: true, quiet: true }, [], [], {}, this.program).handle(); } /** * Create sqlite database if none exist * * @returns */ async createSqliteDB() { if (config("database.default") !== "sqlite") return; if (!await FileSystem.fileExists(database_path())) await mkdir(database_path(), { recursive: true }); if (!await FileSystem.fileExists(database_path("db.sqlite"))) await writeFile$1(database_path("db.sqlite"), ""); } }; //#endregion //#region src/logo.ts const logo = String.raw` 111 111111111 1111111111 111111 111111 111 111111 111111 111 111111 11111 111 11111 1111111 111 1111111 111 11111 111 111111 111 1111 1111 11111111 1111 111 11111 1111 111111 111 1111 1111 1111 11111 1111 111 11111 11111 111 1111 1111 111111111111 111111111111 1111 1111111 1111 111 111111 1111 111 111111111111 111111 11111 1111 111 1111 11111111 1111 1111 111 111 11111111 111 1101 1101 111111111 11111111 1111 1111111111111111101 111 1111111111111111 1111 111 1111 1111 111 11111011 1111 111 1111111 1101 1111 111 11111 1110111111111111 111 1111 1111 1111111101 1111 111111111 1111011 111111111 1111 1111111 111110111110 111 1111 1111 111111 1111 11011101 10111 11111 1111 11011 111111 11 11111 111111 11101 111111 111111 111 111111 111111 111 111111 111111111 110 `; const altLogo = String.raw` _ _ _____ _ | | | |___ / _ __ __ ___ _____| | | |_| | |_ \| '__/ _ \ \ / / _ \ | | _ |___) | | | (_| |\ V / __/ | |_| |_|____/|_| \__,_| \_/ \___|_| `; //#endregion //#region ../../node_modules/.pnpm/@rollup+plugin-run@3.1.0_rollup@4.52.5/node_modules/@rollup/plugin-run/dist/es/index.js function run(opts = {}) { let input; let proc; const args = opts.args || []; const allowRestarts = opts.allowRestarts || false; const overrideInput = opts.input; const forkOptions = opts.options || opts; delete forkOptions.args; delete forkOptions.allowRestarts; return { name: "run", buildStart(options) { let inputs = overrideInput !== null && overrideInput !== void 0 ? overrideInput : options.input; if (typeof inputs === "string") inputs = [inputs]; if (typeof inputs === "object") inputs = Object.values(inputs); if (inputs.length > 1) throw new Error(`@rollup/plugin-run must have a single entry point; consider setting the \`input\` option`); input = resolve(inputs[0]); }, generateBundle(_outputOptions, _bundle, isWrite) { if (!isWrite) this.error(`@rollup/plugin-run currently only works with bundles that are written to disk`); }, writeBundle(outputOptions, bundle) { const forkBundle = (dir$1, entryFileName$1) => { if (proc) proc.kill(); proc = fork(join(dir$1, entryFileName$1), args, forkOptions); }; const dir = outputOptions.dir || dirname(outputOptions.file); const entryFileName = Object.keys(bundle).find((fileName) => { const chunk = bundle[fileName]; return chunk.isEntry && chunk.facadeModuleId === input; }); if (entryFileName) { forkBundle(dir, entryFileName); if (allowRestarts) { process.stdin.resume(); process.stdin.setEncoding("utf8"); process.stdin.on("data", (data) => { const line = data.toString().trim().toLowerCase(); if (line === "rs" || line === "restart" || data.toString().charCodeAt(0) === 11) forkBundle(dir, entryFileName); else if (line === "cls" || line === "clear" || data.toString().charCodeAt(0) === 12) console.clear(); }); } } else this.error(`@rollup/plugin-run could not find output chunk`); } }; } //#endregion //#region src/TsdownConfig.ts const env$1 = process.env.NODE_ENV || "development"; let outDir = env$1 === "development" ? ".h3ravel/serve" : "dist"; if (process.env.DIST_DIR) outDir = process.env.DIST_DIR; const TsDownConfig = { outDir, outExtensions: (e) => { return { js: e.format === "es" ? ".js" : ".cjs", dts: ".d.ts" }; }, entry: ["src/**/*.ts"], format: ["esm"], target: "node22", sourcemap: env$1 === "development", minify: !!process.env.DIST_MINIFY, external: [/^@h3ravel\/.*/gi], clean: true, shims: true, copy: [ { from: "public", to: outDir }, "src/resources", "src/database" ], env: env$1 === "development" ? { NODE_ENV: env$1, DIST_DIR: outDir } : {}, watch: env$1 === "development" && process.env.CLI_BUILD !== "true" ? [ ".env", ".env.*", "src", "../../packages" ] : false, dts: false, logLevel: "silent", nodeProtocol: true, skipNodeModulesBundle: true, hooks(e) { e.hook("build:done", async () => { const paths = [ "database/migrations", "database/factories", "database/seeders" ]; for (let i = 0; i < paths.length; i++) { const name = paths[i]; if (existsSync(nodepath.join(outDir, name))) await rm(nodepath.join(outDir, name), { recursive: true }); } }); }, plugins: env$1 === "development" && process.env.CLI_BUILD !== "true" ? [run({ env: Object.assign({}, process.env, { NODE_ENV: env$1, DIST_DIR: outDir }), execArgv: ["-r", "source-map-support/register"], allowRestarts: false, input: process.cwd() + "/src/server.ts" })] : [] }; var TsdownConfig_default = TsDownConfig; //#endregion //#region src/Providers/ConsoleServiceProvider.ts /** * Handles CLI commands and tooling. * * Auto-Registered when in CLI mode */ var ConsoleServiceProvider = class extends ServiceProvider { static priority = 992; /** * Indicate that this service provider only runs in console */ static runsInConsole = true; runsInConsole = true; register() { const DIST_DIR = `/${env("DIST_DIR", ".h3ravel/serve")}/`.replaceAll("//", ""); const baseCommands = [ BuildCommand, MakeCommand, PostinstallCommand, KeyGenerateCommand ]; Kernel.init(this.app, { logo: altLogo, resolver: new ContainerResolver(this.app).resolveMethodParams, tsDownConfig: TsdownConfig_default, baseCommands, packages: [{ name: "@h3ravel/core", alias: "H3ravel Framework" }, { name: "@h3ravel/musket", alias: "Musket CLI" }], cliName: "musket", hideMusketInfo: true, discoveryPaths: [app_path("Console/Commands/*.js").replace("/src/", DIST_DIR)] }); [ "SIGINT", "SIGTERM", "SIGTSTP" ].forEach((sig) => process.on(sig, () => { process.exit(0); })); } }; //#endregion export { BuildCommand, ConsoleServiceProvider, KeyGenerateCommand, MakeCommand, PostinstallCommand, TsDownConfig }; //# sourceMappingURL=index.js.map