@oxog/dockcraft 1.0.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.
@@ -0,0 +1,2065 @@
1
+ /**
2
+ * @oxog/dockcraft - Zero-Dependency NPM Package
3
+ * GitHub: https://github.com/ersinkoc/dockcraft
4
+ * License: MIT
5
+ */
6
+
7
+ // src/cli/parser.ts
8
+ function parseArgs(args) {
9
+ const result = {
10
+ command: "",
11
+ flags: /* @__PURE__ */ new Set(),
12
+ options: /* @__PURE__ */ new Map(),
13
+ positionals: []
14
+ };
15
+ let i = 0;
16
+ while (i < args.length) {
17
+ const arg = args[i];
18
+ if (!arg) {
19
+ i++;
20
+ continue;
21
+ }
22
+ if (arg.startsWith("--")) {
23
+ const name = arg.slice(2);
24
+ if (name.includes("=")) {
25
+ const parts = name.split("=");
26
+ const key = parts[0];
27
+ const value = parts.slice(1).join("=");
28
+ if (key) result.options.set(key, value);
29
+ } else {
30
+ const nextIndex = i + 1;
31
+ if (nextIndex < args.length) {
32
+ const nextArg = args[nextIndex];
33
+ if (nextArg && !nextArg.startsWith("-")) {
34
+ result.options.set(name, nextArg);
35
+ i++;
36
+ } else {
37
+ result.flags.add(name);
38
+ }
39
+ } else {
40
+ result.flags.add(name);
41
+ }
42
+ }
43
+ } else if (arg.startsWith("-")) {
44
+ const shorts = arg.slice(1);
45
+ if (shorts.length === 1) {
46
+ const nextIndex = i + 1;
47
+ if (nextIndex < args.length) {
48
+ const nextArg = args[nextIndex];
49
+ if (nextArg && !nextArg.startsWith("-")) {
50
+ result.options.set(shorts, nextArg);
51
+ i++;
52
+ } else {
53
+ result.flags.add(shorts);
54
+ }
55
+ } else {
56
+ result.flags.add(shorts);
57
+ }
58
+ } else {
59
+ for (const s of shorts) {
60
+ result.flags.add(s);
61
+ }
62
+ }
63
+ } else if (!result.command) {
64
+ result.command = arg;
65
+ } else {
66
+ result.positionals.push(arg);
67
+ }
68
+ i++;
69
+ }
70
+ return result;
71
+ }
72
+ function hasFlag(args, flag) {
73
+ if (args.flags.has(flag)) return true;
74
+ const firstChar = flag[0];
75
+ return firstChar !== void 0 && args.flags.has(firstChar);
76
+ }
77
+ function getOption(args, option, defaultValue = "") {
78
+ const value = args.options.get(option);
79
+ if (value !== void 0) return value;
80
+ const firstChar = option[0];
81
+ if (firstChar !== void 0) {
82
+ const shortValue = args.options.get(firstChar);
83
+ if (shortValue !== void 0) return shortValue;
84
+ }
85
+ return defaultValue;
86
+ }
87
+ function getBooleanFlag(args, flag) {
88
+ return hasFlag(args, flag) || getOption(args, flag, "") === "true";
89
+ }
90
+ function parseList(args, option) {
91
+ const value = getOption(args, option);
92
+ if (!value) return [];
93
+ return value.split(",").map((s) => s.trim()).filter(Boolean);
94
+ }
95
+
96
+ // src/cli/output.ts
97
+ var Colors = {
98
+ reset: "\x1B[0m",
99
+ bright: "\x1B[1m",
100
+ dim: "\x1B[2m",
101
+ black: "\x1B[30m",
102
+ red: "\x1B[31m",
103
+ green: "\x1B[32m",
104
+ yellow: "\x1B[33m",
105
+ blue: "\x1B[34m",
106
+ magenta: "\x1B[35m",
107
+ cyan: "\x1B[36m",
108
+ white: "\x1B[37m",
109
+ bgBlack: "\x1B[40m",
110
+ bgRed: "\x1B[41m",
111
+ bgGreen: "\x1B[42m",
112
+ bgYellow: "\x1B[43m",
113
+ bgBlue: "\x1B[44m"
114
+ };
115
+ function useColors() {
116
+ return process.env.NO_COLOR === void 0 && process.stdout.isTTY && process.env.TERM !== "dumb";
117
+ }
118
+ function color(text, colorCode) {
119
+ if (useColors()) {
120
+ return `${colorCode}${text}${Colors.reset}`;
121
+ }
122
+ return text;
123
+ }
124
+ function success(message) {
125
+ console.log(color("\u2713", Colors.green), color(message, Colors.bright));
126
+ }
127
+ function error(message) {
128
+ console.error(color("\u2717", Colors.red), color(message, Colors.bright));
129
+ }
130
+ function info(message) {
131
+ console.log(color("\u2139", Colors.blue), color(message, Colors.bright));
132
+ }
133
+ function title(message) {
134
+ console.log("");
135
+ console.log(color(message, Colors.bright));
136
+ console.log(color("=".repeat(message.length), Colors.dim));
137
+ }
138
+ function subtitle(message) {
139
+ console.log("");
140
+ console.log(color(message, Colors.bright));
141
+ }
142
+ function table(headers, rows) {
143
+ const widths = headers.map((h, i) => {
144
+ const maxRowWidth = rows.length > 0 ? Math.max(...rows.map((r) => (r[i] ?? "").length)) : 0;
145
+ return Math.max(h.length, maxRowWidth);
146
+ });
147
+ const headerRow = headers.map((h, i) => h.padEnd(widths[i] ?? 0)).join(" | ");
148
+ console.log(color(headerRow, Colors.bright));
149
+ const separator = widths.map((w) => "-".repeat(w ?? 0)).join("-+-");
150
+ console.log(color(separator, Colors.dim));
151
+ for (const row of rows) {
152
+ const rowStr = headers.map((_, i) => (row[i] ?? "").padEnd(widths[i] ?? 0)).join(" | ");
153
+ console.log(rowStr);
154
+ }
155
+ }
156
+ function json(data) {
157
+ console.log(JSON.stringify(data, null, 2));
158
+ }
159
+ function list(items) {
160
+ for (const item of items) {
161
+ console.log(` ${color("\u2022", Colors.cyan)} ${item}`);
162
+ }
163
+ }
164
+ function kv(pairs) {
165
+ const maxKeyLen = Math.max(...Object.keys(pairs).map((k) => k.length));
166
+ for (const [key, value] of Object.entries(pairs)) {
167
+ console.log(` ${color(key.padEnd(maxKeyLen), Colors.cyan)} : ${value}`);
168
+ }
169
+ }
170
+
171
+ // src/cli/prompts.ts
172
+ import { createInterface } from "readline";
173
+ async function prompt(question, defaultValue = "") {
174
+ if (process.argv.includes("-y") || process.argv.includes("--yes")) {
175
+ return defaultValue;
176
+ }
177
+ const rl = createInterface({
178
+ input: process.stdin,
179
+ output: process.stdout
180
+ });
181
+ const query = defaultValue ? `${question} (${defaultValue}): ` : `${question}: `;
182
+ return new Promise((resolve) => {
183
+ rl.question(query, (answer) => {
184
+ rl.close();
185
+ resolve(answer || defaultValue);
186
+ });
187
+ });
188
+ }
189
+ async function confirm(question) {
190
+ if (process.argv.includes("-y") || process.argv.includes("--yes")) {
191
+ return true;
192
+ }
193
+ const rl = createInterface({
194
+ input: process.stdin,
195
+ output: process.stdout
196
+ });
197
+ const query = `${question} (y/N): `;
198
+ return new Promise((resolve) => {
199
+ rl.question(query, (answer) => {
200
+ rl.close();
201
+ resolve(answer.toLowerCase() === "y" || answer.toLowerCase() === "yes");
202
+ });
203
+ });
204
+ }
205
+ async function select(question, options) {
206
+ if (process.argv.includes("-y") || process.argv.includes("--yes")) {
207
+ return options[0] ?? "";
208
+ }
209
+ const rl = createInterface({
210
+ input: process.stdin,
211
+ output: process.stdout
212
+ });
213
+ console.log("");
214
+ console.log(question);
215
+ for (let i = 0; i < options.length; i++) {
216
+ console.log(` ${i + 1}. ${options[i]}`);
217
+ }
218
+ console.log("");
219
+ return new Promise((resolve) => {
220
+ rl.question(`Select (1-${options.length}): `, (answer) => {
221
+ rl.close();
222
+ const index = parseInt(answer ?? "0", 10) - 1;
223
+ if (index >= 0 && index < options.length) {
224
+ resolve(options[index] ?? "");
225
+ } else {
226
+ resolve(options[0] ?? "");
227
+ }
228
+ });
229
+ });
230
+ }
231
+ async function multiselect(question, options) {
232
+ if (process.argv.includes("-y") || process.argv.includes("--yes")) {
233
+ return options;
234
+ }
235
+ const rl = createInterface({
236
+ input: process.stdin,
237
+ output: process.stdout
238
+ });
239
+ console.log("");
240
+ console.log(question);
241
+ console.log(" (comma-separated, e.g., 1,3,5)");
242
+ for (let i = 0; i < options.length; i++) {
243
+ console.log(` ${i + 1}. ${options[i]}`);
244
+ }
245
+ console.log("");
246
+ return new Promise((resolve) => {
247
+ rl.question(`Select (1-${options.length}): `, (answer) => {
248
+ rl.close();
249
+ const indices = (answer ?? "").split(",").map((s) => parseInt(s.trim(), 10) - 1);
250
+ const selected = indices.filter((i) => i >= 0 && i < options.length).map((i) => options[i]).filter((s) => s !== void 0);
251
+ resolve(selected.length > 0 ? selected : [options[0] ?? ""]);
252
+ });
253
+ });
254
+ }
255
+
256
+ // src/utils/fs.ts
257
+ import { promises as fs } from "fs";
258
+ import { join, dirname, basename, extname, relative } from "path";
259
+ async function ensureDir(path) {
260
+ try {
261
+ await fs.mkdir(path, { recursive: true });
262
+ } catch (error3) {
263
+ const err = error3;
264
+ if (err.code !== "EEXIST") {
265
+ throw error3;
266
+ }
267
+ }
268
+ }
269
+ async function writeFile(filePath, content) {
270
+ const dir = dirname(filePath);
271
+ await ensureDir(dir);
272
+ const tempPath = join(dir, `.${basename(filePath)}.tmp`);
273
+ try {
274
+ await fs.writeFile(tempPath, content, "utf8");
275
+ await fs.rename(tempPath, filePath);
276
+ } catch (error3) {
277
+ try {
278
+ await fs.unlink(tempPath);
279
+ } catch {
280
+ }
281
+ throw error3;
282
+ }
283
+ }
284
+ async function fileExists(filePath) {
285
+ try {
286
+ const stat = await fs.stat(filePath);
287
+ return stat.isFile();
288
+ } catch {
289
+ return false;
290
+ }
291
+ }
292
+
293
+ // src/presets/express-postgres.ts
294
+ var expressPostgresPreset = {
295
+ description: "Express application with PostgreSQL database",
296
+ app: {
297
+ port: 3e3,
298
+ node: "20-alpine",
299
+ workdir: "/app",
300
+ command: "npm start",
301
+ buildCommand: "npm run build",
302
+ multiStage: true,
303
+ healthcheck: "/health"
304
+ },
305
+ services: {
306
+ postgres: {
307
+ version: "16"
308
+ }
309
+ }
310
+ };
311
+
312
+ // src/presets/express-postgres-redis.ts
313
+ var expressPostgresRedisPreset = {
314
+ description: "Express application with PostgreSQL database and Redis cache",
315
+ app: {
316
+ port: 3e3,
317
+ node: "20-alpine",
318
+ workdir: "/app",
319
+ command: "npm start",
320
+ buildCommand: "npm run build",
321
+ multiStage: true,
322
+ healthcheck: "/health"
323
+ },
324
+ services: {
325
+ postgres: {
326
+ version: "16"
327
+ },
328
+ redis: {
329
+ version: "7-alpine"
330
+ }
331
+ }
332
+ };
333
+
334
+ // src/presets/express-mongo.ts
335
+ var expressMongoPreset = {
336
+ description: "Express application with MongoDB database",
337
+ app: {
338
+ port: 3e3,
339
+ node: "20-alpine",
340
+ workdir: "/app",
341
+ command: "npm start",
342
+ buildCommand: "npm run build",
343
+ multiStage: true,
344
+ healthcheck: "/health"
345
+ },
346
+ services: {
347
+ mongo: {
348
+ version: "7"
349
+ }
350
+ }
351
+ };
352
+
353
+ // src/presets/express-mongo-redis.ts
354
+ var expressMongoRedisPreset = {
355
+ description: "Express application with MongoDB database and Redis cache",
356
+ app: {
357
+ port: 3e3,
358
+ node: "20-alpine",
359
+ workdir: "/app",
360
+ command: "npm start",
361
+ buildCommand: "npm run build",
362
+ multiStage: true,
363
+ healthcheck: "/health"
364
+ },
365
+ services: {
366
+ mongo: {
367
+ version: "7"
368
+ },
369
+ redis: {
370
+ version: "7-alpine"
371
+ }
372
+ }
373
+ };
374
+
375
+ // src/presets/express-mysql.ts
376
+ var expressMysqlPreset = {
377
+ description: "Express application with MySQL database",
378
+ app: {
379
+ port: 3e3,
380
+ node: "20-alpine",
381
+ workdir: "/app",
382
+ command: "npm start",
383
+ buildCommand: "npm run build",
384
+ multiStage: true,
385
+ healthcheck: "/health"
386
+ },
387
+ services: {
388
+ mysql: {
389
+ version: "8"
390
+ }
391
+ }
392
+ };
393
+
394
+ // src/presets/express-mysql-redis.ts
395
+ var expressMysqlRedisPreset = {
396
+ description: "Express application with MySQL database and Redis cache",
397
+ app: {
398
+ port: 3e3,
399
+ node: "20-alpine",
400
+ workdir: "/app",
401
+ command: "npm start",
402
+ buildCommand: "npm run build",
403
+ multiStage: true,
404
+ healthcheck: "/health"
405
+ },
406
+ services: {
407
+ mysql: {
408
+ version: "8"
409
+ },
410
+ redis: {
411
+ version: "7-alpine"
412
+ }
413
+ }
414
+ };
415
+
416
+ // src/presets/fastify-postgres.ts
417
+ var fastifyPostgresPreset = {
418
+ description: "Fastify application with PostgreSQL database",
419
+ app: {
420
+ port: 3e3,
421
+ node: "20-alpine",
422
+ workdir: "/app",
423
+ command: "npm start",
424
+ buildCommand: "npm run build",
425
+ multiStage: true,
426
+ healthcheck: "/health"
427
+ },
428
+ services: {
429
+ postgres: {
430
+ version: "16"
431
+ }
432
+ }
433
+ };
434
+
435
+ // src/presets/fastify-postgres-redis.ts
436
+ var fastifyPostgresRedisPreset = {
437
+ description: "Fastify application with PostgreSQL database and Redis cache",
438
+ app: {
439
+ port: 3e3,
440
+ node: "20-alpine",
441
+ workdir: "/app",
442
+ command: "npm start",
443
+ buildCommand: "npm run build",
444
+ multiStage: true,
445
+ healthcheck: "/health"
446
+ },
447
+ services: {
448
+ postgres: {
449
+ version: "16"
450
+ },
451
+ redis: {
452
+ version: "7-alpine"
453
+ }
454
+ }
455
+ };
456
+
457
+ // src/presets/nest-postgres.ts
458
+ var nestPostgresPreset = {
459
+ description: "NestJS application with PostgreSQL database",
460
+ app: {
461
+ port: 3e3,
462
+ node: "20-alpine",
463
+ workdir: "/app",
464
+ command: "npm run start:prod",
465
+ buildCommand: "npm run build",
466
+ multiStage: true,
467
+ healthcheck: "/health"
468
+ },
469
+ services: {
470
+ postgres: {
471
+ version: "16"
472
+ }
473
+ }
474
+ };
475
+
476
+ // src/presets/nest-mongo.ts
477
+ var nestMongoPreset = {
478
+ description: "NestJS application with MongoDB database",
479
+ app: {
480
+ port: 3e3,
481
+ node: "20-alpine",
482
+ workdir: "/app",
483
+ command: "npm run start:prod",
484
+ buildCommand: "npm run build",
485
+ multiStage: true,
486
+ healthcheck: "/health"
487
+ },
488
+ services: {
489
+ mongo: {
490
+ version: "7"
491
+ }
492
+ }
493
+ };
494
+
495
+ // src/presets/node-minimal.ts
496
+ var nodeMinimalPreset = {
497
+ description: "Minimal Node.js application setup",
498
+ app: {
499
+ port: 3e3,
500
+ node: "20-alpine",
501
+ workdir: "/app",
502
+ command: "npm start",
503
+ multiStage: true
504
+ },
505
+ services: {}
506
+ };
507
+
508
+ // src/presets/index.ts
509
+ var presets = /* @__PURE__ */ new Map();
510
+ function registerPreset(name, config) {
511
+ presets.set(name, config);
512
+ }
513
+ function getPreset(name) {
514
+ return presets.get(name);
515
+ }
516
+ function listPresets() {
517
+ return Array.from(presets.keys());
518
+ }
519
+ registerPreset("express-postgres", expressPostgresPreset);
520
+ registerPreset("express-postgres-redis", expressPostgresRedisPreset);
521
+ registerPreset("express-mongo", expressMongoPreset);
522
+ registerPreset("express-mongo-redis", expressMongoRedisPreset);
523
+ registerPreset("express-mysql", expressMysqlPreset);
524
+ registerPreset("express-mysql-redis", expressMysqlRedisPreset);
525
+ registerPreset("fastify-postgres", fastifyPostgresPreset);
526
+ registerPreset("fastify-postgres-redis", fastifyPostgresRedisPreset);
527
+ registerPreset("nest-postgres", nestPostgresPreset);
528
+ registerPreset("nest-mongo", nestMongoPreset);
529
+ registerPreset("node-minimal", nodeMinimalPreset);
530
+
531
+ // src/cli/commands/init.ts
532
+ async function init(args) {
533
+ title("Dockcraft Init");
534
+ const name = getOption(args, "name") || await prompt("Project name");
535
+ const preset = getOption(args, "preset");
536
+ const servicesOption = getOption(args, "services");
537
+ const port = getOption(args, "port") || await prompt("App port", "3000");
538
+ const outputDir = getOption(args, "output") || await prompt("Output directory", "./");
539
+ const skipPrompts = getBooleanFlag(args, "yes");
540
+ info(`Creating config for "${name}"`);
541
+ let selectedPreset = preset;
542
+ if (!selectedPreset && !skipPrompts) {
543
+ const presets3 = listPresets();
544
+ const usePreset = await confirm("Use a preset?");
545
+ if (usePreset) {
546
+ const presetName = await select("Select preset:", presets3);
547
+ selectedPreset = presetName;
548
+ }
549
+ }
550
+ let selectedServices = [];
551
+ if (servicesOption) {
552
+ selectedServices = parseList(args, "services");
553
+ } else if (!skipPrompts && !selectedPreset) {
554
+ const availableServices = ["postgres", "mysql", "mongo", "redis"];
555
+ selectedServices = await multiselect("Select services:", availableServices);
556
+ }
557
+ const config = generateConfig(name, selectedPreset, selectedServices, port);
558
+ const configPath = `${outputDir}/dockcraft.config.ts`;
559
+ await writeFile(configPath, config);
560
+ success(`Config file created: ${configPath}`);
561
+ info('Run "dockcraft generate" to generate Docker files');
562
+ }
563
+ function generateConfig(name, preset, services2, port) {
564
+ let content = `import { dockcraft } from '@oxog/dockcraft';
565
+
566
+ `;
567
+ content += `await dockcraft({
568
+ `;
569
+ content += ` name: '${name}',
570
+ `;
571
+ if (preset) {
572
+ content += ` preset: '${preset}',
573
+ `;
574
+ }
575
+ content += ` app: {
576
+ `;
577
+ content += ` port: ${port},
578
+ `;
579
+ content += ` },
580
+ `;
581
+ if (services2.length > 0) {
582
+ content += ` services: {
583
+ `;
584
+ for (const service of services2) {
585
+ content += ` ${service}: {},
586
+ `;
587
+ }
588
+ content += ` },
589
+ `;
590
+ }
591
+ content += `});
592
+ `;
593
+ return content;
594
+ }
595
+
596
+ // src/services/postgres.ts
597
+ var postgresService = {
598
+ name: "postgres",
599
+ image: (version) => `postgres:${version}-alpine`,
600
+ defaultPort: 5432,
601
+ defaultVersion: "16",
602
+ env: {
603
+ POSTGRES_USER: "postgres",
604
+ POSTGRES_PASSWORD: "postgres",
605
+ POSTGRES_DB: "myapp"
606
+ },
607
+ volumes: ["postgres_data:/var/lib/postgresql/data"],
608
+ healthcheck: "pg_isready -U postgres",
609
+ ports: [],
610
+ connectionString: (config) => {
611
+ const user = config.env.POSTGRES_USER || "postgres";
612
+ const password = config.env.POSTGRES_PASSWORD || "postgres";
613
+ const database = config.env.POSTGRES_DB || "myapp";
614
+ const host = config.name;
615
+ const port = config.port;
616
+ return `postgres://${user}:${password}@${host}:${port}/${database}`;
617
+ }
618
+ };
619
+
620
+ // src/services/mysql.ts
621
+ var mysqlService = {
622
+ name: "mysql",
623
+ image: (version) => `mysql:${version}`,
624
+ defaultPort: 3306,
625
+ defaultVersion: "8",
626
+ env: {
627
+ MYSQL_ROOT_PASSWORD: "root",
628
+ MYSQL_DATABASE: "myapp",
629
+ MYSQL_USER: "mysql",
630
+ MYSQL_PASSWORD: "mysql"
631
+ },
632
+ volumes: ["mysql_data:/var/lib/mysql"],
633
+ healthcheck: "mysqladmin ping -h localhost",
634
+ ports: [],
635
+ connectionString: (config) => {
636
+ const user = config.env.MYSQL_USER || "root";
637
+ const password = config.env.MYSQL_PASSWORD || config.env.MYSQL_ROOT_PASSWORD || "root";
638
+ const database = config.env.MYSQL_DATABASE || "myapp";
639
+ const host = config.name;
640
+ const port = config.port;
641
+ return `mysql://${user}:${password}@${host}:${port}/${database}`;
642
+ }
643
+ };
644
+
645
+ // src/services/mongo.ts
646
+ var mongoService = {
647
+ name: "mongo",
648
+ image: (version) => `mongo:${version}`,
649
+ defaultPort: 27017,
650
+ defaultVersion: "7",
651
+ env: {
652
+ MONGO_INITDB_ROOT_USERNAME: "mongo",
653
+ MONGO_INITDB_ROOT_PASSWORD: "mongo",
654
+ MONGO_INITDB_DATABASE: "myapp"
655
+ },
656
+ volumes: ["mongo_data:/data/db"],
657
+ healthcheck: 'mongosh --eval "db.adminCommand({ ping: 1 })"',
658
+ ports: [],
659
+ connectionString: (config) => {
660
+ const user = config.env.MONGO_INITDB_ROOT_USERNAME || "mongo";
661
+ const password = config.env.MONGO_INITDB_ROOT_PASSWORD || "mongo";
662
+ const database = config.env.MONGO_INITDB_DATABASE || "myapp";
663
+ const host = config.name;
664
+ const port = config.port;
665
+ return `mongodb://${user}:${password}@${host}:${port}/${database}`;
666
+ }
667
+ };
668
+
669
+ // src/services/redis.ts
670
+ var redisService = {
671
+ name: "redis",
672
+ image: (version) => `redis:${version}-alpine`,
673
+ defaultPort: 6379,
674
+ defaultVersion: "7",
675
+ env: {},
676
+ volumes: ["redis_data:/data"],
677
+ healthcheck: "redis-cli ping",
678
+ ports: [],
679
+ connectionString: (config) => {
680
+ const host = config.name;
681
+ const port = config.port;
682
+ return `redis://${host}:${port}`;
683
+ }
684
+ };
685
+
686
+ // src/services/index.ts
687
+ var services = /* @__PURE__ */ new Map();
688
+ function registerService(def) {
689
+ services.set(def.name, def);
690
+ }
691
+ function getService(name) {
692
+ return services.get(name);
693
+ }
694
+ registerService(postgresService);
695
+ registerService(mysqlService);
696
+ registerService(mongoService);
697
+ registerService(redisService);
698
+
699
+ // src/utils/merge.ts
700
+ function deepMerge(...objects) {
701
+ const result = {};
702
+ for (const obj of objects) {
703
+ if (obj === null || typeof obj !== "object") continue;
704
+ for (const [key, value] of Object.entries(obj)) {
705
+ if (value === void 0) continue;
706
+ if (value && typeof value === "object" && !Array.isArray(value) && result[key] && typeof result[key] === "object" && !Array.isArray(result[key])) {
707
+ result[key] = deepMerge(result[key], value);
708
+ } else {
709
+ result[key] = value;
710
+ }
711
+ }
712
+ }
713
+ return result;
714
+ }
715
+
716
+ // src/ports/scanner.ts
717
+ import { createServer } from "net";
718
+ async function isPortAvailable(port) {
719
+ return new Promise((resolve) => {
720
+ const server = createServer();
721
+ server.once("error", () => {
722
+ resolve(false);
723
+ });
724
+ server.once("listening", () => {
725
+ server.close(() => {
726
+ resolve(true);
727
+ });
728
+ });
729
+ server.listen(port, "127.0.0.1");
730
+ setTimeout(() => {
731
+ server.close();
732
+ resolve(false);
733
+ }, 1e3);
734
+ });
735
+ }
736
+ async function checkPorts(ports2) {
737
+ const results = /* @__PURE__ */ new Map();
738
+ await Promise.all(
739
+ ports2.map(async (port) => {
740
+ results.set(port, await isPortAvailable(port));
741
+ })
742
+ );
743
+ return results;
744
+ }
745
+ async function findNextAvailablePort(startPort, maxPort = 65535) {
746
+ for (let port = startPort; port <= maxPort; port++) {
747
+ if (await isPortAvailable(port)) {
748
+ return port;
749
+ }
750
+ }
751
+ return void 0;
752
+ }
753
+ async function findAvailablePortInRange(start, end) {
754
+ for (let port = start; port <= end; port++) {
755
+ if (await isPortAvailable(port)) {
756
+ return port;
757
+ }
758
+ }
759
+ return void 0;
760
+ }
761
+ async function resolvePort(options = {}) {
762
+ const {
763
+ preferred = 3e3,
764
+ strategy = "auto",
765
+ range
766
+ } = options;
767
+ switch (strategy) {
768
+ case "fixed":
769
+ if (await isPortAvailable(preferred)) {
770
+ return preferred;
771
+ }
772
+ throw new Error(`Port ${preferred} is already in use`);
773
+ case "range":
774
+ if (range) {
775
+ const [start, end = start + 100] = range;
776
+ const port2 = await findAvailablePortInRange(start, end);
777
+ if (port2 !== void 0) {
778
+ return port2;
779
+ }
780
+ throw new Error(`No available port in range ${start}-${end}`);
781
+ }
782
+ // Fall through to auto if no range specified
783
+ case "auto":
784
+ default:
785
+ const port = await findNextAvailablePort(preferred);
786
+ if (port !== void 0) {
787
+ return port;
788
+ }
789
+ throw new Error(`No available port found starting from ${preferred}`);
790
+ }
791
+ }
792
+
793
+ // src/core/config.ts
794
+ var DEFAULT_APP_CONFIG = {
795
+ port: 3e3,
796
+ node: "20-alpine",
797
+ workdir: "/app",
798
+ command: "npm start",
799
+ buildCommand: "npm run build",
800
+ env: [],
801
+ volumes: [],
802
+ multiStage: true
803
+ };
804
+ function normalizeAppConfig(config) {
805
+ return {
806
+ port: config.port === "auto" ? 3e3 : config.port,
807
+ node: config.node ?? DEFAULT_APP_CONFIG.node,
808
+ workdir: config.workdir ?? DEFAULT_APP_CONFIG.workdir,
809
+ command: config.command ?? DEFAULT_APP_CONFIG.command,
810
+ buildCommand: config.buildCommand ?? DEFAULT_APP_CONFIG.buildCommand,
811
+ env: config.env ?? DEFAULT_APP_CONFIG.env,
812
+ volumes: config.volumes ?? DEFAULT_APP_CONFIG.volumes,
813
+ multiStage: config.multiStage ?? DEFAULT_APP_CONFIG.multiStage,
814
+ healthcheck: config.healthcheck
815
+ };
816
+ }
817
+ function normalizeOutputConfig(config) {
818
+ return {
819
+ dir: config?.dir ?? "./",
820
+ files: config?.files ?? ["dockerfile", "compose", "dockerignore", "env"],
821
+ overwrite: config?.overwrite ?? false
822
+ };
823
+ }
824
+ function normalizeConfig(config) {
825
+ return {
826
+ name: config.name,
827
+ preset: config.preset,
828
+ app: config.app,
829
+ services: config.services ?? {},
830
+ output: normalizeOutputConfig(config.output),
831
+ plugins: config.plugins ?? []
832
+ };
833
+ }
834
+ async function loadConfig(configPath) {
835
+ try {
836
+ const module = await import(configPath.toString());
837
+ const config = module.default ?? module;
838
+ return config;
839
+ } catch (error3) {
840
+ throw new Error(
841
+ `Failed to load config from ${configPath}: ${error3 instanceof Error ? error3.message : String(error3)}`
842
+ );
843
+ }
844
+ }
845
+
846
+ // src/core/resolver.ts
847
+ function mergePreset(config, presetName) {
848
+ const preset = getPreset(presetName);
849
+ if (!preset) {
850
+ throw new Error(`Preset '${presetName}' not found`);
851
+ }
852
+ const merged = deepMerge(
853
+ {
854
+ name: config.name,
855
+ app: preset.app ?? {},
856
+ services: preset.services ?? {},
857
+ output: preset.output ?? {}
858
+ },
859
+ config
860
+ );
861
+ return merged;
862
+ }
863
+ async function resolveServiceConfig(name, config, projectName) {
864
+ if ("image" in config && config.image) {
865
+ return resolveCustomService(name, config);
866
+ }
867
+ const definition = getService(name);
868
+ if (!definition) {
869
+ throw new Error(`Unknown service: ${name}`);
870
+ }
871
+ const defaultPort = definition.defaultPort;
872
+ let port = defaultPort;
873
+ let hostPort;
874
+ if (config.port === "auto") {
875
+ port = await resolvePort({ preferred: defaultPort, strategy: "auto" });
876
+ hostPort = port;
877
+ } else if (typeof config.port === "number") {
878
+ port = config.port;
879
+ hostPort = config.port;
880
+ } else if (config.port && typeof config.port === "object") {
881
+ const { start, end } = config.port;
882
+ const startPort = start ?? defaultPort;
883
+ const endPort = end ?? startPort + 100;
884
+ port = await resolvePort({ preferred: startPort, strategy: "range", range: [startPort, endPort] });
885
+ hostPort = port;
886
+ }
887
+ const version = config.version ?? definition.defaultVersion;
888
+ const image = typeof definition.image === "function" ? definition.image(version) : definition.image;
889
+ const env = { ...definition.env, ...config.env };
890
+ if (name === "postgres") {
891
+ const pgConfig = config;
892
+ if (pgConfig.database) env.POSTGRES_DB = pgConfig.database;
893
+ if (pgConfig.user) env.POSTGRES_USER = pgConfig.user;
894
+ if (pgConfig.password) env.POSTGRES_PASSWORD = pgConfig.password;
895
+ if (!env.POSTGRES_DB) env.POSTGRES_DB = projectName;
896
+ } else if (name === "mysql") {
897
+ const mysqlConfig = config;
898
+ if (mysqlConfig.database) env.MYSQL_DATABASE = mysqlConfig.database;
899
+ if (mysqlConfig.user) env.MYSQL_USER = mysqlConfig.user;
900
+ if (mysqlConfig.password) env.MYSQL_PASSWORD = mysqlConfig.password;
901
+ if (mysqlConfig.rootPassword) env.MYSQL_ROOT_PASSWORD = mysqlConfig.rootPassword;
902
+ if (!env.MYSQL_DATABASE) env.MYSQL_DATABASE = projectName;
903
+ } else if (name === "mongo") {
904
+ const mongoConfig = config;
905
+ if (mongoConfig.database) env.MONGO_INITDB_DATABASE = mongoConfig.database;
906
+ if (mongoConfig.user) env.MONGO_INITDB_ROOT_USERNAME = mongoConfig.user;
907
+ if (mongoConfig.password) env.MONGO_INITDB_ROOT_PASSWORD = mongoConfig.password;
908
+ if (!env.MONGO_INITDB_DATABASE) env.MONGO_INITDB_DATABASE = projectName;
909
+ } else if (name === "redis") {
910
+ const redisConfig = config;
911
+ if (redisConfig.password) env.REDIS_PASSWORD = redisConfig.password;
912
+ }
913
+ const volumes = [...definition.volumes ?? [], ...config.volumes ?? []];
914
+ const resolvedConfig = {
915
+ name,
916
+ image,
917
+ port,
918
+ hostPort,
919
+ env,
920
+ volumes,
921
+ command: config.command,
922
+ healthcheck: definition.healthcheck,
923
+ ports: definition.ports
924
+ };
925
+ if (definition.connectionString) {
926
+ resolvedConfig.connectionString = definition.connectionString(resolvedConfig);
927
+ }
928
+ return resolvedConfig;
929
+ }
930
+ async function resolveCustomService(name, config) {
931
+ const imageMatch = config.image.match(/:(\d+)$/);
932
+ const defaultPort = imageMatch && imageMatch[1] ? parseInt(imageMatch[1], 10) : 80;
933
+ let port = defaultPort;
934
+ let hostPort;
935
+ if (config.port === "auto") {
936
+ port = await resolvePort({ preferred: defaultPort, strategy: "auto" });
937
+ hostPort = port;
938
+ } else if (typeof config.port === "number") {
939
+ port = config.port;
940
+ hostPort = config.port;
941
+ } else if (config.port && typeof config.port === "object") {
942
+ const { start, end } = config.port;
943
+ const startPort = start ?? defaultPort;
944
+ const endPort = end ?? startPort + 100;
945
+ port = await resolvePort({ preferred: startPort, strategy: "range", range: [startPort, endPort] });
946
+ hostPort = port;
947
+ }
948
+ return {
949
+ name,
950
+ image: config.image,
951
+ port,
952
+ hostPort,
953
+ env: config.env ?? {},
954
+ volumes: config.volumes ?? [],
955
+ command: config.command,
956
+ healthcheck: config.command,
957
+ ports: []
958
+ };
959
+ }
960
+ async function resolveConfig(config) {
961
+ let finalConfig = config;
962
+ if (config.preset) {
963
+ finalConfig = mergePreset(config, config.preset);
964
+ }
965
+ finalConfig = normalizeConfig(finalConfig);
966
+ const appPort = finalConfig.app.port === "auto" ? await resolvePort({ preferred: 3e3, strategy: "auto" }) : finalConfig.app.port;
967
+ const app = normalizeAppConfig({ ...finalConfig.app, port: appPort });
968
+ const services2 = {};
969
+ if (finalConfig.services) {
970
+ for (const [name, serviceConfig] of Object.entries(finalConfig.services)) {
971
+ if (serviceConfig) {
972
+ services2[name] = await resolveServiceConfig(
973
+ name,
974
+ serviceConfig,
975
+ finalConfig.name
976
+ );
977
+ }
978
+ }
979
+ }
980
+ return {
981
+ name: finalConfig.name,
982
+ app,
983
+ services: services2,
984
+ output: normalizeOutputConfig(finalConfig.output)
985
+ };
986
+ }
987
+
988
+ // src/utils/validation.ts
989
+ var MIN_PORT = 1;
990
+ var MAX_PORT = 65535;
991
+ function isPort(value) {
992
+ return typeof value === "number" && Number.isInteger(value) && value >= MIN_PORT && value <= MAX_PORT;
993
+ }
994
+ function isEnvVarName(value) {
995
+ if (typeof value !== "string") return false;
996
+ return /^[A-Z_][A-Z0-9_]*$/.test(value);
997
+ }
998
+ function isVersion(value) {
999
+ if (typeof value !== "string") return false;
1000
+ if (value.length === 0) return false;
1001
+ return /^[a-zA-Z0-9.\-]+$/.test(value);
1002
+ }
1003
+ function isProjectName(value) {
1004
+ if (typeof value !== "string") return false;
1005
+ if (value.length === 0 || value.length > 100) return false;
1006
+ return /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(value);
1007
+ }
1008
+
1009
+ // src/core/validator.ts
1010
+ function validateProjectName(name) {
1011
+ const errors = [];
1012
+ if (!isProjectName(name)) {
1013
+ errors.push({
1014
+ code: "INVALID_NAME",
1015
+ message: `Invalid project name '${name}'. Must start with a letter and contain only letters, numbers, hyphens, and underscores.`,
1016
+ path: "name",
1017
+ value: name
1018
+ });
1019
+ }
1020
+ return errors;
1021
+ }
1022
+ function validateAppConfig(config) {
1023
+ const errors = [];
1024
+ if (config.port !== "auto" && !isPort(config.port)) {
1025
+ errors.push({
1026
+ code: "INVALID_PORT",
1027
+ message: `Invalid app port '${String(config.port)}'. Must be a number between 1-65535 or 'auto'.`,
1028
+ path: "app.port",
1029
+ value: config.port
1030
+ });
1031
+ }
1032
+ if (config.node !== void 0 && !isVersion(config.node)) {
1033
+ errors.push({
1034
+ code: "INVALID_VERSION",
1035
+ message: `Invalid Node.js version '${config.node}'.`,
1036
+ path: "app.node",
1037
+ value: config.node
1038
+ });
1039
+ }
1040
+ if (config.env) {
1041
+ for (const envVar of config.env) {
1042
+ if (!isEnvVarName(envVar)) {
1043
+ errors.push({
1044
+ code: "INVALID_ENV_VAR",
1045
+ message: `Invalid environment variable name '${envVar}'. Must be uppercase letters, numbers, and underscores.`,
1046
+ path: "app.env",
1047
+ value: envVar
1048
+ });
1049
+ }
1050
+ }
1051
+ }
1052
+ return errors;
1053
+ }
1054
+ function validateServiceConfig(name, config) {
1055
+ const errors = [];
1056
+ if (config.version !== void 0 && !isVersion(config.version)) {
1057
+ errors.push({
1058
+ code: "INVALID_VERSION",
1059
+ message: `Invalid version '${config.version}' for service '${name}'.`,
1060
+ path: `services.${name}.version`,
1061
+ value: config.version
1062
+ });
1063
+ }
1064
+ if (config.port !== void 0 && config.port !== "auto" && typeof config.port !== "number" && typeof config.port !== "object") {
1065
+ errors.push({
1066
+ code: "INVALID_PORT",
1067
+ message: `Invalid port configuration for service '${name}'. Must be a number, 'auto', or a range object.`,
1068
+ path: `services.${name}.port`,
1069
+ value: config.port
1070
+ });
1071
+ }
1072
+ return errors;
1073
+ }
1074
+ function validateOutputConfig(config) {
1075
+ const errors = [];
1076
+ if (config?.files) {
1077
+ const validFiles = ["dockerfile", "compose", "dockerignore", "env", "scripts", "makefile"];
1078
+ for (const file of config.files) {
1079
+ if (!validFiles.includes(file)) {
1080
+ errors.push({
1081
+ code: "INVALID_OUTPUT_FILE",
1082
+ message: `Invalid output file '${file}'. Must be one of: ${validFiles.join(", ")}.`,
1083
+ path: "output.files",
1084
+ value: file
1085
+ });
1086
+ }
1087
+ }
1088
+ }
1089
+ return errors;
1090
+ }
1091
+ function validateConfig(config) {
1092
+ const errors = [];
1093
+ errors.push(...validateProjectName(config.name));
1094
+ if (config.app) {
1095
+ errors.push(...validateAppConfig(config.app));
1096
+ }
1097
+ if (config.services) {
1098
+ for (const [name, serviceConfig] of Object.entries(config.services)) {
1099
+ if (serviceConfig) {
1100
+ errors.push(...validateServiceConfig(name, serviceConfig));
1101
+ }
1102
+ }
1103
+ }
1104
+ if (config.output) {
1105
+ errors.push(...validateOutputConfig(config.output));
1106
+ }
1107
+ return {
1108
+ valid: errors.length === 0,
1109
+ errors
1110
+ };
1111
+ }
1112
+ function validateResolvedConfig(config) {
1113
+ const errors = [];
1114
+ const usedPorts = /* @__PURE__ */ new Set();
1115
+ usedPorts.add(config.app.port);
1116
+ for (const [serviceName, serviceConfig] of Object.entries(config.services)) {
1117
+ if (usedPorts.has(serviceConfig.port)) {
1118
+ errors.push({
1119
+ code: "PORT_CONFLICT",
1120
+ message: `Port ${serviceConfig.port} is already in use by ${serviceName}.`,
1121
+ path: `services.${serviceName}.port`,
1122
+ value: serviceConfig.port
1123
+ });
1124
+ }
1125
+ usedPorts.add(serviceConfig.port);
1126
+ }
1127
+ return {
1128
+ valid: errors.length === 0,
1129
+ errors
1130
+ };
1131
+ }
1132
+
1133
+ // src/generators/dockerfile.ts
1134
+ function generateDockerfile(config, _context) {
1135
+ const { app, name } = config;
1136
+ const { node, workdir, command, buildCommand, multiStage, healthcheck } = app;
1137
+ const port = app.port;
1138
+ let dockerfile = "";
1139
+ if (multiStage) {
1140
+ dockerfile += `# Builder stage
1141
+ `;
1142
+ dockerfile += `FROM node:${node} AS builder
1143
+
1144
+ `;
1145
+ dockerfile += `WORKDIR ${workdir}
1146
+
1147
+ `;
1148
+ dockerfile += `# Copy package files
1149
+ `;
1150
+ dockerfile += `COPY package*.json ./
1151
+
1152
+ `;
1153
+ dockerfile += `# Install dependencies
1154
+ `;
1155
+ dockerfile += `RUN npm ci && npm cache clean --force
1156
+
1157
+ `;
1158
+ dockerfile += `# Copy source files
1159
+ `;
1160
+ dockerfile += `COPY . .
1161
+
1162
+ `;
1163
+ dockerfile += `# Build application
1164
+ `;
1165
+ dockerfile += `RUN npm run build 2>/dev/null || true
1166
+
1167
+ `;
1168
+ dockerfile += `# Production stage
1169
+ `;
1170
+ dockerfile += `FROM node:${node}
1171
+
1172
+ `;
1173
+ dockerfile += `WORKDIR ${workdir}
1174
+
1175
+ `;
1176
+ dockerfile += `ENV NODE_ENV=production
1177
+
1178
+ `;
1179
+ dockerfile += `# Copy from builder
1180
+ `;
1181
+ dockerfile += `COPY --from=builder ${workdir}/node_modules ./node_modules
1182
+ `;
1183
+ dockerfile += `COPY --from=builder ${workdir}/dist ./dist
1184
+ `;
1185
+ dockerfile += `COPY --from=builder ${workdir}/package*.json ./
1186
+
1187
+ `;
1188
+ } else {
1189
+ dockerfile += `FROM node:${node}
1190
+
1191
+ `;
1192
+ dockerfile += `WORKDIR ${workdir}
1193
+
1194
+ `;
1195
+ dockerfile += `ENV NODE_ENV=production
1196
+
1197
+ `;
1198
+ dockerfile += `# Copy package files
1199
+ `;
1200
+ dockerfile += `COPY package*.json ./
1201
+
1202
+ `;
1203
+ dockerfile += `# Install dependencies
1204
+ `;
1205
+ dockerfile += `RUN npm ci --only=production && npm cache clean --force
1206
+
1207
+ `;
1208
+ dockerfile += `# Copy source files
1209
+ `;
1210
+ dockerfile += `COPY . .
1211
+
1212
+ `;
1213
+ }
1214
+ dockerfile += `EXPOSE ${port}
1215
+
1216
+ `;
1217
+ if (healthcheck) {
1218
+ dockerfile += `HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \\
1219
+ CMD node -e "require('http').get('http://localhost:${port}${healthcheck}', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})" || exit 1
1220
+
1221
+ `;
1222
+ }
1223
+ dockerfile += `CMD ["npm", "start"]
1224
+ `;
1225
+ return dockerfile;
1226
+ }
1227
+
1228
+ // src/utils/yaml.ts
1229
+ function toYaml(obj, indent = 0) {
1230
+ const spaces = " ".repeat(indent);
1231
+ if (obj === null) {
1232
+ return "null";
1233
+ }
1234
+ if (typeof obj === "string") {
1235
+ return quoteStringIfNeeded(obj);
1236
+ }
1237
+ if (typeof obj === "number" || typeof obj === "boolean") {
1238
+ return String(obj);
1239
+ }
1240
+ if (Array.isArray(obj)) {
1241
+ return arrayToYaml(obj, indent);
1242
+ }
1243
+ if (typeof obj === "object") {
1244
+ return objectToYaml(obj, indent);
1245
+ }
1246
+ return String(obj);
1247
+ }
1248
+ function arrayToYaml(arr, indent) {
1249
+ const spaces = " ".repeat(indent);
1250
+ const innerSpaces = " ".repeat(indent + 2);
1251
+ if (arr.length === 0) {
1252
+ return "[]";
1253
+ }
1254
+ if (arr.every(
1255
+ (item) => typeof item === "string" || typeof item === "number" || typeof item === "boolean" || item === null
1256
+ )) {
1257
+ const items = arr.map((item) => toYaml(item, 0)).join(", ");
1258
+ return `[${items}]`;
1259
+ }
1260
+ const lines = [];
1261
+ for (const item of arr) {
1262
+ const value = toYaml(item, indent + 2);
1263
+ if (value.includes("\n")) {
1264
+ lines.push(`${spaces}- ${value.slice(indent + 2)}`);
1265
+ } else {
1266
+ lines.push(`${spaces}- ${value}`);
1267
+ }
1268
+ }
1269
+ return lines.join("\n");
1270
+ }
1271
+ function objectToYaml(obj, indent) {
1272
+ const keys = Object.keys(obj);
1273
+ if (keys.length === 0) {
1274
+ return "{}";
1275
+ }
1276
+ const spaces = " ".repeat(indent);
1277
+ const lines = [];
1278
+ for (const key of keys) {
1279
+ const value = obj[key];
1280
+ const valueStr = toYaml(value, indent + 2);
1281
+ if (valueStr.includes("\n")) {
1282
+ lines.push(`${spaces}${key}:`);
1283
+ lines.push(valueStr);
1284
+ } else {
1285
+ lines.push(`${spaces}${key}: ${valueStr}`);
1286
+ }
1287
+ }
1288
+ return lines.join("\n");
1289
+ }
1290
+ function quoteStringIfNeeded(str) {
1291
+ if (str === "" || str.startsWith('"') || str.startsWith("'")) {
1292
+ return `"${escapeString(str)}"`;
1293
+ }
1294
+ if (/^[\-\?:\[\]{},&*#|!<>@%'"`]/.test(str)) {
1295
+ return `"${escapeString(str)}"`;
1296
+ }
1297
+ if (/[:\s#]/.test(str)) {
1298
+ return `"${escapeString(str)}"`;
1299
+ }
1300
+ if (/^(true|false|null|NaN|Infinity|\-?\d+(\.\d+)?)$/.test(str)) {
1301
+ return `"${escapeString(str)}"`;
1302
+ }
1303
+ return escapeString(str);
1304
+ }
1305
+ function escapeString(str) {
1306
+ return str.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
1307
+ }
1308
+
1309
+ // src/generators/compose.ts
1310
+ function generateCompose(config, context) {
1311
+ const { name, app, services: services2 } = config;
1312
+ const compose = {
1313
+ version: "3.9",
1314
+ services: {
1315
+ app: {
1316
+ build: ".",
1317
+ ports: [`${app.port}:${app.port}`],
1318
+ environment: generateAppEnvironment(config, context),
1319
+ depends_on: Object.keys(services2),
1320
+ volumes: app.volumes.length > 0 ? app.volumes : void 0
1321
+ }
1322
+ },
1323
+ volumes: generateVolumeDefinitions(services2)
1324
+ };
1325
+ const servicesRecord = compose.services;
1326
+ if (app.healthcheck && servicesRecord.app) {
1327
+ servicesRecord.app.healthcheck = {
1328
+ test: [`CMD`, `curl`, `-f`, `http://localhost:${app.port}${app.healthcheck}`],
1329
+ interval: "30s",
1330
+ timeout: "3s",
1331
+ retries: 3
1332
+ };
1333
+ }
1334
+ for (const [serviceName, serviceConfig] of Object.entries(services2)) {
1335
+ servicesRecord[serviceName] = generateServiceConfig(serviceName, serviceConfig);
1336
+ }
1337
+ return toYaml(compose);
1338
+ }
1339
+ function generateAppEnvironment(config, context) {
1340
+ const env = ["NODE_ENV=production", `PORT=${config.app.port}`];
1341
+ for (const [serviceName, serviceConfig] of Object.entries(config.services)) {
1342
+ if (serviceConfig.connectionString) {
1343
+ const key = `${serviceName.toUpperCase()}_URL`;
1344
+ env.push(`${key}=${serviceConfig.connectionString}`);
1345
+ }
1346
+ }
1347
+ if (config.services.postgres) {
1348
+ const pg = config.services.postgres;
1349
+ env.push(`POSTGRES_HOST=${pg.name}`);
1350
+ env.push(`POSTGRES_PORT=${pg.port}`);
1351
+ env.push(`POSTGRES_USER=${pg.env.POSTGRES_USER || "postgres"}`);
1352
+ env.push(`POSTGRES_PASSWORD=${pg.env.POSTGRES_PASSWORD || "postgres"}`);
1353
+ env.push(`POSTGRES_DB=${pg.env.POSTGRES_DB || config.name}`);
1354
+ }
1355
+ if (config.services.mysql) {
1356
+ const mysql = config.services.mysql;
1357
+ env.push(`MYSQL_HOST=${mysql.name}`);
1358
+ env.push(`MYSQL_PORT=${mysql.port}`);
1359
+ env.push(`MYSQL_USER=${mysql.env.MYSQL_USER || "root"}`);
1360
+ env.push(`MYSQL_PASSWORD=${mysql.env.MYSQL_PASSWORD || mysql.env.MYSQL_ROOT_PASSWORD || "root"}`);
1361
+ env.push(`MYSQL_DATABASE=${mysql.env.MYSQL_DATABASE || config.name}`);
1362
+ }
1363
+ if (config.services.mongo) {
1364
+ const mongo = config.services.mongo;
1365
+ env.push(`MONGO_HOST=${mongo.name}`);
1366
+ env.push(`MONGO_PORT=${mongo.port}`);
1367
+ env.push(`MONGO_USER=${mongo.env.MONGO_INITDB_ROOT_USERNAME || "mongo"}`);
1368
+ env.push(`MONGO_PASSWORD=${mongo.env.MONGO_INITDB_ROOT_PASSWORD || "mongo"}`);
1369
+ env.push(`MONGO_DATABASE=${mongo.env.MONGO_INITDB_DATABASE || config.name}`);
1370
+ }
1371
+ if (config.services.redis) {
1372
+ const redis = config.services.redis;
1373
+ env.push(`REDIS_HOST=${redis.name}`);
1374
+ env.push(`REDIS_PORT=${redis.port}`);
1375
+ }
1376
+ return env;
1377
+ }
1378
+ function generateServiceConfig(name, config) {
1379
+ const service = {
1380
+ image: config.image,
1381
+ ports: [],
1382
+ environment: config.env
1383
+ };
1384
+ const portMappings = [];
1385
+ portMappings.push(`${config.hostPort ?? config.port}:${config.port}`);
1386
+ if (config.ports) {
1387
+ for (const extraPort of config.ports) {
1388
+ portMappings.push(`${extraPort}:${extraPort}`);
1389
+ }
1390
+ }
1391
+ service.ports = portMappings;
1392
+ if (config.volumes.length > 0) {
1393
+ service.volumes = config.volumes;
1394
+ }
1395
+ if (config.command) {
1396
+ service.command = config.command;
1397
+ }
1398
+ if (config.healthcheck) {
1399
+ service.healthcheck = {
1400
+ test: ["CMD-SHELL", config.healthcheck],
1401
+ interval: "10s",
1402
+ timeout: "5s",
1403
+ retries: 5
1404
+ };
1405
+ }
1406
+ return service;
1407
+ }
1408
+ function generateVolumeDefinitions(services2) {
1409
+ const volumes = {};
1410
+ for (const serviceConfig of Object.values(services2)) {
1411
+ for (const volume of serviceConfig.volumes) {
1412
+ if (volume.includes(":")) {
1413
+ const [name] = volume.split(":");
1414
+ if (name) {
1415
+ volumes[name] = null;
1416
+ }
1417
+ }
1418
+ }
1419
+ }
1420
+ return volumes;
1421
+ }
1422
+
1423
+ // src/generators/dockerignore.ts
1424
+ function generateDockerignore(_config) {
1425
+ return `# Dependencies
1426
+ node_modules/
1427
+ npm-debug.log*
1428
+ yarn-debug.log*
1429
+ yarn-error.log*
1430
+ pnpm-debug.log*
1431
+
1432
+ # Environment
1433
+ .env
1434
+ .env.local
1435
+ .env.*.local
1436
+
1437
+ # Git
1438
+ .git/
1439
+ .gitignore
1440
+ .gitattributes
1441
+
1442
+ # Documentation
1443
+ README.md
1444
+ CHANGELOG.md
1445
+ LICENSE
1446
+ SPECIFICATION.md
1447
+ IMPLEMENTATION.md
1448
+ TASKS.md
1449
+ docs/
1450
+
1451
+ # IDE
1452
+ .vscode/
1453
+ .idea/
1454
+ *.swp
1455
+ *.swo
1456
+ *~
1457
+ .DS_Store
1458
+
1459
+ # Testing
1460
+ coverage/
1461
+ .nyc_output/
1462
+ *.test.ts
1463
+ *.spec.ts
1464
+ tests/
1465
+ vitest.config.ts
1466
+
1467
+ # Build
1468
+ dist/
1469
+ build/
1470
+ *.tsbuildinfo
1471
+
1472
+ # Temporary
1473
+ *.log
1474
+ tmp/
1475
+ temp/
1476
+
1477
+ # CI/CD
1478
+ .github/
1479
+ .gitlab-ci.yml
1480
+ .travis.yml
1481
+
1482
+ # Docker
1483
+ Dockerfile
1484
+ docker-compose.yml
1485
+ .dockerignore
1486
+
1487
+ # Package manager lockfiles (optional - uncomment if you want to exclude)
1488
+ # package-lock.json
1489
+ # yarn.lock
1490
+ # pnpm-lock.yaml
1491
+ `;
1492
+ }
1493
+
1494
+ // src/generators/env.ts
1495
+ function generateEnvExample(config) {
1496
+ let content = `# Application Configuration
1497
+ NODE_ENV=production
1498
+ PORT=${config.app.port}
1499
+ `;
1500
+ if (config.app.env.length > 0) {
1501
+ content += `
1502
+ # Required Environment Variables
1503
+ `;
1504
+ for (const envVar of config.app.env) {
1505
+ content += `${envVar}=
1506
+ `;
1507
+ }
1508
+ }
1509
+ if (config.services.postgres) {
1510
+ const pg = config.services.postgres;
1511
+ content += `
1512
+ # PostgreSQL
1513
+ `;
1514
+ content += `DATABASE_URL=${pg.connectionString || ""}
1515
+ `;
1516
+ content += `POSTGRES_HOST=${pg.name}
1517
+ `;
1518
+ content += `POSTGRES_PORT=${pg.port}
1519
+ `;
1520
+ content += `POSTGRES_USER=${pg.env.POSTGRES_USER || "postgres"}
1521
+ `;
1522
+ content += `POSTGRES_PASSWORD=${pg.env.POSTGRES_PASSWORD || "postgres"}
1523
+ `;
1524
+ content += `POSTGRES_DB=${pg.env.POSTGRES_DB || config.name}
1525
+ `;
1526
+ }
1527
+ if (config.services.mysql) {
1528
+ const mysql = config.services.mysql;
1529
+ content += `
1530
+ # MySQL
1531
+ `;
1532
+ content += `MYSQL_URL=${mysql.connectionString || ""}
1533
+ `;
1534
+ content += `MYSQL_HOST=${mysql.name}
1535
+ `;
1536
+ content += `MYSQL_PORT=${mysql.port}
1537
+ `;
1538
+ content += `MYSQL_USER=${mysql.env.MYSQL_USER || "root"}
1539
+ `;
1540
+ content += `MYSQL_PASSWORD=${mysql.env.MYSQL_PASSWORD || mysql.env.MYSQL_ROOT_PASSWORD || "root"}
1541
+ `;
1542
+ content += `MYSQL_DATABASE=${mysql.env.MYSQL_DATABASE || config.name}
1543
+ `;
1544
+ }
1545
+ if (config.services.mongo) {
1546
+ const mongo = config.services.mongo;
1547
+ content += `
1548
+ # MongoDB
1549
+ `;
1550
+ content += `MONGO_URL=${mongo.connectionString || ""}
1551
+ `;
1552
+ content += `MONGO_HOST=${mongo.name}
1553
+ `;
1554
+ content += `MONGO_PORT=${mongo.port}
1555
+ `;
1556
+ content += `MONGO_USER=${mongo.env.MONGO_INITDB_ROOT_USERNAME || "mongo"}
1557
+ `;
1558
+ content += `MONGO_PASSWORD=${mongo.env.MONGO_INITDB_ROOT_PASSWORD || "mongo"}
1559
+ `;
1560
+ content += `MONGO_DATABASE=${mongo.env.MONGO_INITDB_DATABASE || config.name}
1561
+ `;
1562
+ }
1563
+ if (config.services.redis) {
1564
+ const redis = config.services.redis;
1565
+ content += `
1566
+ # Redis
1567
+ `;
1568
+ content += `REDIS_URL=${redis.connectionString || ""}
1569
+ `;
1570
+ content += `REDIS_HOST=${redis.name}
1571
+ `;
1572
+ content += `REDIS_PORT=${redis.port}
1573
+ `;
1574
+ if (redis.env.REDIS_PASSWORD) {
1575
+ content += `REDIS_PASSWORD=${redis.env.REDIS_PASSWORD}
1576
+ `;
1577
+ }
1578
+ }
1579
+ return content;
1580
+ }
1581
+
1582
+ // src/generators/scripts.ts
1583
+ function generateBuildScript(_config) {
1584
+ return `#!/bin/bash
1585
+ # Docker build script
1586
+
1587
+ set -e
1588
+
1589
+ echo "Building Docker image..."
1590
+ docker-compose build
1591
+
1592
+ echo "Build complete!"
1593
+ `;
1594
+ }
1595
+ function generateUpScript(config) {
1596
+ const services2 = ["app", ...Object.keys(config.services)];
1597
+ return `#!/bin/bash
1598
+ # Docker up script
1599
+
1600
+ set -e
1601
+
1602
+ echo "Starting services..."
1603
+ docker-compose up -d ${services2.join(" ")}
1604
+
1605
+ echo "Services started!"
1606
+ echo ""
1607
+ echo "App running at http://localhost:${config.app.port}"
1608
+ `;
1609
+ }
1610
+ function generateDownScript(_config) {
1611
+ return `#!/bin/bash
1612
+ # Docker down script
1613
+
1614
+ set -e
1615
+
1616
+ echo "Stopping services..."
1617
+ docker-compose down
1618
+
1619
+ echo "Services stopped!"
1620
+ `;
1621
+ }
1622
+ function generateLogsScript(_config) {
1623
+ return `#!/bin/bash
1624
+ # Docker logs script
1625
+
1626
+ set -e
1627
+
1628
+ if [ -n "$1" ]; then
1629
+ docker-compose logs -f "$1"
1630
+ else
1631
+ docker-compose logs -f
1632
+ fi
1633
+ `;
1634
+ }
1635
+ function generateScripts(config) {
1636
+ return {
1637
+ "docker-build.sh": generateBuildScript(config),
1638
+ "docker-up.sh": generateUpScript(config),
1639
+ "docker-down.sh": generateDownScript(config),
1640
+ "docker-logs.sh": generateLogsScript(config)
1641
+ };
1642
+ }
1643
+
1644
+ // src/generators/makefile.ts
1645
+ function generateMakefile(config) {
1646
+ const services2 = Object.keys(config.services);
1647
+ let content = `.PHONY: help build up down restart logs clean install shell
1648
+
1649
+ # Default target
1650
+ help:
1651
+ @echo "Available targets:"
1652
+ @echo " make build - Build Docker images"
1653
+ @echo " make up - Start all services"
1654
+ @echo " make down - Stop all services"
1655
+ @echo " make restart - Restart all services"
1656
+ @echo " make logs - Show logs from all services"
1657
+ @echo " make shell - Open shell in app container"
1658
+ @echo " make clean - Remove containers and volumes"
1659
+ @echo " make install - Install dependencies"
1660
+
1661
+ # Build Docker images
1662
+ build:
1663
+ docker-compose build
1664
+
1665
+ # Start all services
1666
+ up:
1667
+ docker-compose up -d
1668
+ @echo "App running at http://localhost:${config.app.port}"
1669
+
1670
+ # Stop all services
1671
+ down:
1672
+ docker-compose down
1673
+
1674
+ # Restart all services
1675
+ restart: down up
1676
+
1677
+ # Show logs from all services
1678
+ logs:
1679
+ docker-compose logs -f
1680
+ `;
1681
+ if (services2.length > 0) {
1682
+ content += "\n";
1683
+ for (const service of services2) {
1684
+ content += `
1685
+ logs-${service}:
1686
+ `;
1687
+ content += ` docker-compose logs -f ${service}
1688
+ `;
1689
+ }
1690
+ }
1691
+ content += `
1692
+ # Clean up containers and volumes
1693
+ clean:
1694
+ docker-compose down -v
1695
+ docker system prune -f
1696
+
1697
+ # Install dependencies (in running container)
1698
+ shell:
1699
+ docker-compose exec app sh
1700
+
1701
+ # Install dependencies
1702
+ install:
1703
+ docker-compose exec app npm install
1704
+ `;
1705
+ return content;
1706
+ }
1707
+
1708
+ // src/generators/index.ts
1709
+ var GENERATORS = {
1710
+ dockerfile: { file: "Dockerfile", generate: generateDockerfile },
1711
+ compose: { file: "docker-compose.yml", generate: generateCompose },
1712
+ dockerignore: { file: ".dockerignore", generate: generateDockerignore },
1713
+ env: { file: ".env.example", generate: generateEnvExample },
1714
+ scripts: { file: "scripts", generate: () => "" },
1715
+ // Special handling
1716
+ makefile: { file: "Makefile", generate: generateMakefile }
1717
+ };
1718
+ function generateAll(config, context) {
1719
+ const result = {};
1720
+ const filesToGenerate = config.output.files ?? Object.keys(GENERATORS);
1721
+ for (const fileType of filesToGenerate) {
1722
+ if (fileType === "scripts") {
1723
+ const scripts = generateScripts(config);
1724
+ for (const [name, content] of Object.entries(scripts)) {
1725
+ result[name] = content;
1726
+ }
1727
+ } else {
1728
+ const generator = GENERATORS[fileType];
1729
+ if (generator) {
1730
+ result[generator.file] = generator.generate(config, context);
1731
+ }
1732
+ }
1733
+ }
1734
+ return result;
1735
+ }
1736
+
1737
+ // src/core/dockcraft.ts
1738
+ import { join as join2 } from "path";
1739
+ async function dockcraft(config, options = {}) {
1740
+ const validation = validateConfig(config);
1741
+ if (!validation.valid) {
1742
+ const errorMessages = validation.errors.map((e) => ` - ${e.message}`).join("\n");
1743
+ throw new Error(
1744
+ `Configuration validation failed:
1745
+ ${errorMessages}`
1746
+ );
1747
+ }
1748
+ const resolved = await resolveConfig(config);
1749
+ const resolvedValidation = validateResolvedConfig(resolved);
1750
+ if (!resolvedValidation.valid) {
1751
+ const errorMessages = resolvedValidation.errors.map((e) => ` - ${e.message}`).join("\n");
1752
+ throw new Error(
1753
+ `Resolved configuration validation failed:
1754
+ ${errorMessages}`
1755
+ );
1756
+ }
1757
+ const context = {
1758
+ config: resolved,
1759
+ ports: new Map(
1760
+ Object.entries(resolved.services).map(([name, svc]) => [name, svc.port])
1761
+ ),
1762
+ strings: new Map(
1763
+ Object.entries(resolved.services).filter(([, svc]) => svc.connectionString).map(([name, svc]) => [name, svc.connectionString])
1764
+ )
1765
+ };
1766
+ context.ports.set("app", resolved.app.port);
1767
+ const generated = generateAll(resolved, context);
1768
+ const written = [];
1769
+ const outputDir = resolved.output.dir ?? "./";
1770
+ if (!options.dryRun) {
1771
+ for (const [fileName, content] of Object.entries(generated)) {
1772
+ if (!fileName) continue;
1773
+ const filePath = join2(outputDir, fileName);
1774
+ const exists = await fileExists(filePath);
1775
+ if (exists && !resolved.output.overwrite) {
1776
+ continue;
1777
+ }
1778
+ await writeFile(filePath, content);
1779
+ written.push(filePath);
1780
+ }
1781
+ }
1782
+ return {
1783
+ files: new Map(Object.entries(generated)),
1784
+ written,
1785
+ config: resolved
1786
+ };
1787
+ }
1788
+
1789
+ // src/cli/commands/generate.ts
1790
+ async function generate(args) {
1791
+ title("Dockcraft Generate");
1792
+ const configPath = getOption(args, "config", "./dockcraft.config.ts");
1793
+ const dryRun = getBooleanFlag(args, "dry-run");
1794
+ const force = getBooleanFlag(args, "force");
1795
+ const outputDir = getOption(args, "output", "./");
1796
+ try {
1797
+ subtitle(`Loading config from: ${configPath}`);
1798
+ const config = await loadConfig(configPath);
1799
+ if (force) {
1800
+ config.output = config.output ?? {};
1801
+ config.output.overwrite = true;
1802
+ }
1803
+ if (outputDir !== "./") {
1804
+ config.output = config.output ?? {};
1805
+ config.output.dir = outputDir;
1806
+ }
1807
+ const result = await dockcraft(config, { dryRun });
1808
+ if (dryRun) {
1809
+ subtitle("Preview (dry-run mode):");
1810
+ for (const [fileName, content] of result.files) {
1811
+ console.log("");
1812
+ console.log(`File: ${fileName}`);
1813
+ console.log("\u2500".repeat(50));
1814
+ console.log(content);
1815
+ console.log("\u2500".repeat(50));
1816
+ }
1817
+ } else {
1818
+ success(`Generated ${result.written.length} files:`);
1819
+ list(result.written);
1820
+ console.log("");
1821
+ success('Done! Run "docker-compose up -d" to start services');
1822
+ }
1823
+ } catch (err) {
1824
+ error(err instanceof Error ? err.message : String(err));
1825
+ process.exit(1);
1826
+ }
1827
+ }
1828
+
1829
+ // src/ports/defaults.ts
1830
+ var DEFAULT_PORTS = {
1831
+ postgres: 5432,
1832
+ mysql: 3306,
1833
+ mongo: 27017,
1834
+ mongodb: 27017,
1835
+ redis: 6379,
1836
+ elasticsearch: 9200,
1837
+ rabbitmq: 5672,
1838
+ memcached: 11211,
1839
+ nginx: 80,
1840
+ apache: 80
1841
+ };
1842
+ function listDefaultPorts() {
1843
+ return { ...DEFAULT_PORTS };
1844
+ }
1845
+
1846
+ // src/cli/commands/ports.ts
1847
+ async function ports(args) {
1848
+ title("Port Utilities");
1849
+ const checkOption = getOption(args, "check");
1850
+ const rangeOption = getOption(args, "range");
1851
+ const asJson = getBooleanFlag(args, "json");
1852
+ if (checkOption) {
1853
+ const portsToCheck = checkOption.split(",").map((s) => parseInt(s.trim(), 10));
1854
+ const results = await checkPorts(portsToCheck);
1855
+ if (asJson) {
1856
+ json(Object.fromEntries(results));
1857
+ } else {
1858
+ table(["Port", "Status"], [
1859
+ ...Array.from(results.entries()).map(([port, available]) => [
1860
+ String(port),
1861
+ available ? "\u2713 Available" : "\u2717 In use"
1862
+ ])
1863
+ ]);
1864
+ }
1865
+ return;
1866
+ }
1867
+ if (rangeOption) {
1868
+ const match = rangeOption.match(/^(\d+)-(\d+)$/);
1869
+ if (!match || !match[1] || !match[2]) {
1870
+ throw new Error("Invalid range format. Use: --range START-END (e.g., 3000-3010)");
1871
+ }
1872
+ const start = parseInt(match[1], 10);
1873
+ const end = parseInt(match[2], 10);
1874
+ if (asJson) {
1875
+ const port = await findAvailablePortInRange(start, end);
1876
+ json({ available: port });
1877
+ } else {
1878
+ const port = await findAvailablePortInRange(start, end);
1879
+ if (port) {
1880
+ success(`Found available port: ${port} in range ${start}-${end}`);
1881
+ } else {
1882
+ console.log(`No available port in range ${start}-${end}`);
1883
+ }
1884
+ }
1885
+ return;
1886
+ }
1887
+ const defaults = listDefaultPorts();
1888
+ if (asJson) {
1889
+ json(defaults);
1890
+ } else {
1891
+ subtitle("Default service ports:");
1892
+ table(["Service", "Port"], [
1893
+ ...Object.entries(defaults).map(([service, port]) => [service, String(port)])
1894
+ ]);
1895
+ }
1896
+ }
1897
+
1898
+ // src/cli/commands/presets.ts
1899
+ function presets2(args) {
1900
+ const presetName = args.positionals[0];
1901
+ if (presetName) {
1902
+ const preset = getPreset(presetName);
1903
+ if (!preset) {
1904
+ console.log(`Preset '${presetName}' not found`);
1905
+ return;
1906
+ }
1907
+ title(`Preset: ${presetName}`);
1908
+ if (preset.description) {
1909
+ subtitle("Description");
1910
+ console.log(` ${preset.description}`);
1911
+ }
1912
+ if (preset.app) {
1913
+ subtitle("App Configuration");
1914
+ const appConfig = {};
1915
+ if (preset.app.port) appConfig.port = String(preset.app.port);
1916
+ if (preset.app.node) appConfig.node = preset.app.node;
1917
+ if (preset.app.command) appConfig.command = preset.app.command;
1918
+ kv(appConfig);
1919
+ }
1920
+ if (preset.services && Object.keys(preset.services).length > 0) {
1921
+ subtitle("Services");
1922
+ list(Object.keys(preset.services));
1923
+ }
1924
+ } else {
1925
+ title("Available Presets");
1926
+ const presets3 = listPresets();
1927
+ list(presets3);
1928
+ console.log("");
1929
+ console.log('Run "dockcraft presets <name>" to see preset details');
1930
+ }
1931
+ }
1932
+
1933
+ // src/cli/index.ts
1934
+ var VERSION = "1.0.0";
1935
+ var commands = /* @__PURE__ */ new Map();
1936
+ commands.set("init", init);
1937
+ commands.set("generate", generate);
1938
+ commands.set("ports", ports);
1939
+ commands.set("presets", presets2);
1940
+ function showHelp(command) {
1941
+ if (command) {
1942
+ showCommandHelp(command);
1943
+ } else {
1944
+ showGeneralHelp();
1945
+ }
1946
+ }
1947
+ function showGeneralHelp() {
1948
+ console.log(`
1949
+ @oxog/dockcraft - Zero-Dependency Docker Orchestration Toolkit
1950
+
1951
+ VERSION:
1952
+ ${VERSION}
1953
+
1954
+ USAGE:
1955
+ dockcraft <command> [options]
1956
+
1957
+ COMMANDS:
1958
+ init Initialize a new dockcraft configuration
1959
+ generate Generate Docker files from config
1960
+ ports Check port availability
1961
+ presets List available presets
1962
+
1963
+ GLOBAL OPTIONS:
1964
+ -h, --help Show this help message
1965
+ -v, --version Show version information
1966
+
1967
+ Run "dockcraft <command> --help" for command-specific help.
1968
+ `);
1969
+ }
1970
+ function showCommandHelp(command) {
1971
+ switch (command) {
1972
+ case "init":
1973
+ console.log(`
1974
+ USAGE:
1975
+ dockcraft init [options]
1976
+
1977
+ OPTIONS:
1978
+ --preset <name> Use a preset configuration
1979
+ --name <name> Project name
1980
+ --port <port> App port
1981
+ --services <list> Comma-separated service list
1982
+ --output <dir> Output directory
1983
+ -y, --yes Skip prompts, use defaults
1984
+ `);
1985
+ break;
1986
+ case "generate":
1987
+ console.log(`
1988
+ USAGE:
1989
+ dockcraft generate [options]
1990
+
1991
+ OPTIONS:
1992
+ --config <file> Config file path (default: dockcraft.config.ts)
1993
+ --dry-run Preview without writing
1994
+ --force Overwrite existing files
1995
+ --output <dir> Output directory
1996
+ `);
1997
+ break;
1998
+ case "ports":
1999
+ console.log(`
2000
+ USAGE:
2001
+ dockcraft ports [options]
2002
+
2003
+ OPTIONS:
2004
+ --check <ports> Check specific ports (comma-separated)
2005
+ --range <start-end> Scan port range
2006
+ --json Output as JSON
2007
+ `);
2008
+ break;
2009
+ case "presets":
2010
+ console.log(`
2011
+ USAGE:
2012
+ dockcraft presets [name]
2013
+
2014
+ ARGUMENTS:
2015
+ name Preset name to show details
2016
+ `);
2017
+ break;
2018
+ default:
2019
+ console.log(`Unknown command: ${command}`);
2020
+ }
2021
+ }
2022
+ function showVersion() {
2023
+ console.log(`@oxog/dockcraft v${VERSION}`);
2024
+ }
2025
+ async function main(cliArgs = process.argv.slice(2)) {
2026
+ const args = parseArgs(cliArgs);
2027
+ if (!args.command) {
2028
+ if (args.flags.has("version") || args.flags.has("v")) {
2029
+ showVersion();
2030
+ return;
2031
+ }
2032
+ showHelp();
2033
+ return;
2034
+ }
2035
+ if (args.flags.has("help") || args.flags.has("h")) {
2036
+ showHelp(args.command);
2037
+ return;
2038
+ }
2039
+ if (args.flags.has("version") || args.flags.has("v")) {
2040
+ showVersion();
2041
+ return;
2042
+ }
2043
+ const handler = commands.get(args.command);
2044
+ if (!handler) {
2045
+ error(`Unknown command: ${args.command}`);
2046
+ console.log('Run "dockcraft --help" for usage information.');
2047
+ process.exit(1);
2048
+ }
2049
+ try {
2050
+ await handler(args);
2051
+ } catch (err) {
2052
+ error(err instanceof Error ? err.message : String(err));
2053
+ process.exit(1);
2054
+ }
2055
+ }
2056
+ if (import.meta.url === `file://${process.argv[1]}`) {
2057
+ main().catch((err) => {
2058
+ error(err instanceof Error ? err.message : String(err));
2059
+ process.exit(1);
2060
+ });
2061
+ }
2062
+ export {
2063
+ main
2064
+ };
2065
+ //# sourceMappingURL=index.js.map