@forinda/kickjs 0.1.6 → 1.4.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js DELETED
@@ -1,1037 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- var __create = Object.create;
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getProtoOf = Object.getPrototypeOf;
8
- var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
19
- // If the importer is in node compatibility mode or this is not an ESM
20
- // file that has been converted to a CommonJS file using a Babel-
21
- // compatible transform (i.e. "__esModule" has not been set), then set
22
- // "default" to the CommonJS "module.exports" for node compatibility.
23
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
24
- mod
25
- ));
26
-
27
- // src/cli/cli.ts
28
- var import_commander = require("commander");
29
-
30
- // package.json
31
- var package_default = {
32
- name: "@forinda/kickjs",
33
- version: "0.1.6",
34
- description: "Express + TypeScript + Inversify starter with reactive state, request telemetry, and Spring Boot-style decorators.",
35
- main: "dist/index.js",
36
- types: "dist/index.d.ts",
37
- exports: {
38
- ".": {
39
- require: "./dist/index.js",
40
- types: "./dist/index.d.ts"
41
- }
42
- },
43
- files: [
44
- "dist",
45
- "LICENSE",
46
- "README.md"
47
- ],
48
- bin: {
49
- kick: "dist/cli.js"
50
- },
51
- scripts: {
52
- clean: "rm -rf dist",
53
- dev: "tsup --watch src/index.ts",
54
- check: "tsc --noEmit",
55
- build: "tsup",
56
- start: "node dist/index.js",
57
- prepublishOnly: "npm run build && npm run check && npm test",
58
- test: "vitest run",
59
- "test:watch": "vitest",
60
- prepare: "husky",
61
- prerelease: "npm run clean && npm run build && npm run check && npm test",
62
- "release:patch": "node scripts/release.js patch",
63
- "release:minor": "node scripts/release.js minor",
64
- "release:major": "node scripts/release.js major",
65
- "release:prerelease": "node scripts/release.js prerelease",
66
- "release:dry": "node scripts/release.js patch --dry-run",
67
- version: `git add package.json && git commit -m "chore: bump version to $(node -p "require('./package.json').version")"`
68
- },
69
- keywords: [
70
- "express",
71
- "typescript",
72
- "inversify",
73
- "decorators",
74
- "starter"
75
- ],
76
- author: "",
77
- license: "MIT",
78
- engines: {
79
- node: ">=20.0"
80
- },
81
- publishConfig: {
82
- access: "public"
83
- },
84
- dependencies: {
85
- commander: "^11.1.0"
86
- },
87
- peerDependencies: {
88
- express: "^5.1.0",
89
- inversify: "^7.10.0",
90
- "reflect-metadata": "^0.2.2"
91
- },
92
- devDependencies: {
93
- "@swc/core": "^1.7.28",
94
- "@types/express": "^5.0.3",
95
- "@types/node": "^24.5.2",
96
- "@types/supertest": "^6.0.3",
97
- "@vitest/coverage-v8": "^3.2.4",
98
- express: "^5.1.0",
99
- husky: "^9.1.7",
100
- inversify: "^7.10.0",
101
- joi: "^18.0.1",
102
- "node-mocks-http": "^1.17.2",
103
- "reflect-metadata": "^0.2.2",
104
- supertest: "^7.1.4",
105
- "ts-node": "^10.9.2",
106
- "ts-node-dev": "^2.0.0",
107
- tsup: "^8.5.0",
108
- tsx: "^4.20.6",
109
- typescript: "^5.9.2",
110
- vitest: "^3.2.4",
111
- zod: "^4.1.9"
112
- }
113
- };
114
-
115
- // src/cli/tasks/init-project.ts
116
- var import_node_path2 = __toESM(require("path"));
117
-
118
- // src/cli/utils/fs.ts
119
- var import_node_fs = require("fs");
120
- var import_node_path = __toESM(require("path"));
121
- async function ensureDirectory(target) {
122
- await import_node_fs.promises.mkdir(target, {
123
- recursive: true
124
- });
125
- }
126
- __name(ensureDirectory, "ensureDirectory");
127
- async function writeFileSafe(filePath, content, options = {}) {
128
- const { force = false } = options;
129
- try {
130
- if (!force) {
131
- await import_node_fs.promises.access(filePath);
132
- return false;
133
- }
134
- } catch (error) {
135
- }
136
- await ensureDirectory(import_node_path.default.dirname(filePath));
137
- await import_node_fs.promises.writeFile(filePath, content, "utf8");
138
- return true;
139
- }
140
- __name(writeFileSafe, "writeFileSafe");
141
- async function fileExists(filePath) {
142
- try {
143
- await import_node_fs.promises.access(filePath);
144
- return true;
145
- } catch (error) {
146
- return false;
147
- }
148
- }
149
- __name(fileExists, "fileExists");
150
- async function readJsonFile(filePath) {
151
- try {
152
- const raw = await import_node_fs.promises.readFile(filePath, "utf8");
153
- return JSON.parse(raw);
154
- } catch (error) {
155
- return void 0;
156
- }
157
- }
158
- __name(readJsonFile, "readJsonFile");
159
- async function writeJsonFile(filePath, data, options = {}) {
160
- await writeFileSafe(filePath, `${JSON.stringify(data, null, 2)}
161
- `, options);
162
- }
163
- __name(writeJsonFile, "writeJsonFile");
164
-
165
- // src/cli/tasks/init-project.ts
166
- async function initProject(options) {
167
- const targetDir = import_node_path2.default.resolve(process.cwd(), options.targetDirectory || ".");
168
- const force = options.force ?? false;
169
- const structure = normalizeStructure(options.structure);
170
- const createdFiles = [];
171
- const skippedFiles = [];
172
- await ensureDirectory(targetDir);
173
- const packageJsonPath = import_node_path2.default.join(targetDir, "package.json");
174
- const packageJson = await readJsonFile(packageJsonPath) ?? {};
175
- if (Object.keys(packageJson).length === 0) {
176
- const name = options.packageName ?? (import_node_path2.default.basename(targetDir).replace(/[^a-zA-Z0-9-_]/g, "-") || "kick-app");
177
- await writeJsonFile(packageJsonPath, {
178
- name,
179
- version: "0.1.0",
180
- private: true,
181
- type: "commonjs",
182
- scripts: {
183
- dev: "tsx watch src/main.ts",
184
- build: "tsup",
185
- start: "node dist/main.js",
186
- test: "vitest"
187
- },
188
- dependencies: {
189
- "@forinda/kickjs": "latest"
190
- },
191
- devDependencies: {
192
- typescript: "^5.4.0",
193
- tsx: "^4.7.0",
194
- tsup: "^8.0.0",
195
- vitest: "^3.0.0"
196
- }
197
- }, {
198
- force: true
199
- });
200
- createdFiles.push("package.json");
201
- } else {
202
- skippedFiles.push("package.json");
203
- }
204
- const tsconfigPath = import_node_path2.default.join(targetDir, "tsconfig.json");
205
- const tsconfigExists = await fileExists(tsconfigPath);
206
- if (!tsconfigExists || force) {
207
- await writeJsonFile(tsconfigPath, {
208
- compilerOptions: {
209
- target: "es2021",
210
- module: "commonjs",
211
- moduleResolution: "node",
212
- lib: [
213
- "es2021"
214
- ],
215
- rootDir: "src",
216
- outDir: "dist",
217
- strict: true,
218
- esModuleInterop: true,
219
- skipLibCheck: true,
220
- resolveJsonModule: true,
221
- experimentalDecorators: true,
222
- emitDecoratorMetadata: true
223
- },
224
- include: [
225
- "src"
226
- ]
227
- }, {
228
- force: true
229
- });
230
- createdFiles.push("tsconfig.json");
231
- } else {
232
- skippedFiles.push("tsconfig.json");
233
- }
234
- const mainFilePath = import_node_path2.default.join(targetDir, "src", "main.ts");
235
- const mainCreated = await writeFileSafe(mainFilePath, `import 'reflect-metadata';
236
- import { bootstrap, configureApp } from '@forinda/kickjs';
237
-
238
- configureApp({ prefix: '/api' });
239
-
240
- async function main() {
241
- const { shutdown } = await bootstrap({ port: process.env.PORT ?? 3000 });
242
- process.on('SIGINT', shutdown);
243
- process.on('SIGTERM', shutdown);
244
- }
245
-
246
- main().catch((error) => {
247
- console.error('Failed to bootstrap Kick app', error);
248
- process.exitCode = 1;
249
- });
250
- `, {
251
- force
252
- });
253
- mainCreated ? createdFiles.push("src/main.ts") : skippedFiles.push("src/main.ts");
254
- const domainBase = import_node_path2.default.join(targetDir, structure.domainRoot, structure.defaultDomain);
255
- for (const folder of structure.domainFolders) {
256
- const folderPath = import_node_path2.default.join(domainBase, folder);
257
- const exists = await fileExists(folderPath);
258
- await ensureDirectory(folderPath);
259
- const relativePath = import_node_path2.default.relative(targetDir, folderPath);
260
- if (exists) {
261
- skippedFiles.push(relativePath);
262
- } else {
263
- createdFiles.push(relativePath);
264
- }
265
- }
266
- const controllerFolder = structure.domainFolders.includes("controllers") ? "controllers" : structure.domainFolders[0];
267
- const controllerPath = import_node_path2.default.join(domainBase, controllerFolder, "hello.get.controller.ts");
268
- const controllerCreated = await writeFileSafe(controllerPath, `import type { Request, Response } from 'express';
269
- import { GetController } from '@forinda/kickjs';
270
-
271
- export default class HelloGetController extends GetController {
272
- handle(_req: Request, res: Response) {
273
- return this.ok(res, { message: 'Hello from Kick!' });
274
- }
275
- }
276
- `, {
277
- force
278
- });
279
- const relativeControllerPath = import_node_path2.default.relative(targetDir, controllerPath);
280
- controllerCreated ? createdFiles.push(relativeControllerPath) : skippedFiles.push(relativeControllerPath);
281
- const appConfigDir = import_node_path2.default.join(targetDir, "src", "config");
282
- await ensureDirectory(appConfigDir);
283
- const appConfigPath = import_node_path2.default.join(appConfigDir, "kick.config.ts");
284
- const appConfigCreated = await writeFileSafe(appConfigPath, buildAppConfigFile(structure), {
285
- force
286
- });
287
- const relativeAppConfig = import_node_path2.default.relative(targetDir, appConfigPath);
288
- appConfigCreated ? createdFiles.push(relativeAppConfig) : skippedFiles.push(relativeAppConfig);
289
- const configPath = import_node_path2.default.join(targetDir, "kick.config.ts");
290
- const configCreated = await writeFileSafe(configPath, buildConfigFile(structure), {
291
- force
292
- });
293
- configCreated ? createdFiles.push("kick.config.ts") : skippedFiles.push("kick.config.ts");
294
- return {
295
- createdFiles,
296
- skippedFiles
297
- };
298
- }
299
- __name(initProject, "initProject");
300
- function normalizeStructure(structure) {
301
- return {
302
- domainRoot: structure?.domainRoot ?? "src/domains",
303
- domainFolders: structure?.domainFolders && structure.domainFolders.length > 0 ? [
304
- ...structure.domainFolders
305
- ] : [
306
- "controllers",
307
- "services",
308
- "domain"
309
- ],
310
- defaultDomain: structure?.defaultDomain ?? "app"
311
- };
312
- }
313
- __name(normalizeStructure, "normalizeStructure");
314
- function buildConfigFile(structure) {
315
- const controllerRoot = `${structure.domainRoot}/${structure.defaultDomain}/controllers`;
316
- const structureSnippet = JSON.stringify(structure, null, 2).split("\n").map((line, index) => index === 0 ? line : ` ${line}`).join("\n");
317
- return `import type { KickConfig } from '@forinda/kickjs';
318
-
319
- const config: KickConfig = {
320
- structure: ${structureSnippet},
321
- generators: {
322
- controllerRoot: '${controllerRoot}'
323
- },
324
- commands: [
325
- {
326
- name: 'dev',
327
- description: 'Run the Kick dev server',
328
- steps: 'npm run dev'
329
- }
330
- ]
331
- };
332
-
333
- export default config;
334
- `;
335
- }
336
- __name(buildConfigFile, "buildConfigFile");
337
- function buildAppConfigFile(structure) {
338
- const controllerRoot = `${structure.domainRoot}/${structure.defaultDomain}/controllers`;
339
- const roots = [
340
- controllerRoot,
341
- "src/http"
342
- ].map((root) => `'${root}'`).join(", ");
343
- return `import { createKickConfig } from '@forinda/kickjs';
344
-
345
- export default createKickConfig({
346
- defaults: {
347
- prefix: '/api',
348
- api: {
349
- discovery: {
350
- roots: [${roots}]
351
- }
352
- }
353
- },
354
- env: {
355
- KICK_PREFIX: 'prefix',
356
- KICK_HEALTH: 'healthEndpoint',
357
- KICK_LOG_LEVEL: { path: 'logging.level' }
358
- }
359
- });
360
- `;
361
- }
362
- __name(buildAppConfigFile, "buildAppConfigFile");
363
-
364
- // src/cli/commands/init.ts
365
- function registerInitCommand(program, defaults = {}) {
366
- program.command("init [directory]").description("Scaffold a new Kick project in the target directory").option("-f, --force", "Overwrite existing files when scaffolding", false).option("-n, --name <packageName>", "Package name to use in package.json").action(async (directory, options) => {
367
- const targetDirectory = directory ?? ".";
368
- const result = await initProject({
369
- targetDirectory,
370
- force: options.force,
371
- packageName: options.name,
372
- structure: defaults.structure
373
- });
374
- if (result.createdFiles.length > 0) {
375
- console.log(`Created files:
376
- - ${result.createdFiles.join("\n - ")}`);
377
- }
378
- if (result.skippedFiles.length > 0) {
379
- console.log(`Skipped existing files:
380
- - ${result.skippedFiles.join("\n - ")}`);
381
- }
382
- console.log('Project scaffold complete. Run "npm install" to install dependencies.');
383
- });
384
- }
385
- __name(registerInitCommand, "registerInitCommand");
386
-
387
- // src/cli/tasks/generate-controller.ts
388
- var import_node_path3 = __toESM(require("path"));
389
- var SUPPORTED_METHODS = [
390
- "get",
391
- "post",
392
- "put",
393
- "patch",
394
- "delete"
395
- ];
396
- async function generateController(options) {
397
- const method = normalizeMethod(options.method);
398
- const root = options.root ?? "src/http";
399
- const rootPath = import_node_path3.default.isAbsolute(root) ? root : import_node_path3.default.join(process.cwd(), root);
400
- const normalizedName = options.name.replace(/\\/g, "/");
401
- const segments = normalizedName.split("/").filter(Boolean);
402
- const fileSegment = segments.pop() ?? "index";
403
- const relativeDir = segments.join("/");
404
- const fileName = `${fileSegment}.${method}.controller.ts`;
405
- const targetFile = import_node_path3.default.join(rootPath, relativeDir, fileName);
406
- const className = buildClassName([
407
- ...segments,
408
- fileSegment
409
- ], method);
410
- const methodController = `${capitalize(method)}Controller`;
411
- const template = buildTemplate({
412
- className,
413
- methodController,
414
- method,
415
- tags: options.tags
416
- });
417
- const created = await writeFileSafe(targetFile, template, {
418
- force: options.force
419
- });
420
- return {
421
- filePath: targetFile,
422
- created
423
- };
424
- }
425
- __name(generateController, "generateController");
426
- function normalizeMethod(raw) {
427
- const method = (raw ?? "get").toLowerCase();
428
- if (!SUPPORTED_METHODS.includes(method)) {
429
- throw new Error(`Unsupported method "${raw}". Supported methods: ${SUPPORTED_METHODS.join(", ")}`);
430
- }
431
- return method;
432
- }
433
- __name(normalizeMethod, "normalizeMethod");
434
- function buildTemplate(params) {
435
- const tagsBlock = params.tags && params.tags.length > 0 ? ` static tags = ${JSON.stringify(params.tags)};
436
-
437
- ` : "";
438
- const requestType = params.method === "get" || params.method === "delete" ? "Request" : "Request";
439
- return `import type { Request, Response } from 'express';
440
- import { ${params.methodController} } from '@forinda/kickjs';
441
-
442
- export default class ${params.className} extends ${params.methodController} {
443
- ${tagsBlock} handle(_req: ${requestType}, res: Response) {
444
- return this.ok(res, { message: '${humanize(params.method)} ${params.className}' });
445
- }
446
- }
447
- `;
448
- }
449
- __name(buildTemplate, "buildTemplate");
450
- function humanize(method) {
451
- return method.toUpperCase();
452
- }
453
- __name(humanize, "humanize");
454
- function buildClassName(segments, method) {
455
- const normalizedSegments = segments.map((segment) => segment.replace(/\.\.\./g, "Rest")).map((segment) => segment.replace(/\[(.+?)]/g, "$1")).flatMap((segment) => segment.split(/[^a-zA-Z0-9]+/g)).filter(Boolean).map(capitalize);
456
- if (normalizedSegments.length === 0) {
457
- normalizedSegments.push("Root");
458
- }
459
- normalizedSegments.push(capitalize(method), "Controller");
460
- return normalizedSegments.join("");
461
- }
462
- __name(buildClassName, "buildClassName");
463
- function capitalize(value) {
464
- return value.charAt(0).toUpperCase() + value.slice(1);
465
- }
466
- __name(capitalize, "capitalize");
467
-
468
- // src/cli/tasks/generate-domain.ts
469
- var import_node_path4 = __toESM(require("path"));
470
- async function generateDomain(options) {
471
- const structure = options.structure ?? {
472
- domainRoot: "src/domains",
473
- domainFolders: [
474
- "controllers",
475
- "services",
476
- "domain"
477
- ],
478
- defaultDomain: "app"
479
- };
480
- const domainRoot = structure.domainRoot ?? "src/domains";
481
- const domainRootBase = import_node_path4.default.isAbsolute(domainRoot) ? domainRoot : import_node_path4.default.join(process.cwd(), domainRoot);
482
- const folders = structure.domainFolders && structure.domainFolders.length > 0 ? structure.domainFolders : [
483
- "controllers"
484
- ];
485
- const targetRoot = import_node_path4.default.join(domainRootBase, options.name);
486
- const createdFolders = [];
487
- const existingFolders = [];
488
- for (const folder of folders) {
489
- const folderPath = import_node_path4.default.join(targetRoot, folder);
490
- const alreadyExists = await fileExists(folderPath);
491
- await ensureDirectory(folderPath);
492
- if (alreadyExists) {
493
- existingFolders.push(import_node_path4.default.relative(process.cwd(), folderPath));
494
- } else {
495
- createdFolders.push(import_node_path4.default.relative(process.cwd(), folderPath));
496
- }
497
- }
498
- let controllerPath;
499
- let controllerCreated;
500
- if (options.withController !== false && folders.includes("controllers")) {
501
- controllerPath = import_node_path4.default.join(targetRoot, "controllers", "index.get.controller.ts");
502
- controllerCreated = await writeFileSafe(controllerPath, `import type { Request, Response } from 'express';
503
- import { GetController } from '@forinda/kickjs';
504
-
505
- export default class ${capitalize2(options.name)}IndexGetController extends GetController {
506
- handle(_req: Request, res: Response) {
507
- return this.ok(res, { domain: '${options.name}', message: 'Hello from ${options.name}' });
508
- }
509
- }
510
- `, {
511
- force: options.force
512
- });
513
- if (controllerCreated) {
514
- createdFolders.push(import_node_path4.default.relative(process.cwd(), controllerPath));
515
- } else if (controllerPath) {
516
- existingFolders.push(import_node_path4.default.relative(process.cwd(), controllerPath));
517
- }
518
- }
519
- return {
520
- root: targetRoot,
521
- createdFolders,
522
- existingFolders,
523
- controllerPath,
524
- controllerCreated
525
- };
526
- }
527
- __name(generateDomain, "generateDomain");
528
- function capitalize2(value) {
529
- if (!value) {
530
- return "Domain";
531
- }
532
- return value.charAt(0).toUpperCase() + value.slice(1);
533
- }
534
- __name(capitalize2, "capitalize");
535
-
536
- // src/cli/commands/generate-controller.ts
537
- function registerGeneratorCommands(program, defaults = {}) {
538
- const generate = program.command("generate").description("Generate Kick resources");
539
- generate.command("domain <name>").description("Scaffold a domain folder with optional default files").option("-f, --force", "Overwrite existing generated files", false).option("--no-controller", "Do not create a default controller").action(async (name, options) => {
540
- const result = await generateDomain({
541
- name,
542
- structure: defaults.structure,
543
- force: options.force,
544
- withController: options.controller
545
- });
546
- console.log(`Domain root: ${result.root}`);
547
- if (result.createdFolders.length > 0) {
548
- console.log(`Created:
549
- - ${result.createdFolders.join("\n - ")}`);
550
- }
551
- if (result.existingFolders.length > 0) {
552
- console.log(`Existing:
553
- - ${result.existingFolders.join("\n - ")}`);
554
- }
555
- });
556
- generate.command("controller <name>").description("Generate a file-system discovered controller").option("-m, --method <verb>", "HTTP verb to use (get, post, put, patch, delete)", "get").option("-r, --root <path>", "Root directory for generated controllers", defaults.controllerRoot ?? "src/http").option("-f, --force", "Overwrite the controller if it already exists", false).option("--tags <tags>", "Comma separated tags to assign to the controller").action(async (name, options) => {
557
- const tags = options.tags ? options.tags.split(",").map((tag) => tag.trim()).filter(Boolean) : void 0;
558
- const defaultRoot = computeDefaultControllerRoot(defaults, name);
559
- const result = await generateController({
560
- name,
561
- method: options.method,
562
- root: options.root ?? defaultRoot,
563
- force: options.force,
564
- tags
565
- });
566
- if (result.created) {
567
- console.log(`Created controller at ${result.filePath}`);
568
- } else {
569
- console.log(`Controller already exists at ${result.filePath}`);
570
- }
571
- });
572
- }
573
- __name(registerGeneratorCommands, "registerGeneratorCommands");
574
- function computeDefaultControllerRoot(defaults, name) {
575
- if (defaults.controllerRoot) {
576
- return defaults.controllerRoot;
577
- }
578
- const structure = defaults.structure;
579
- if (!structure) {
580
- return "src/http";
581
- }
582
- const domainRoot = structure.domainRoot ?? "src/domains";
583
- const defaultDomain = structure.defaultDomain ?? "app";
584
- if (name.includes("/")) {
585
- const [maybeDomain] = name.split("/");
586
- return `${domainRoot}/${maybeDomain}/controllers`;
587
- }
588
- return `${domainRoot}/${defaultDomain}/controllers`;
589
- }
590
- __name(computeDefaultControllerRoot, "computeDefaultControllerRoot");
591
-
592
- // src/cli/commands/run.ts
593
- var import_node_child_process = require("child_process");
594
- var import_node_fs3 = require("fs");
595
- var import_node_path6 = __toESM(require("path"));
596
-
597
- // src/utils/errors.ts
598
- var AppError = class extends Error {
599
- static {
600
- __name(this, "AppError");
601
- }
602
- code;
603
- status;
604
- details;
605
- constructor(code, message, options = {}) {
606
- super(message);
607
- this.code = code;
608
- this.status = options.status;
609
- this.details = options.details;
610
- if (options.cause) {
611
- this.cause = options.cause;
612
- }
613
- this.name = "AppError";
614
- }
615
- };
616
- function createError(code, message, options = {}) {
617
- return new AppError(code, message, options);
618
- }
619
- __name(createError, "createError");
620
-
621
- // src/cli/utils/config-loader.ts
622
- var import_node_fs2 = require("fs");
623
- var import_node_path5 = __toESM(require("path"));
624
- var CONFIG_FILE_NAMES = [
625
- "kick.config.ts",
626
- "kick.config.js",
627
- "kick.config.mjs",
628
- "kickjs.config.ts",
629
- "kickjs.config.js",
630
- "kickjs.config.mjs"
631
- ];
632
- async function loadKickConfig(cwd) {
633
- const workingDir = cwd || process.cwd();
634
- for (const configFileName of CONFIG_FILE_NAMES) {
635
- const configPath = import_node_path5.default.resolve(workingDir, configFileName);
636
- if ((0, import_node_fs2.existsSync)(configPath)) {
637
- try {
638
- const configModule = await import(configPath);
639
- const config = configModule.default || configModule;
640
- return {
641
- ...config,
642
- configPath
643
- };
644
- } catch (error) {
645
- console.warn(`\u26A0\uFE0F Failed to load config from ${configPath}:`, error);
646
- }
647
- }
648
- }
649
- return getDefaultConfig();
650
- }
651
- __name(loadKickConfig, "loadKickConfig");
652
- function getDefaultConfig() {
653
- return {
654
- app: {
655
- name: "KickJS App",
656
- port: 3e3,
657
- host: "localhost",
658
- prefix: "",
659
- env: "development"
660
- },
661
- dev: {
662
- port: 3e3,
663
- host: "localhost",
664
- entry: "src/index.ts",
665
- watch: true,
666
- env: {
667
- NODE_ENV: "development"
668
- }
669
- },
670
- start: {
671
- port: 3e3,
672
- host: "0.0.0.0",
673
- entry: "dist/index.js",
674
- env: {
675
- NODE_ENV: "production"
676
- }
677
- },
678
- structure: {
679
- domainRoot: "src/domains",
680
- domainFolders: [
681
- "controllers",
682
- "services",
683
- "domain"
684
- ],
685
- defaultDomain: "app"
686
- },
687
- generators: {
688
- controllerRoot: "src/domains/app/controllers"
689
- }
690
- };
691
- }
692
- __name(getDefaultConfig, "getDefaultConfig");
693
- function mergeConfigWithOptions(config, cliOptions, command) {
694
- const baseConfig = command === "dev" ? config.dev : config.start;
695
- return {
696
- ...baseConfig,
697
- port: cliOptions.port ? parseInt(cliOptions.port) : baseConfig?.port,
698
- host: cliOptions.host || baseConfig?.host,
699
- entry: cliOptions.entry || baseConfig?.entry,
700
- env: {
701
- ...baseConfig?.env,
702
- ...cliOptions.env
703
- }
704
- };
705
- }
706
- __name(mergeConfigWithOptions, "mergeConfigWithOptions");
707
-
708
- // src/cli/commands/run.ts
709
- function registerRunCommands(program) {
710
- program.command("dev").description("Start the application in development mode with hot reload").option("-p, --port <port>", "Port to run the server on").option("-h, --host <host>", "Host to bind the server to").option("-e, --entry <entry>", "Entry file path").action(async (options) => {
711
- await runDev(options);
712
- });
713
- program.command("start").description("Start the application in production mode").option("-p, --port <port>", "Port to run the server on").option("-h, --host <host>", "Host to bind the server to").option("-e, --entry <entry>", "Entry file path").action(async (options) => {
714
- await runStart(options);
715
- });
716
- }
717
- __name(registerRunCommands, "registerRunCommands");
718
- async function runDev(options) {
719
- const kickConfig = await loadKickConfig();
720
- const config = mergeConfigWithOptions(kickConfig, options, "dev");
721
- const entryFile = config.entry;
722
- const cwd = process.cwd();
723
- const entryPath = import_node_path6.default.resolve(cwd, entryFile);
724
- if (!(0, import_node_fs3.existsSync)(entryPath)) {
725
- throw createError("ENTRY_FILE_NOT_FOUND", `Entry file not found: ${entryPath}`);
726
- }
727
- console.log(`\u{1F680} Starting development server...`);
728
- if (kickConfig.configPath) {
729
- console.log(`\u2699\uFE0F Config: ${import_node_path6.default.relative(cwd, kickConfig.configPath)}`);
730
- }
731
- console.log(`\u{1F4C1} Entry: ${entryFile}`);
732
- console.log(`\u{1F310} Port: ${config.port}`);
733
- console.log(`\u{1F3E0} Host: ${config.host}`);
734
- const runners = [
735
- {
736
- cmd: "tsx",
737
- args: [
738
- "watch",
739
- entryFile
740
- ]
741
- },
742
- {
743
- cmd: "ts-node-dev",
744
- args: [
745
- "--respawn",
746
- "--transpile-only",
747
- entryFile
748
- ]
749
- },
750
- {
751
- cmd: "ts-node",
752
- args: [
753
- entryFile
754
- ]
755
- }
756
- ];
757
- let runner = null;
758
- for (const r of runners) {
759
- if (await commandExists(r.cmd)) {
760
- runner = r;
761
- break;
762
- }
763
- }
764
- if (!runner) {
765
- throw createError("DEV_RUNNER_NOT_FOUND", "No development runner found. Please install one of: tsx, ts-node-dev, or ts-node\nnpm install --save-dev tsx\n# or\nnpm install --save-dev ts-node-dev\n# or\nnpm install --save-dev ts-node");
766
- }
767
- const env = {
768
- ...process.env,
769
- ...config.env,
770
- PORT: config.port?.toString(),
771
- HOST: config.host
772
- };
773
- console.log(`\u{1F527} Using runner: ${runner.cmd}`);
774
- const localBinPath = import_node_path6.default.resolve(cwd, "node_modules", ".bin", runner.cmd);
775
- const commandToRun = (0, import_node_fs3.existsSync)(localBinPath) ? localBinPath : runner.cmd;
776
- const child = (0, import_node_child_process.spawn)(commandToRun, runner.args, {
777
- stdio: "inherit",
778
- env,
779
- cwd
780
- });
781
- child.on("error", (error) => {
782
- console.error(`\u274C Failed to start development server: ${error.message}`);
783
- process.exit(1);
784
- });
785
- child.on("exit", (code) => {
786
- if (code !== 0) {
787
- console.error(`\u274C Development server exited with code ${code}`);
788
- process.exit(code || 1);
789
- }
790
- });
791
- process.on("SIGINT", () => {
792
- console.log("\n\u{1F6D1} Shutting down development server...");
793
- child.kill("SIGINT");
794
- });
795
- process.on("SIGTERM", () => {
796
- console.log("\n\u{1F6D1} Shutting down development server...");
797
- child.kill("SIGTERM");
798
- });
799
- }
800
- __name(runDev, "runDev");
801
- async function runStart(options) {
802
- const kickConfig = await loadKickConfig();
803
- const config = mergeConfigWithOptions(kickConfig, options, "start");
804
- const entryFile = config.entry;
805
- const cwd = process.cwd();
806
- const entryPath = import_node_path6.default.resolve(cwd, entryFile);
807
- if (!(0, import_node_fs3.existsSync)(entryPath)) {
808
- throw createError("ENTRY_FILE_NOT_FOUND", `Entry file not found: ${entryPath}
809
- Make sure to build your application first with: npm run build`);
810
- }
811
- console.log(`\u{1F680} Starting production server...`);
812
- if (kickConfig.configPath) {
813
- console.log(`\u2699\uFE0F Config: ${import_node_path6.default.relative(cwd, kickConfig.configPath)}`);
814
- }
815
- console.log(`\u{1F4C1} Entry: ${entryFile}`);
816
- console.log(`\u{1F310} Port: ${config.port}`);
817
- console.log(`\u{1F3E0} Host: ${config.host}`);
818
- const env = {
819
- ...process.env,
820
- ...config.env,
821
- PORT: config.port?.toString(),
822
- HOST: config.host
823
- };
824
- const child = (0, import_node_child_process.spawn)("node", [
825
- entryFile
826
- ], {
827
- stdio: "inherit",
828
- env,
829
- cwd
830
- });
831
- child.on("error", (error) => {
832
- console.error(`\u274C Failed to start production server: ${error.message}`);
833
- process.exit(1);
834
- });
835
- child.on("exit", (code) => {
836
- if (code !== 0) {
837
- console.error(`\u274C Production server exited with code ${code}`);
838
- process.exit(code || 1);
839
- }
840
- });
841
- process.on("SIGINT", () => {
842
- console.log("\n\u{1F6D1} Shutting down production server...");
843
- child.kill("SIGINT");
844
- });
845
- process.on("SIGTERM", () => {
846
- console.log("\n\u{1F6D1} Shutting down production server...");
847
- child.kill("SIGTERM");
848
- });
849
- }
850
- __name(runStart, "runStart");
851
- async function commandExists(command) {
852
- return new Promise((resolve) => {
853
- const localBinPath = import_node_path6.default.resolve(process.cwd(), "node_modules", ".bin", command);
854
- if ((0, import_node_fs3.existsSync)(localBinPath)) {
855
- resolve(true);
856
- return;
857
- }
858
- const child = (0, import_node_child_process.spawn)("which", [
859
- command
860
- ], {
861
- stdio: "ignore"
862
- });
863
- child.on("close", (code) => {
864
- resolve(code === 0);
865
- });
866
- child.on("error", () => {
867
- resolve(false);
868
- });
869
- });
870
- }
871
- __name(commandExists, "commandExists");
872
-
873
- // src/cli/config.ts
874
- var import_node_fs4 = require("fs");
875
- var import_node_path7 = __toESM(require("path"));
876
- var CONFIG_FILE_CANDIDATES = [
877
- "kick.config.ts",
878
- "kick.config.js",
879
- "kick.config.mjs",
880
- "kick.config.cjs",
881
- "kick.config.json"
882
- ];
883
- var tsNodeRegistered = false;
884
- async function loadKickConfig2(cwd = process.cwd()) {
885
- for (const file of CONFIG_FILE_CANDIDATES) {
886
- const absolute = import_node_path7.default.join(cwd, file);
887
- if (!(0, import_node_fs4.existsSync)(absolute)) {
888
- continue;
889
- }
890
- if (file.endsWith(".json")) {
891
- const raw = await import_node_fs4.promises.readFile(absolute, "utf8");
892
- return normalizeConfig(JSON.parse(raw));
893
- }
894
- if (file.endsWith(".ts")) {
895
- ensureTsNode();
896
- }
897
- const loaded = require(absolute);
898
- const config = loaded?.default ?? loaded;
899
- return normalizeConfig(config);
900
- }
901
- return void 0;
902
- }
903
- __name(loadKickConfig2, "loadKickConfig");
904
- function ensureTsNode() {
905
- if (tsNodeRegistered) {
906
- return;
907
- }
908
- try {
909
- require("ts-node/register");
910
- tsNodeRegistered = true;
911
- } catch (error) {
912
- throw createError("TS_NODE_REQUIRED", "Custom CLI config requires ts-node for TypeScript configuration files.");
913
- }
914
- }
915
- __name(ensureTsNode, "ensureTsNode");
916
- function normalizeConfig(raw) {
917
- if (!raw || typeof raw !== "object") {
918
- throw createError("INVALID_CLI_CONFIG", "kick.config must export an object");
919
- }
920
- const config = raw;
921
- const normalized = {};
922
- if (Array.isArray(config.commands)) {
923
- normalized.commands = config.commands.map((command) => {
924
- if (!command || typeof command !== "object") {
925
- throw createError("INVALID_CLI_COMMAND", "Command entries must be objects");
926
- }
927
- if (!command.name) {
928
- throw createError("INVALID_CLI_COMMAND", "Command entries must include a name");
929
- }
930
- return {
931
- name: command.name,
932
- description: command.description,
933
- steps: Array.isArray(command.steps) ? [
934
- ...command.steps
935
- ] : command.steps ? [
936
- command.steps
937
- ] : []
938
- };
939
- });
940
- }
941
- if (config.generators) {
942
- normalized.generators = {
943
- controllerRoot: config.generators.controllerRoot ?? void 0
944
- };
945
- }
946
- if (config.structure) {
947
- normalized.structure = normalizeStructureConfig(config.structure);
948
- }
949
- return normalized;
950
- }
951
- __name(normalizeConfig, "normalizeConfig");
952
- function normalizeStructureConfig(raw) {
953
- return {
954
- domainRoot: raw.domainRoot ?? "src/domains",
955
- domainFolders: Array.isArray(raw.domainFolders) && raw.domainFolders.length > 0 ? [
956
- ...raw.domainFolders
957
- ] : [
958
- "controllers",
959
- "services",
960
- "domain"
961
- ],
962
- defaultDomain: raw.defaultDomain ?? "app"
963
- };
964
- }
965
- __name(normalizeStructureConfig, "normalizeStructureConfig");
966
-
967
- // src/cli/utils/shell.ts
968
- var import_node_child_process2 = require("child_process");
969
- function runShellCommand(command, options = {}) {
970
- return new Promise((resolve, reject) => {
971
- const child = (0, import_node_child_process2.spawn)(command, {
972
- cwd: options.cwd,
973
- stdio: "inherit",
974
- shell: true
975
- });
976
- child.on("exit", (code) => {
977
- if (code === 0) {
978
- resolve();
979
- } else {
980
- reject(new Error(`Command failed with exit code ${code}: ${command}`));
981
- }
982
- });
983
- child.on("error", (error) => {
984
- reject(error);
985
- });
986
- });
987
- }
988
- __name(runShellCommand, "runShellCommand");
989
-
990
- // src/cli/commands/custom.ts
991
- function registerCustomCommands(program, config) {
992
- if (!config?.commands) {
993
- return;
994
- }
995
- config.commands.forEach((command) => {
996
- const cmd = program.command(command.name).description(command.description ?? "Custom command defined in kick.config");
997
- cmd.action(async () => {
998
- if (!command.steps || command.steps.length === 0) {
999
- console.warn(`No steps defined for command "${command.name}".`);
1000
- return;
1001
- }
1002
- for (const step of command.steps) {
1003
- await runShellCommand(step);
1004
- }
1005
- });
1006
- });
1007
- }
1008
- __name(registerCustomCommands, "registerCustomCommands");
1009
-
1010
- // src/cli/cli.ts
1011
- async function main() {
1012
- const program = new import_commander.Command();
1013
- program.name("kick").description("Kick project CLI").version(package_default.version ?? "0.0.0");
1014
- const config = await loadKickConfig2(process.cwd());
1015
- registerInitCommand(program, {
1016
- structure: config?.structure
1017
- });
1018
- registerGeneratorCommands(program, {
1019
- controllerRoot: config?.generators?.controllerRoot,
1020
- structure: config?.structure
1021
- });
1022
- registerRunCommands(program);
1023
- registerCustomCommands(program, config);
1024
- program.showHelpAfterError();
1025
- try {
1026
- await program.parseAsync(process.argv);
1027
- } catch (error) {
1028
- console.error(error instanceof Error ? error.message : error);
1029
- process.exitCode = 1;
1030
- }
1031
- }
1032
- __name(main, "main");
1033
- main().catch((error) => {
1034
- console.error(error instanceof Error ? error.message : error);
1035
- process.exitCode = 1;
1036
- });
1037
- //# sourceMappingURL=cli.js.map