@oxog/dockcraft 1.0.0 → 1.1.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/index.js CHANGED
@@ -1,8 +1,12 @@
1
+ #!/usr/bin/env node
1
2
  /**
2
- * @oxog/dockcraft - Zero-Dependency NPM Package
3
- * GitHub: https://github.com/ersinkoc/dockcraft
4
- * License: MIT
5
- */
3
+ * @oxog/dockcraft - Zero-Dependency NPM Package
4
+ * GitHub: https://github.com/ersinkoc/DockCraft
5
+ * License: MIT
6
+ */
7
+
8
+ // src/version.ts
9
+ var VERSION = "1.1.0";
6
10
 
7
11
  // src/cli/parser.ts
8
12
  function parseArgs(args) {
@@ -168,6 +172,9 @@ function kv(pairs) {
168
172
  }
169
173
  }
170
174
 
175
+ // src/cli/commands/init.ts
176
+ import { basename as basename2, join as join2 } from "path";
177
+
171
178
  // src/cli/prompts.ts
172
179
  import { createInterface } from "readline";
173
180
  async function prompt(question, defaultValue = "") {
@@ -179,10 +186,10 @@ async function prompt(question, defaultValue = "") {
179
186
  output: process.stdout
180
187
  });
181
188
  const query = defaultValue ? `${question} (${defaultValue}): ` : `${question}: `;
182
- return new Promise((resolve) => {
189
+ return new Promise((resolve2) => {
183
190
  rl.question(query, (answer) => {
184
191
  rl.close();
185
- resolve(answer || defaultValue);
192
+ resolve2(answer || defaultValue);
186
193
  });
187
194
  });
188
195
  }
@@ -195,10 +202,10 @@ async function confirm(question) {
195
202
  output: process.stdout
196
203
  });
197
204
  const query = `${question} (y/N): `;
198
- return new Promise((resolve) => {
205
+ return new Promise((resolve2) => {
199
206
  rl.question(query, (answer) => {
200
207
  rl.close();
201
- resolve(answer.toLowerCase() === "y" || answer.toLowerCase() === "yes");
208
+ resolve2(answer.toLowerCase() === "y" || answer.toLowerCase() === "yes");
202
209
  });
203
210
  });
204
211
  }
@@ -216,14 +223,14 @@ async function select(question, options) {
216
223
  console.log(` ${i + 1}. ${options[i]}`);
217
224
  }
218
225
  console.log("");
219
- return new Promise((resolve) => {
226
+ return new Promise((resolve2) => {
220
227
  rl.question(`Select (1-${options.length}): `, (answer) => {
221
228
  rl.close();
222
229
  const index = parseInt(answer ?? "0", 10) - 1;
223
230
  if (index >= 0 && index < options.length) {
224
- resolve(options[index] ?? "");
231
+ resolve2(options[index] ?? "");
225
232
  } else {
226
- resolve(options[0] ?? "");
233
+ resolve2(options[0] ?? "");
227
234
  }
228
235
  });
229
236
  });
@@ -243,12 +250,12 @@ async function multiselect(question, options) {
243
250
  console.log(` ${i + 1}. ${options[i]}`);
244
251
  }
245
252
  console.log("");
246
- return new Promise((resolve) => {
253
+ return new Promise((resolve2) => {
247
254
  rl.question(`Select (1-${options.length}): `, (answer) => {
248
255
  rl.close();
249
256
  const indices = (answer ?? "").split(",").map((s) => parseInt(s.trim(), 10) - 1);
250
257
  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] ?? ""]);
258
+ resolve2(selected.length > 0 ? selected : [options[0] ?? ""]);
252
259
  });
253
260
  });
254
261
  }
@@ -259,26 +266,28 @@ import { join, dirname, basename, extname, relative } from "path";
259
266
  async function ensureDir(path) {
260
267
  try {
261
268
  await fs.mkdir(path, { recursive: true });
262
- } catch (error3) {
263
- const err = error3;
269
+ } catch (error2) {
270
+ const err = error2;
264
271
  if (err.code !== "EEXIST") {
265
- throw error3;
272
+ throw error2;
266
273
  }
267
274
  }
268
275
  }
269
- async function writeFile(filePath, content) {
276
+ async function writeFile(filePath, content, mode) {
270
277
  const dir = dirname(filePath);
271
278
  await ensureDir(dir);
272
- const tempPath = join(dir, `.${basename(filePath)}.tmp`);
279
+ const suffix = `${process.pid}.${Date.now().toString(36)}.${Math.random().toString(36).slice(2)}`;
280
+ const tempPath = join(dir, `.${basename(filePath)}.${suffix}.tmp`);
273
281
  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 {
282
+ await fs.writeFile(tempPath, content, { encoding: "utf8", mode });
283
+ if (mode !== void 0) {
284
+ await fs.chmod(tempPath, mode);
280
285
  }
281
- throw error3;
286
+ await fs.rename(tempPath, filePath);
287
+ } catch (error2) {
288
+ await fs.unlink(tempPath).catch(() => {
289
+ });
290
+ throw error2;
282
291
  }
283
292
  }
284
293
  async function fileExists(filePath) {
@@ -528,53 +537,129 @@ registerPreset("nest-postgres", nestPostgresPreset);
528
537
  registerPreset("nest-mongo", nestMongoPreset);
529
538
  registerPreset("node-minimal", nodeMinimalPreset);
530
539
 
540
+ // src/utils/validation.ts
541
+ var MIN_PORT = 1;
542
+ var MAX_PORT = 65535;
543
+ function isPort(value) {
544
+ return typeof value === "number" && Number.isInteger(value) && value >= MIN_PORT && value <= MAX_PORT;
545
+ }
546
+ function isEnvVarName(value) {
547
+ if (typeof value !== "string") return false;
548
+ return /^[A-Z_][A-Z0-9_]*$/.test(value);
549
+ }
550
+ function isVersion(value) {
551
+ if (typeof value !== "string") return false;
552
+ return /^\w[\w.-]{0,127}$/.test(value);
553
+ }
554
+ function isProjectName(value) {
555
+ if (typeof value !== "string") return false;
556
+ if (value.length === 0 || value.length > 100) return false;
557
+ return /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(value);
558
+ }
559
+ function isComposeServiceName(value) {
560
+ if (typeof value !== "string") return false;
561
+ return /^[a-zA-Z0-9][\w.-]{0,62}$/.test(value);
562
+ }
563
+ var DOMAIN_COMPONENT = "(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])";
564
+ var DOMAIN = `${DOMAIN_COMPONENT}(?:\\.${DOMAIN_COMPONENT})*(?::[0-9]+)?`;
565
+ var PATH_COMPONENT = "[a-z0-9]+(?:(?:[._]|__|[-]+)[a-z0-9]+)*";
566
+ var TAG = "\\w[\\w.-]{0,127}";
567
+ var DIGEST = "[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*:[0-9a-fA-F]{32,}";
568
+ var IMAGE_REFERENCE = new RegExp(
569
+ `^(?:${DOMAIN}/)?${PATH_COMPONENT}(?:/${PATH_COMPONENT})*(?::${TAG})?(?:@${DIGEST})?$`
570
+ );
571
+ function isDockerImage(value) {
572
+ if (typeof value !== "string") return false;
573
+ if (value.length === 0 || value.length > 255) return false;
574
+ return IMAGE_REFERENCE.test(value);
575
+ }
576
+ function isHealthcheckPath(value) {
577
+ if (typeof value !== "string") return false;
578
+ return value.length <= 2048 && /^\/[\w\-.~%/?=&+,;:@]*$/.test(value);
579
+ }
580
+ function isSingleLine(value) {
581
+ return typeof value === "string" && !/[\r\n\0]/.test(value);
582
+ }
583
+ function isContainerPath(value) {
584
+ return typeof value === "string" && /^\/[\w./-]*$/.test(value);
585
+ }
586
+ function namedVolume(spec) {
587
+ const index = spec.indexOf(":");
588
+ if (index <= 0) return void 0;
589
+ const source = spec.slice(0, index);
590
+ return /^[a-zA-Z0-9][\w.-]*$/.test(source) ? source : void 0;
591
+ }
592
+
531
593
  // src/cli/commands/init.ts
594
+ var INIT_CONFIG_FILE = "dockcraft.config.mts";
595
+ var INIT_SERVICES = ["postgres", "mysql", "mongo", "redis"];
596
+ function defaultProjectName(dir) {
597
+ const name = basename2(dir).replace(/[^a-zA-Z0-9_-]/g, "-").replace(/^[^a-zA-Z]+/, "");
598
+ return isProjectName(name) ? name : "my-app";
599
+ }
532
600
  async function init(args) {
533
601
  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
602
  const skipPrompts = getBooleanFlag(args, "yes");
603
+ const force = getBooleanFlag(args, "force");
604
+ const ask = (question, defaultValue) => skipPrompts ? Promise.resolve(defaultValue) : prompt(question, defaultValue);
605
+ const name = getOption(args, "name") || await ask("Project name", defaultProjectName(process.cwd()));
606
+ if (!isProjectName(name)) {
607
+ throw new Error(
608
+ `Invalid project name '${name}'. Must start with a letter and contain only letters, numbers, hyphens, and underscores.`
609
+ );
610
+ }
611
+ const preset = getOption(args, "preset");
612
+ const presets3 = listPresets();
613
+ if (preset && !presets3.includes(preset)) {
614
+ throw new Error(`Unknown preset '${preset}'. Available presets: ${presets3.join(", ")}`);
615
+ }
616
+ const portInput = getOption(args, "port") || await ask("App port", "3000");
617
+ const port = portInput === "auto" ? "auto" : /^\d+$/.test(portInput) ? Number(portInput) : NaN;
618
+ if (port !== "auto" && !isPort(port)) {
619
+ throw new Error(`Invalid port '${portInput}'. Must be a number between 1-65535 or 'auto'.`);
620
+ }
621
+ const outputDir = getOption(args, "output") || await ask("Output directory", "./");
540
622
  info(`Creating config for "${name}"`);
541
623
  let selectedPreset = preset;
542
624
  if (!selectedPreset && !skipPrompts) {
543
- const presets3 = listPresets();
544
625
  const usePreset = await confirm("Use a preset?");
545
626
  if (usePreset) {
546
- const presetName = await select("Select preset:", presets3);
547
- selectedPreset = presetName;
627
+ selectedPreset = await select("Select preset:", presets3);
548
628
  }
549
629
  }
550
630
  let selectedServices = [];
551
- if (servicesOption) {
631
+ if (getOption(args, "services")) {
552
632
  selectedServices = parseList(args, "services");
553
633
  } else if (!skipPrompts && !selectedPreset) {
554
- const availableServices = ["postgres", "mysql", "mongo", "redis"];
555
- selectedServices = await multiselect("Select services:", availableServices);
634
+ selectedServices = await multiselect("Select services:", [...INIT_SERVICES]);
635
+ }
636
+ const unknown = selectedServices.filter((s) => !INIT_SERVICES.includes(s));
637
+ if (unknown.length > 0) {
638
+ throw new Error(`Unknown service(s): ${unknown.join(", ")}. Available services: ${INIT_SERVICES.join(", ")}`);
556
639
  }
557
- const config = generateConfig(name, selectedPreset, selectedServices, port);
558
- const configPath = `${outputDir}/dockcraft.config.ts`;
559
- await writeFile(configPath, config);
640
+ const configPath = join2(outputDir, INIT_CONFIG_FILE);
641
+ if (!force && await fileExists(configPath)) {
642
+ throw new Error(`${configPath} already exists. Use --force to overwrite it.`);
643
+ }
644
+ await writeFile(configPath, generateConfig(name, selectedPreset, selectedServices, port));
560
645
  success(`Config file created: ${configPath}`);
561
646
  info('Run "dockcraft generate" to generate Docker files');
562
647
  }
563
648
  function generateConfig(name, preset, services2, port) {
564
- let content = `import { dockcraft } from '@oxog/dockcraft';
649
+ let content = `import type { DockcraftConfig } from '@oxog/dockcraft';
565
650
 
566
651
  `;
567
- content += `await dockcraft({
652
+ content += `export default {
568
653
  `;
569
- content += ` name: '${name}',
654
+ content += ` name: ${JSON.stringify(name)},
570
655
  `;
571
656
  if (preset) {
572
- content += ` preset: '${preset}',
657
+ content += ` preset: ${JSON.stringify(preset)},
573
658
  `;
574
659
  }
575
660
  content += ` app: {
576
661
  `;
577
- content += ` port: ${port},
662
+ content += ` port: ${JSON.stringify(port)},
578
663
  `;
579
664
  content += ` },
580
665
  `;
@@ -582,21 +667,69 @@ function generateConfig(name, preset, services2, port) {
582
667
  content += ` services: {
583
668
  `;
584
669
  for (const service of services2) {
585
- content += ` ${service}: {},
670
+ content += ` ${JSON.stringify(service)}: {},
586
671
  `;
587
672
  }
588
673
  content += ` },
589
674
  `;
590
675
  }
591
- content += `});
676
+ content += `} satisfies DockcraftConfig;
592
677
  `;
593
678
  return content;
594
679
  }
595
680
 
681
+ // src/types.ts
682
+ var DockcraftError = class extends Error {
683
+ constructor(message, code) {
684
+ super(message);
685
+ this.code = code;
686
+ this.name = "DockcraftError";
687
+ }
688
+ };
689
+ var ConfigError = class extends DockcraftError {
690
+ constructor(message, code = "CONFIG_ERROR") {
691
+ super(message, code);
692
+ this.name = "ConfigError";
693
+ }
694
+ };
695
+ var ValidationError = class extends DockcraftError {
696
+ constructor(message, errors, code = "VALIDATION_ERROR") {
697
+ super(message, code);
698
+ this.errors = errors;
699
+ this.name = "ValidationError";
700
+ }
701
+ };
702
+ var PresetNotFoundError = class extends DockcraftError {
703
+ constructor(name, code = "PRESET_NOT_FOUND") {
704
+ super(`Preset '${name}' not found`, code);
705
+ this.name = "PresetNotFoundError";
706
+ }
707
+ };
708
+ var ServiceNotFoundError = class extends DockcraftError {
709
+ constructor(name, code = "SERVICE_NOT_FOUND") {
710
+ super(`Service '${name}' not found`, code);
711
+ this.name = "ServiceNotFoundError";
712
+ }
713
+ };
714
+
715
+ // src/services/image.ts
716
+ function variantImage(repository, version, variant) {
717
+ if (version === "latest") {
718
+ return `${repository}:${variant}`;
719
+ }
720
+ if (version === variant || version.includes("-")) {
721
+ return `${repository}:${version}`;
722
+ }
723
+ return `${repository}:${version}-${variant}`;
724
+ }
725
+ function urlPart(value) {
726
+ return encodeURIComponent(value);
727
+ }
728
+
596
729
  // src/services/postgres.ts
597
730
  var postgresService = {
598
731
  name: "postgres",
599
- image: (version) => `postgres:${version}-alpine`,
732
+ image: (version) => variantImage("postgres", version, "alpine"),
600
733
  defaultPort: 5432,
601
734
  defaultVersion: "16",
602
735
  env: {
@@ -613,7 +746,7 @@ var postgresService = {
613
746
  const database = config.env.POSTGRES_DB || "myapp";
614
747
  const host = config.name;
615
748
  const port = config.port;
616
- return `postgres://${user}:${password}@${host}:${port}/${database}`;
749
+ return `postgres://${urlPart(user)}:${urlPart(password)}@${host}:${port}/${urlPart(database)}`;
617
750
  }
618
751
  };
619
752
 
@@ -638,7 +771,7 @@ var mysqlService = {
638
771
  const database = config.env.MYSQL_DATABASE || "myapp";
639
772
  const host = config.name;
640
773
  const port = config.port;
641
- return `mysql://${user}:${password}@${host}:${port}/${database}`;
774
+ return `mysql://${urlPart(user)}:${urlPart(password)}@${host}:${port}/${urlPart(database)}`;
642
775
  }
643
776
  };
644
777
 
@@ -662,14 +795,14 @@ var mongoService = {
662
795
  const database = config.env.MONGO_INITDB_DATABASE || "myapp";
663
796
  const host = config.name;
664
797
  const port = config.port;
665
- return `mongodb://${user}:${password}@${host}:${port}/${database}`;
798
+ return `mongodb://${urlPart(user)}:${urlPart(password)}@${host}:${port}/${urlPart(database)}?authSource=admin`;
666
799
  }
667
800
  };
668
801
 
669
802
  // src/services/redis.ts
670
803
  var redisService = {
671
804
  name: "redis",
672
- image: (version) => `redis:${version}-alpine`,
805
+ image: (version) => variantImage("redis", version, "alpine"),
673
806
  defaultPort: 6379,
674
807
  defaultVersion: "7",
675
808
  env: {},
@@ -679,7 +812,9 @@ var redisService = {
679
812
  connectionString: (config) => {
680
813
  const host = config.name;
681
814
  const port = config.port;
682
- return `redis://${host}:${port}`;
815
+ const password = config.env.REDIS_PASSWORD;
816
+ const auth = password ? `:${urlPart(password)}@` : "";
817
+ return `redis://${auth}${host}:${port}`;
683
818
  }
684
819
  };
685
820
 
@@ -697,12 +832,13 @@ registerService(mongoService);
697
832
  registerService(redisService);
698
833
 
699
834
  // src/utils/merge.ts
835
+ var UNSAFE_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
700
836
  function deepMerge(...objects) {
701
837
  const result = {};
702
838
  for (const obj of objects) {
703
839
  if (obj === null || typeof obj !== "object") continue;
704
840
  for (const [key, value] of Object.entries(obj)) {
705
- if (value === void 0) continue;
841
+ if (value === void 0 || UNSAFE_KEYS.has(key)) continue;
706
842
  if (value && typeof value === "object" && !Array.isArray(value) && result[key] && typeof result[key] === "object" && !Array.isArray(result[key])) {
707
843
  result[key] = deepMerge(result[key], value);
708
844
  } else {
@@ -716,21 +852,30 @@ function deepMerge(...objects) {
716
852
  // src/ports/scanner.ts
717
853
  import { createServer } from "net";
718
854
  async function isPortAvailable(port) {
719
- return new Promise((resolve) => {
855
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
856
+ throw new RangeError(`Invalid port: ${String(port)}. Must be an integer between 1 and 65535.`);
857
+ }
858
+ return new Promise((resolve2) => {
720
859
  const server = createServer();
860
+ let settled = false;
861
+ const finish = (available) => {
862
+ if (settled) return;
863
+ settled = true;
864
+ clearTimeout(timer);
865
+ resolve2(available);
866
+ };
867
+ const timer = setTimeout(() => {
868
+ server.close();
869
+ finish(false);
870
+ }, 1e3);
871
+ timer.unref();
721
872
  server.once("error", () => {
722
- resolve(false);
873
+ finish(false);
723
874
  });
724
875
  server.once("listening", () => {
725
- server.close(() => {
726
- resolve(true);
727
- });
876
+ server.close(() => finish(true));
728
877
  });
729
878
  server.listen(port, "127.0.0.1");
730
- setTimeout(() => {
731
- server.close();
732
- resolve(false);
733
- }, 1e3);
734
879
  });
735
880
  }
736
881
  async function checkPorts(ports2) {
@@ -773,24 +918,28 @@ async function resolvePort(options = {}) {
773
918
  case "range":
774
919
  if (range) {
775
920
  const [start, end = start + 100] = range;
776
- const port2 = await findAvailablePortInRange(start, end);
777
- if (port2 !== void 0) {
778
- return port2;
921
+ const port = await findAvailablePortInRange(start, end);
922
+ if (port !== void 0) {
923
+ return port;
779
924
  }
780
925
  throw new Error(`No available port in range ${start}-${end}`);
781
926
  }
782
927
  // Fall through to auto if no range specified
783
928
  case "auto":
784
- default:
929
+ default: {
785
930
  const port = await findNextAvailablePort(preferred);
786
931
  if (port !== void 0) {
787
932
  return port;
788
933
  }
789
934
  throw new Error(`No available port found starting from ${preferred}`);
935
+ }
790
936
  }
791
937
  }
792
938
 
793
939
  // src/core/config.ts
940
+ import { existsSync } from "fs";
941
+ import { isAbsolute, resolve } from "path";
942
+ import { pathToFileURL } from "url";
794
943
  var DEFAULT_APP_CONFIG = {
795
944
  port: 3e3,
796
945
  node: "20-alpine",
@@ -801,9 +950,9 @@ var DEFAULT_APP_CONFIG = {
801
950
  volumes: [],
802
951
  multiStage: true
803
952
  };
804
- function normalizeAppConfig(config) {
953
+ function normalizeAppConfig(config = {}) {
805
954
  return {
806
- port: config.port === "auto" ? 3e3 : config.port,
955
+ port: typeof config.port === "number" ? config.port : DEFAULT_APP_CONFIG.port,
807
956
  node: config.node ?? DEFAULT_APP_CONFIG.node,
808
957
  workdir: config.workdir ?? DEFAULT_APP_CONFIG.workdir,
809
958
  command: config.command ?? DEFAULT_APP_CONFIG.command,
@@ -825,29 +974,57 @@ function normalizeConfig(config) {
825
974
  return {
826
975
  name: config.name,
827
976
  preset: config.preset,
828
- app: config.app,
977
+ app: config.app ?? {},
829
978
  services: config.services ?? {},
830
979
  output: normalizeOutputConfig(config.output),
831
980
  plugins: config.plugins ?? []
832
981
  };
833
982
  }
834
- async function loadConfig(configPath) {
983
+ var DEFAULT_CONFIG_FILES = [
984
+ "dockcraft.config.ts",
985
+ "dockcraft.config.mts",
986
+ "dockcraft.config.js",
987
+ "dockcraft.config.mjs",
988
+ "dockcraft.config.cjs"
989
+ ];
990
+ function findConfigFile(cwd = process.cwd()) {
991
+ for (const name of DEFAULT_CONFIG_FILES) {
992
+ const candidate = resolve(cwd, name);
993
+ if (existsSync(candidate)) return candidate;
994
+ }
995
+ return void 0;
996
+ }
997
+ async function loadConfig(configPath, cwd = process.cwd()) {
998
+ const url = configPath instanceof URL ? configPath : pathToFileURL(isAbsolute(configPath) ? configPath : resolve(cwd, configPath));
999
+ let module;
835
1000
  try {
836
- const module = await import(configPath.toString());
837
- const config = module.default ?? module;
838
- return config;
839
- } catch (error3) {
1001
+ module = await import(url.href);
1002
+ } catch (error2) {
1003
+ const message = error2 instanceof Error ? error2.message : String(error2);
1004
+ const code = error2.code;
1005
+ let hint = "";
1006
+ if (code === "ERR_UNKNOWN_FILE_EXTENSION") {
1007
+ hint = " (this Node.js version cannot load TypeScript files; use dockcraft.config.mjs or Node.js >= 22.18)";
1008
+ } else if (/Cannot use import statement outside a module|Unexpected token 'export'/.test(message)) {
1009
+ hint = " (the file uses ES module syntax in a CommonJS package; rename it to .mts / .mjs)";
1010
+ }
1011
+ throw new Error(`Failed to load config from ${String(configPath)}: ${message}${hint}`);
1012
+ }
1013
+ const config = module.default;
1014
+ if (!config || typeof config !== "object") {
840
1015
  throw new Error(
841
- `Failed to load config from ${configPath}: ${error3 instanceof Error ? error3.message : String(error3)}`
1016
+ `Config file ${String(configPath)} must export the configuration as its default export, e.g. \`export default defineConfig({ name: "my-app" })\``
842
1017
  );
843
1018
  }
1019
+ return config;
844
1020
  }
845
1021
 
846
1022
  // src/core/resolver.ts
1023
+ var REDIS_AUTH_COMMAND = `sh -c 'exec redis-server --requirepass "$$REDIS_PASSWORD"'`;
847
1024
  function mergePreset(config, presetName) {
848
1025
  const preset = getPreset(presetName);
849
1026
  if (!preset) {
850
- throw new Error(`Preset '${presetName}' not found`);
1027
+ throw new PresetNotFoundError(presetName);
851
1028
  }
852
1029
  const merged = deepMerge(
853
1030
  {
@@ -860,55 +1037,65 @@ function mergePreset(config, presetName) {
860
1037
  );
861
1038
  return merged;
862
1039
  }
863
- async function resolveServiceConfig(name, config, projectName) {
1040
+ async function resolveServicePorts(portConfig, containerPort) {
1041
+ if (portConfig === "auto") {
1042
+ return {
1043
+ port: containerPort,
1044
+ hostPort: await resolvePort({ preferred: containerPort, strategy: "auto" })
1045
+ };
1046
+ }
1047
+ if (typeof portConfig === "number") {
1048
+ return { port: containerPort, hostPort: portConfig };
1049
+ }
1050
+ if (portConfig && typeof portConfig === "object") {
1051
+ const startPort = portConfig.start ?? containerPort;
1052
+ const endPort = portConfig.end ?? startPort + 100;
1053
+ return {
1054
+ port: containerPort,
1055
+ hostPort: await resolvePort({ preferred: startPort, strategy: "range", range: [startPort, endPort] })
1056
+ };
1057
+ }
1058
+ return { port: containerPort };
1059
+ }
1060
+ async function resolveServiceConfig(name, config, projectName, definitions) {
864
1061
  if ("image" in config && config.image) {
865
1062
  return resolveCustomService(name, config);
866
1063
  }
867
- const definition = getService(name);
1064
+ const definition = definitions?.get(name) ?? getService(name);
868
1065
  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;
1066
+ throw new ServiceNotFoundError(name);
886
1067
  }
1068
+ const { port, hostPort } = await resolveServicePorts(config.port, definition.defaultPort);
887
1069
  const version = config.version ?? definition.defaultVersion;
888
1070
  const image = typeof definition.image === "function" ? definition.image(version) : definition.image;
889
1071
  const env = { ...definition.env, ...config.env };
1072
+ let command = config.command;
890
1073
  if (name === "postgres") {
891
1074
  const pgConfig = config;
892
1075
  if (pgConfig.database) env.POSTGRES_DB = pgConfig.database;
893
1076
  if (pgConfig.user) env.POSTGRES_USER = pgConfig.user;
894
1077
  if (pgConfig.password) env.POSTGRES_PASSWORD = pgConfig.password;
895
- if (!env.POSTGRES_DB) env.POSTGRES_DB = projectName;
1078
+ if (!pgConfig.database && !config.env?.POSTGRES_DB) env.POSTGRES_DB = projectName;
896
1079
  } else if (name === "mysql") {
897
1080
  const mysqlConfig = config;
898
1081
  if (mysqlConfig.database) env.MYSQL_DATABASE = mysqlConfig.database;
899
1082
  if (mysqlConfig.user) env.MYSQL_USER = mysqlConfig.user;
900
1083
  if (mysqlConfig.password) env.MYSQL_PASSWORD = mysqlConfig.password;
901
1084
  if (mysqlConfig.rootPassword) env.MYSQL_ROOT_PASSWORD = mysqlConfig.rootPassword;
902
- if (!env.MYSQL_DATABASE) env.MYSQL_DATABASE = projectName;
1085
+ if (!mysqlConfig.database && !config.env?.MYSQL_DATABASE) env.MYSQL_DATABASE = projectName;
903
1086
  } else if (name === "mongo") {
904
1087
  const mongoConfig = config;
905
1088
  if (mongoConfig.database) env.MONGO_INITDB_DATABASE = mongoConfig.database;
906
1089
  if (mongoConfig.user) env.MONGO_INITDB_ROOT_USERNAME = mongoConfig.user;
907
1090
  if (mongoConfig.password) env.MONGO_INITDB_ROOT_PASSWORD = mongoConfig.password;
908
- if (!env.MONGO_INITDB_DATABASE) env.MONGO_INITDB_DATABASE = projectName;
1091
+ if (!mongoConfig.database && !config.env?.MONGO_INITDB_DATABASE) env.MONGO_INITDB_DATABASE = projectName;
909
1092
  } else if (name === "redis") {
910
1093
  const redisConfig = config;
911
1094
  if (redisConfig.password) env.REDIS_PASSWORD = redisConfig.password;
1095
+ if (env.REDIS_PASSWORD) {
1096
+ env.REDISCLI_AUTH = env.REDIS_PASSWORD;
1097
+ command ??= REDIS_AUTH_COMMAND;
1098
+ }
912
1099
  }
913
1100
  const volumes = [...definition.volumes ?? [], ...config.volumes ?? []];
914
1101
  const resolvedConfig = {
@@ -918,7 +1105,7 @@ async function resolveServiceConfig(name, config, projectName) {
918
1105
  hostPort,
919
1106
  env,
920
1107
  volumes,
921
- command: config.command,
1108
+ command,
922
1109
  healthcheck: definition.healthcheck,
923
1110
  ports: definition.ports
924
1111
  };
@@ -928,53 +1115,53 @@ async function resolveServiceConfig(name, config, projectName) {
928
1115
  return resolvedConfig;
929
1116
  }
930
1117
  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;
1118
+ let containerPort = 80;
1119
+ if (typeof config.port === "number") {
1120
+ containerPort = config.port;
1121
+ } else if (config.port && typeof config.port === "object" && config.port.start) {
1122
+ containerPort = config.port.start;
947
1123
  }
1124
+ const { port, hostPort } = await resolveServicePorts(config.port, containerPort);
948
1125
  return {
949
1126
  name,
950
1127
  image: config.image,
951
1128
  port,
952
1129
  hostPort,
953
- env: config.env ?? {},
954
- volumes: config.volumes ?? [],
1130
+ env: { ...config.env },
1131
+ volumes: [...config.volumes ?? []],
955
1132
  command: config.command,
956
- healthcheck: config.command,
1133
+ healthcheck: config.healthcheck,
957
1134
  ports: []
958
1135
  };
959
1136
  }
1137
+ function pluginServiceDefinitions(plugins) {
1138
+ const definitions = /* @__PURE__ */ new Map();
1139
+ for (const plugin of plugins ?? []) {
1140
+ for (const [name, def] of Object.entries(plugin.services ?? {})) {
1141
+ definitions.set(name, { ...def, name });
1142
+ }
1143
+ }
1144
+ return definitions;
1145
+ }
960
1146
  async function resolveConfig(config) {
961
1147
  let finalConfig = config;
962
1148
  if (config.preset) {
963
1149
  finalConfig = mergePreset(config, config.preset);
964
1150
  }
965
1151
  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 });
1152
+ const appConfig = finalConfig.app ?? {};
1153
+ const appPort = appConfig.port === "auto" ? await resolvePort({ preferred: 3e3, strategy: "auto" }) : appConfig.port;
1154
+ const app = normalizeAppConfig({ ...appConfig, port: appPort });
1155
+ const definitions = pluginServiceDefinitions(finalConfig.plugins);
968
1156
  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
- }
1157
+ for (const [name, serviceConfig] of Object.entries(finalConfig.services ?? {})) {
1158
+ if (serviceConfig) {
1159
+ services2[name] = await resolveServiceConfig(
1160
+ name,
1161
+ serviceConfig,
1162
+ finalConfig.name,
1163
+ definitions
1164
+ );
978
1165
  }
979
1166
  }
980
1167
  return {
@@ -985,43 +1172,32 @@ async function resolveConfig(config) {
985
1172
  };
986
1173
  }
987
1174
 
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
1175
  // src/core/validator.ts
1176
+ var VALID_OUTPUT_FILES = ["dockerfile", "compose", "dockerignore", "env", "scripts", "makefile"];
1010
1177
  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;
1178
+ if (isProjectName(name)) return [];
1179
+ return [{
1180
+ code: "INVALID_NAME",
1181
+ message: `Invalid project name '${String(name)}'. Must start with a letter and contain only letters, numbers, hyphens, and underscores.`,
1182
+ path: "name",
1183
+ value: name
1184
+ }];
1185
+ }
1186
+ function validateStringList(value, path) {
1187
+ if (value === void 0) return [];
1188
+ if (!Array.isArray(value)) {
1189
+ return [{ code: "INVALID_TYPE", message: `'${path}' must be an array of strings.`, path, value }];
1190
+ }
1191
+ return value.filter((item) => !isSingleLine(item) || item === "").map((item) => ({
1192
+ code: "INVALID_VALUE",
1193
+ message: `Invalid entry ${JSON.stringify(item)} in '${path}'. Entries must be non-empty single-line strings.`,
1194
+ path,
1195
+ value: item
1196
+ }));
1021
1197
  }
1022
1198
  function validateAppConfig(config) {
1023
1199
  const errors = [];
1024
- if (config.port !== "auto" && !isPort(config.port)) {
1200
+ if (config.port !== void 0 && config.port !== "auto" && !isPort(config.port)) {
1025
1201
  errors.push({
1026
1202
  code: "INVALID_PORT",
1027
1203
  message: `Invalid app port '${String(config.port)}'. Must be a number between 1-65535 or 'auto'.`,
@@ -1032,54 +1208,163 @@ function validateAppConfig(config) {
1032
1208
  if (config.node !== void 0 && !isVersion(config.node)) {
1033
1209
  errors.push({
1034
1210
  code: "INVALID_VERSION",
1035
- message: `Invalid Node.js version '${config.node}'.`,
1211
+ message: `Invalid Node.js version '${String(config.node)}'. Must be a valid Docker image tag.`,
1036
1212
  path: "app.node",
1037
1213
  value: config.node
1038
1214
  });
1039
1215
  }
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
- });
1216
+ if (config.workdir !== void 0 && !isContainerPath(config.workdir)) {
1217
+ errors.push({
1218
+ code: "INVALID_WORKDIR",
1219
+ message: `Invalid workdir '${String(config.workdir)}'. Must be an absolute path made of letters, numbers, '.', '_', '-' and '/'.`,
1220
+ path: "app.workdir",
1221
+ value: config.workdir
1222
+ });
1223
+ }
1224
+ for (const key of ["command", "buildCommand"]) {
1225
+ const value = config[key];
1226
+ if (value !== void 0 && !isSingleLine(value)) {
1227
+ errors.push({
1228
+ code: "INVALID_COMMAND",
1229
+ message: `Invalid app.${key}: must be a single-line string.`,
1230
+ path: `app.${key}`,
1231
+ value
1232
+ });
1233
+ }
1234
+ }
1235
+ if (config.command !== void 0 && config.command.trim() === "") {
1236
+ errors.push({
1237
+ code: "INVALID_COMMAND",
1238
+ message: "Invalid app.command: must not be empty.",
1239
+ path: "app.command",
1240
+ value: config.command
1241
+ });
1242
+ }
1243
+ if (config.healthcheck !== void 0 && !isHealthcheckPath(config.healthcheck)) {
1244
+ errors.push({
1245
+ code: "INVALID_HEALTHCHECK",
1246
+ message: `Invalid health check path '${String(config.healthcheck)}'. Must start with '/' and contain only URL path characters (no quotes, spaces, '$' or backslashes).`,
1247
+ path: "app.healthcheck",
1248
+ value: config.healthcheck
1249
+ });
1250
+ }
1251
+ if (config.env !== void 0) {
1252
+ if (!Array.isArray(config.env)) {
1253
+ errors.push({ code: "INVALID_TYPE", message: `'app.env' must be an array of variable names.`, path: "app.env", value: config.env });
1254
+ } else {
1255
+ for (const envVar of config.env) {
1256
+ if (!isEnvVarName(envVar)) {
1257
+ errors.push({
1258
+ code: "INVALID_ENV_VAR",
1259
+ message: `Invalid environment variable name '${String(envVar)}'. Must be uppercase letters, numbers, and underscores.`,
1260
+ path: "app.env",
1261
+ value: envVar
1262
+ });
1263
+ }
1049
1264
  }
1050
1265
  }
1051
1266
  }
1267
+ errors.push(...validateStringList(config.volumes, "app.volumes"));
1052
1268
  return errors;
1053
1269
  }
1270
+ function validateServicePort(name, port) {
1271
+ if (port === void 0 || port === "auto" || isPort(port)) return [];
1272
+ if (port && typeof port === "object" && !Array.isArray(port)) {
1273
+ const { start, end } = port;
1274
+ if (isPort(start) && (end === void 0 || isPort(end) && end >= start)) {
1275
+ return [];
1276
+ }
1277
+ }
1278
+ return [{
1279
+ code: "INVALID_PORT",
1280
+ message: `Invalid port configuration for service '${name}'. Must be a port number (1-65535), 'auto', or a range { start, end } with start <= end.`,
1281
+ path: `services.${name}.port`,
1282
+ value: port
1283
+ }];
1284
+ }
1054
1285
  function validateServiceConfig(name, config) {
1055
1286
  const errors = [];
1056
- if (config.version !== void 0 && !isVersion(config.version)) {
1287
+ if (!isComposeServiceName(name)) {
1288
+ errors.push({
1289
+ code: "INVALID_SERVICE_NAME",
1290
+ message: `Invalid service name '${name}'. Must start with a letter or digit and contain only letters, digits, '.', '_' and '-'.`,
1291
+ path: `services.${name}`,
1292
+ value: name
1293
+ });
1294
+ }
1295
+ if (typeof config !== "object" || config === null || Array.isArray(config)) {
1296
+ errors.push({
1297
+ code: "INVALID_TYPE",
1298
+ message: `Service '${name}' must be configured with an object.`,
1299
+ path: `services.${name}`,
1300
+ value: config
1301
+ });
1302
+ return errors;
1303
+ }
1304
+ const svc = config;
1305
+ if (svc.version !== void 0 && !isVersion(svc.version)) {
1057
1306
  errors.push({
1058
1307
  code: "INVALID_VERSION",
1059
- message: `Invalid version '${config.version}' for service '${name}'.`,
1308
+ message: `Invalid version '${String(svc.version)}' for service '${name}'. Must be a valid Docker image tag.`,
1060
1309
  path: `services.${name}.version`,
1061
- value: config.version
1310
+ value: svc.version
1062
1311
  });
1063
1312
  }
1064
- if (config.port !== void 0 && config.port !== "auto" && typeof config.port !== "number" && typeof config.port !== "object") {
1313
+ if (svc.image !== void 0 && !isDockerImage(svc.image)) {
1065
1314
  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
1315
+ code: "INVALID_IMAGE",
1316
+ message: `Invalid image '${String(svc.image)}' for service '${name}'. Must be a Docker image reference such as 'elasticsearch:8.11.0'.`,
1317
+ path: `services.${name}.image`,
1318
+ value: svc.image
1070
1319
  });
1071
1320
  }
1321
+ errors.push(...validateServicePort(name, svc.port));
1322
+ if (svc.env !== void 0) {
1323
+ if (typeof svc.env !== "object" || svc.env === null || Array.isArray(svc.env)) {
1324
+ errors.push({ code: "INVALID_TYPE", message: `'services.${name}.env' must be an object of strings.`, path: `services.${name}.env`, value: svc.env });
1325
+ } else {
1326
+ for (const [key, value] of Object.entries(svc.env)) {
1327
+ if (key === "" || /[=\s]/.test(key) || typeof value !== "string") {
1328
+ errors.push({
1329
+ code: "INVALID_ENV_VAR",
1330
+ message: `Invalid environment variable '${key}' for service '${name}'. Names must not be empty or contain '=' or whitespace, and values must be strings.`,
1331
+ path: `services.${name}.env.${key}`,
1332
+ value
1333
+ });
1334
+ }
1335
+ }
1336
+ }
1337
+ }
1338
+ for (const key of ["user", "password", "database", "rootPassword", "command", "healthcheck"]) {
1339
+ const value = svc[key];
1340
+ if (value !== void 0 && typeof value !== "string") {
1341
+ errors.push({
1342
+ code: "INVALID_TYPE",
1343
+ message: `'services.${name}.${key}' must be a string.`,
1344
+ path: `services.${name}.${key}`,
1345
+ value
1346
+ });
1347
+ }
1348
+ }
1349
+ errors.push(...validateStringList(svc.volumes, `services.${name}.volumes`));
1072
1350
  return errors;
1073
1351
  }
1074
1352
  function validateOutputConfig(config) {
1075
1353
  const errors = [];
1076
- if (config?.files) {
1077
- const validFiles = ["dockerfile", "compose", "dockerignore", "env", "scripts", "makefile"];
1354
+ if (config.dir !== void 0 && (typeof config.dir !== "string" || config.dir === "" || config.dir.includes("\0"))) {
1355
+ errors.push({
1356
+ code: "INVALID_OUTPUT_DIR",
1357
+ message: "output.dir must be a non-empty path.",
1358
+ path: "output.dir",
1359
+ value: config.dir
1360
+ });
1361
+ }
1362
+ if (config.files) {
1078
1363
  for (const file of config.files) {
1079
- if (!validFiles.includes(file)) {
1364
+ if (!VALID_OUTPUT_FILES.includes(file)) {
1080
1365
  errors.push({
1081
1366
  code: "INVALID_OUTPUT_FILE",
1082
- message: `Invalid output file '${file}'. Must be one of: ${validFiles.join(", ")}.`,
1367
+ message: `Invalid output file '${String(file)}'. Must be one of: ${VALID_OUTPUT_FILES.join(", ")}.`,
1083
1368
  path: "output.files",
1084
1369
  value: file
1085
1370
  });
@@ -1090,13 +1375,19 @@ function validateOutputConfig(config) {
1090
1375
  }
1091
1376
  function validateConfig(config) {
1092
1377
  const errors = [];
1378
+ if (typeof config !== "object" || config === null) {
1379
+ return {
1380
+ valid: false,
1381
+ errors: [{ code: "INVALID_CONFIG", message: "Configuration must be an object.", value: config }]
1382
+ };
1383
+ }
1093
1384
  errors.push(...validateProjectName(config.name));
1094
1385
  if (config.app) {
1095
1386
  errors.push(...validateAppConfig(config.app));
1096
1387
  }
1097
1388
  if (config.services) {
1098
1389
  for (const [name, serviceConfig] of Object.entries(config.services)) {
1099
- if (serviceConfig) {
1390
+ if (serviceConfig !== void 0) {
1100
1391
  errors.push(...validateServiceConfig(name, serviceConfig));
1101
1392
  }
1102
1393
  }
@@ -1111,18 +1402,23 @@ function validateConfig(config) {
1111
1402
  }
1112
1403
  function validateResolvedConfig(config) {
1113
1404
  const errors = [];
1114
- const usedPorts = /* @__PURE__ */ new Set();
1115
- usedPorts.add(config.app.port);
1405
+ const usedPorts = /* @__PURE__ */ new Map();
1406
+ usedPorts.set(config.app.port, "app");
1116
1407
  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
- });
1408
+ const published = [serviceConfig.hostPort ?? serviceConfig.port, ...serviceConfig.ports ?? []];
1409
+ for (const port of published) {
1410
+ const owner = usedPorts.get(port);
1411
+ if (owner !== void 0) {
1412
+ errors.push({
1413
+ code: "PORT_CONFLICT",
1414
+ message: `Host port ${port} of service '${serviceName}' is already published by '${owner}'.`,
1415
+ path: `services.${serviceName}.port`,
1416
+ value: port
1417
+ });
1418
+ } else {
1419
+ usedPorts.set(port, serviceName);
1420
+ }
1124
1421
  }
1125
- usedPorts.add(serviceConfig.port);
1126
1422
  }
1127
1423
  return {
1128
1424
  valid: errors.length === 0,
@@ -1130,11 +1426,24 @@ function validateResolvedConfig(config) {
1130
1426
  };
1131
1427
  }
1132
1428
 
1429
+ // src/generators/healthcheck.ts
1430
+ function nodeHealthcheckScript(port, path) {
1431
+ return `require('http').get('http://localhost:${port}${path}', (r) => process.exit(r.statusCode >= 200 && r.statusCode < 300 ? 0 : 1)).on('error', () => process.exit(1)).setTimeout(2000, () => process.exit(1))`;
1432
+ }
1433
+
1133
1434
  // src/generators/dockerfile.ts
1435
+ function dockerCmd(command) {
1436
+ const words = command.trim().split(/\s+/);
1437
+ if (words.every((word) => /^[\w@%+=:,./-]+$/.test(word))) {
1438
+ return `CMD ${JSON.stringify(words).replace(/","/g, '", "')}`;
1439
+ }
1440
+ return `CMD ${command.trim()}`;
1441
+ }
1134
1442
  function generateDockerfile(config, _context) {
1135
- const { app, name } = config;
1443
+ const { app } = config;
1136
1444
  const { node, workdir, command, buildCommand, multiStage, healthcheck } = app;
1137
1445
  const port = app.port;
1446
+ const hasBuild = buildCommand.trim() !== "";
1138
1447
  let dockerfile = "";
1139
1448
  if (multiStage) {
1140
1449
  dockerfile += `# Builder stage
@@ -1160,11 +1469,13 @@ function generateDockerfile(config, _context) {
1160
1469
  dockerfile += `COPY . .
1161
1470
 
1162
1471
  `;
1163
- dockerfile += `# Build application
1472
+ if (hasBuild) {
1473
+ dockerfile += `# Build application
1164
1474
  `;
1165
- dockerfile += `RUN npm run build 2>/dev/null || true
1475
+ dockerfile += `RUN ${buildCommand.trim()}
1166
1476
 
1167
1477
  `;
1478
+ }
1168
1479
  dockerfile += `# Production stage
1169
1480
  `;
1170
1481
  dockerfile += `FROM node:${node}
@@ -1178,13 +1489,19 @@ function generateDockerfile(config, _context) {
1178
1489
  `;
1179
1490
  dockerfile += `# Copy from builder
1180
1491
  `;
1181
- dockerfile += `COPY --from=builder ${workdir}/node_modules ./node_modules
1492
+ if (hasBuild) {
1493
+ dockerfile += `COPY --from=builder ${workdir}/node_modules ./node_modules
1182
1494
  `;
1183
- dockerfile += `COPY --from=builder ${workdir}/dist ./dist
1495
+ dockerfile += `COPY --from=builder ${workdir}/dist ./dist
1496
+ `;
1497
+ dockerfile += `COPY --from=builder ${workdir}/package*.json ./
1498
+
1184
1499
  `;
1185
- dockerfile += `COPY --from=builder ${workdir}/package*.json ./
1500
+ } else {
1501
+ dockerfile += `COPY --from=builder ${workdir} ./
1186
1502
 
1187
1503
  `;
1504
+ }
1188
1505
  } else {
1189
1506
  dockerfile += `FROM node:${node}
1190
1507
 
@@ -1215,180 +1532,196 @@ function generateDockerfile(config, _context) {
1215
1532
 
1216
1533
  `;
1217
1534
  if (healthcheck) {
1535
+ const script = JSON.stringify(nodeHealthcheckScript(port, healthcheck));
1218
1536
  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
1537
+ `;
1538
+ dockerfile += ` CMD ["node", "-e", ${script}]
1220
1539
 
1221
1540
  `;
1222
1541
  }
1223
- dockerfile += `CMD ["npm", "start"]
1542
+ dockerfile += `${dockerCmd(command)}
1224
1543
  `;
1225
1544
  return dockerfile;
1226
1545
  }
1227
1546
 
1228
1547
  // src/utils/yaml.ts
1548
+ var PLAIN_SCALAR = /^[A-Za-z_/.][\w./=@+~-]*$/;
1549
+ var NUMBER_LIKE = /^\.(?:\d|inf$|nan$)/i;
1550
+ var DURATION = /^\d+(?:\.\d+)?(?:ns|us|ms|s|m|h)$/;
1551
+ var RESERVED_WORD = /^(?:y|n|yes|no|on|off|true|false|null)$/i;
1229
1552
  function toYaml(obj, indent = 0) {
1230
- const spaces = " ".repeat(indent);
1231
- if (obj === null) {
1553
+ if (isInline(obj)) {
1554
+ return inlineValue(obj);
1555
+ }
1556
+ if (Array.isArray(obj)) {
1557
+ return arrayToYaml(obj, indent);
1558
+ }
1559
+ return objectToYaml(obj, indent);
1560
+ }
1561
+ function isInline(value) {
1562
+ if (value === null || typeof value !== "object") {
1563
+ return true;
1564
+ }
1565
+ if (Array.isArray(value)) {
1566
+ return value.every((item) => item === null || item === void 0 || typeof item !== "object");
1567
+ }
1568
+ return Object.values(value).every((item) => item === void 0);
1569
+ }
1570
+ function inlineValue(value) {
1571
+ if (value === null || value === void 0) {
1232
1572
  return "null";
1233
1573
  }
1234
- if (typeof obj === "string") {
1235
- return quoteStringIfNeeded(obj);
1574
+ if (typeof value === "string") {
1575
+ return yamlScalar(value);
1236
1576
  }
1237
- if (typeof obj === "number" || typeof obj === "boolean") {
1238
- return String(obj);
1577
+ if (typeof value === "number") {
1578
+ if (Number.isFinite(value)) return String(value);
1579
+ if (Number.isNaN(value)) return ".nan";
1580
+ return value > 0 ? ".inf" : "-.inf";
1239
1581
  }
1240
- if (Array.isArray(obj)) {
1241
- return arrayToYaml(obj, indent);
1582
+ if (typeof value === "boolean") {
1583
+ return String(value);
1584
+ }
1585
+ if (Array.isArray(value)) {
1586
+ return `[${value.map((item) => inlineValue(item)).join(", ")}]`;
1242
1587
  }
1243
- if (typeof obj === "object") {
1244
- return objectToYaml(obj, indent);
1588
+ if (typeof value === "object") {
1589
+ return "{}";
1245
1590
  }
1246
- return String(obj);
1591
+ return JSON.stringify(String(value));
1247
1592
  }
1248
1593
  function arrayToYaml(arr, indent) {
1249
1594
  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
1595
  const lines = [];
1261
1596
  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)}`);
1597
+ if (isInline(item)) {
1598
+ lines.push(`${spaces}- ${inlineValue(item)}`);
1265
1599
  } else {
1266
- lines.push(`${spaces}- ${value}`);
1600
+ const block = toYaml(item, indent + 2);
1601
+ lines.push(`${spaces}- ${block.slice(indent + 2)}`);
1267
1602
  }
1268
1603
  }
1269
1604
  return lines.join("\n");
1270
1605
  }
1271
1606
  function objectToYaml(obj, indent) {
1272
- const keys = Object.keys(obj);
1273
- if (keys.length === 0) {
1274
- return "{}";
1275
- }
1276
1607
  const spaces = " ".repeat(indent);
1277
1608
  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);
1609
+ for (const [key, value] of Object.entries(obj)) {
1610
+ if (value === void 0) continue;
1611
+ const yamlKey = yamlScalar(key);
1612
+ if (isInline(value)) {
1613
+ lines.push(`${spaces}${yamlKey}: ${inlineValue(value)}`);
1284
1614
  } else {
1285
- lines.push(`${spaces}${key}: ${valueStr}`);
1615
+ lines.push(`${spaces}${yamlKey}:`);
1616
+ lines.push(toYaml(value, indent + 2));
1286
1617
  }
1287
1618
  }
1288
1619
  return lines.join("\n");
1289
1620
  }
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)}"`;
1621
+ function yamlScalar(str) {
1622
+ if ((PLAIN_SCALAR.test(str) || DURATION.test(str)) && !RESERVED_WORD.test(str) && !NUMBER_LIKE.test(str)) {
1623
+ return str;
1302
1624
  }
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");
1625
+ return JSON.stringify(str);
1307
1626
  }
1308
1627
 
1309
1628
  // 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)
1629
+ function composeLiteral(value) {
1630
+ return value.replace(/\$/g, "$$$$");
1631
+ }
1632
+ function generateCompose(config, _context) {
1633
+ const { app, services: services2 } = config;
1634
+ const appService = {
1635
+ build: ".",
1636
+ ports: [`${app.port}:${app.port}`],
1637
+ environment: generateAppEnvironment(config),
1638
+ depends_on: Object.keys(services2),
1639
+ volumes: app.volumes.length > 0 ? app.volumes : void 0
1324
1640
  };
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}`],
1641
+ if (app.healthcheck) {
1642
+ appService.healthcheck = {
1643
+ test: ["CMD", "node", "-e", nodeHealthcheckScript(app.port, app.healthcheck)],
1329
1644
  interval: "30s",
1330
1645
  timeout: "3s",
1331
1646
  retries: 3
1332
1647
  };
1333
1648
  }
1649
+ const composeServices = { app: appService };
1334
1650
  for (const [serviceName, serviceConfig] of Object.entries(services2)) {
1335
- servicesRecord[serviceName] = generateServiceConfig(serviceName, serviceConfig);
1651
+ composeServices[serviceName] = generateServiceConfig(serviceConfig);
1336
1652
  }
1337
- return toYaml(compose);
1653
+ const compose = {
1654
+ version: "3.9",
1655
+ services: composeServices,
1656
+ volumes: generateVolumeDefinitions(config)
1657
+ };
1658
+ return `${toYaml(compose)}
1659
+ `;
1338
1660
  }
1339
- function generateAppEnvironment(config, context) {
1661
+ function generateAppEnvironment(config) {
1340
1662
  const env = ["NODE_ENV=production", `PORT=${config.app.port}`];
1663
+ const add = (key, value) => {
1664
+ env.push(`${key}=${composeLiteral(String(value))}`);
1665
+ };
1341
1666
  for (const [serviceName, serviceConfig] of Object.entries(config.services)) {
1342
1667
  if (serviceConfig.connectionString) {
1343
- const key = `${serviceName.toUpperCase()}_URL`;
1344
- env.push(`${key}=${serviceConfig.connectionString}`);
1668
+ const key = `${serviceName.toUpperCase().replace(/[^A-Z0-9_]/g, "_")}_URL`;
1669
+ add(key, serviceConfig.connectionString);
1345
1670
  }
1346
1671
  }
1347
1672
  if (config.services.postgres) {
1348
1673
  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}`);
1674
+ add("POSTGRES_HOST", pg.name);
1675
+ add("POSTGRES_PORT", pg.port);
1676
+ add("POSTGRES_USER", pg.env.POSTGRES_USER || "postgres");
1677
+ add("POSTGRES_PASSWORD", pg.env.POSTGRES_PASSWORD || "postgres");
1678
+ add("POSTGRES_DB", pg.env.POSTGRES_DB || config.name);
1354
1679
  }
1355
1680
  if (config.services.mysql) {
1356
1681
  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}`);
1682
+ add("MYSQL_HOST", mysql.name);
1683
+ add("MYSQL_PORT", mysql.port);
1684
+ add("MYSQL_USER", mysql.env.MYSQL_USER || "root");
1685
+ add("MYSQL_PASSWORD", mysql.env.MYSQL_PASSWORD || mysql.env.MYSQL_ROOT_PASSWORD || "root");
1686
+ add("MYSQL_DATABASE", mysql.env.MYSQL_DATABASE || config.name);
1362
1687
  }
1363
1688
  if (config.services.mongo) {
1364
1689
  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}`);
1690
+ add("MONGO_HOST", mongo.name);
1691
+ add("MONGO_PORT", mongo.port);
1692
+ add("MONGO_USER", mongo.env.MONGO_INITDB_ROOT_USERNAME || "mongo");
1693
+ add("MONGO_PASSWORD", mongo.env.MONGO_INITDB_ROOT_PASSWORD || "mongo");
1694
+ add("MONGO_DATABASE", mongo.env.MONGO_INITDB_DATABASE || config.name);
1370
1695
  }
1371
1696
  if (config.services.redis) {
1372
1697
  const redis = config.services.redis;
1373
- env.push(`REDIS_HOST=${redis.name}`);
1374
- env.push(`REDIS_PORT=${redis.port}`);
1698
+ add("REDIS_HOST", redis.name);
1699
+ add("REDIS_PORT", redis.port);
1700
+ if (redis.env.REDIS_PASSWORD) {
1701
+ add("REDIS_PASSWORD", redis.env.REDIS_PASSWORD);
1702
+ }
1703
+ }
1704
+ for (const name of config.app.env) {
1705
+ if (!env.some((entry) => entry.startsWith(`${name}=`))) {
1706
+ env.push(name);
1707
+ }
1375
1708
  }
1376
1709
  return env;
1377
1710
  }
1378
- function generateServiceConfig(name, config) {
1711
+ function generateServiceConfig(config) {
1712
+ const environment = {};
1713
+ for (const [key, value] of Object.entries(config.env)) {
1714
+ environment[key] = composeLiteral(value);
1715
+ }
1716
+ const portMappings = [`${config.hostPort ?? config.port}:${config.port}`];
1717
+ for (const extraPort of config.ports ?? []) {
1718
+ portMappings.push(`${extraPort}:${extraPort}`);
1719
+ }
1379
1720
  const service = {
1380
1721
  image: config.image,
1381
- ports: [],
1382
- environment: config.env
1722
+ ports: portMappings,
1723
+ environment
1383
1724
  };
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
1725
  if (config.volumes.length > 0) {
1393
1726
  service.volumes = config.volumes;
1394
1727
  }
@@ -1405,16 +1738,16 @@ function generateServiceConfig(name, config) {
1405
1738
  }
1406
1739
  return service;
1407
1740
  }
1408
- function generateVolumeDefinitions(services2) {
1741
+ function generateVolumeDefinitions(config) {
1409
1742
  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
- }
1743
+ const specs = [
1744
+ ...config.app.volumes,
1745
+ ...Object.values(config.services).flatMap((service) => service.volumes)
1746
+ ];
1747
+ for (const spec of specs) {
1748
+ const name = namedVolume(spec);
1749
+ if (name) {
1750
+ volumes[name] = {};
1418
1751
  }
1419
1752
  }
1420
1753
  return volumes;
@@ -1429,10 +1762,10 @@ yarn-debug.log*
1429
1762
  yarn-error.log*
1430
1763
  pnpm-debug.log*
1431
1764
 
1432
- # Environment
1765
+ # Environment (secrets must never be copied into the image)
1433
1766
  .env
1434
- .env.local
1435
- .env.*.local
1767
+ .env.*
1768
+ !.env.example
1436
1769
 
1437
1770
  # Git
1438
1771
  .git/
@@ -1492,6 +1825,16 @@ docker-compose.yml
1492
1825
  }
1493
1826
 
1494
1827
  // src/generators/env.ts
1828
+ function envValue(value) {
1829
+ if (/^[\w@%+=:,./?&-]*$/.test(value)) {
1830
+ return value;
1831
+ }
1832
+ if (!/['\r\n]/.test(value)) {
1833
+ return `'${value}'`;
1834
+ }
1835
+ const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r");
1836
+ return `"${escaped}"`;
1837
+ }
1495
1838
  function generateEnvExample(config) {
1496
1839
  let content = `# Application Configuration
1497
1840
  NODE_ENV=production
@@ -1511,17 +1854,17 @@ PORT=${config.app.port}
1511
1854
  content += `
1512
1855
  # PostgreSQL
1513
1856
  `;
1514
- content += `DATABASE_URL=${pg.connectionString || ""}
1857
+ content += `DATABASE_URL=${envValue(String(pg.connectionString || ""))}
1515
1858
  `;
1516
- content += `POSTGRES_HOST=${pg.name}
1859
+ content += `POSTGRES_HOST=${envValue(String(pg.name))}
1517
1860
  `;
1518
- content += `POSTGRES_PORT=${pg.port}
1861
+ content += `POSTGRES_PORT=${envValue(String(pg.port))}
1519
1862
  `;
1520
- content += `POSTGRES_USER=${pg.env.POSTGRES_USER || "postgres"}
1863
+ content += `POSTGRES_USER=${envValue(String(pg.env.POSTGRES_USER || "postgres"))}
1521
1864
  `;
1522
- content += `POSTGRES_PASSWORD=${pg.env.POSTGRES_PASSWORD || "postgres"}
1865
+ content += `POSTGRES_PASSWORD=${envValue(String(pg.env.POSTGRES_PASSWORD || "postgres"))}
1523
1866
  `;
1524
- content += `POSTGRES_DB=${pg.env.POSTGRES_DB || config.name}
1867
+ content += `POSTGRES_DB=${envValue(String(pg.env.POSTGRES_DB || config.name))}
1525
1868
  `;
1526
1869
  }
1527
1870
  if (config.services.mysql) {
@@ -1529,17 +1872,17 @@ PORT=${config.app.port}
1529
1872
  content += `
1530
1873
  # MySQL
1531
1874
  `;
1532
- content += `MYSQL_URL=${mysql.connectionString || ""}
1875
+ content += `MYSQL_URL=${envValue(String(mysql.connectionString || ""))}
1533
1876
  `;
1534
- content += `MYSQL_HOST=${mysql.name}
1877
+ content += `MYSQL_HOST=${envValue(String(mysql.name))}
1535
1878
  `;
1536
- content += `MYSQL_PORT=${mysql.port}
1879
+ content += `MYSQL_PORT=${envValue(String(mysql.port))}
1537
1880
  `;
1538
- content += `MYSQL_USER=${mysql.env.MYSQL_USER || "root"}
1881
+ content += `MYSQL_USER=${envValue(String(mysql.env.MYSQL_USER || "root"))}
1539
1882
  `;
1540
- content += `MYSQL_PASSWORD=${mysql.env.MYSQL_PASSWORD || mysql.env.MYSQL_ROOT_PASSWORD || "root"}
1883
+ content += `MYSQL_PASSWORD=${envValue(String(mysql.env.MYSQL_PASSWORD || mysql.env.MYSQL_ROOT_PASSWORD || "root"))}
1541
1884
  `;
1542
- content += `MYSQL_DATABASE=${mysql.env.MYSQL_DATABASE || config.name}
1885
+ content += `MYSQL_DATABASE=${envValue(String(mysql.env.MYSQL_DATABASE || config.name))}
1543
1886
  `;
1544
1887
  }
1545
1888
  if (config.services.mongo) {
@@ -1547,17 +1890,17 @@ PORT=${config.app.port}
1547
1890
  content += `
1548
1891
  # MongoDB
1549
1892
  `;
1550
- content += `MONGO_URL=${mongo.connectionString || ""}
1893
+ content += `MONGO_URL=${envValue(String(mongo.connectionString || ""))}
1551
1894
  `;
1552
- content += `MONGO_HOST=${mongo.name}
1895
+ content += `MONGO_HOST=${envValue(String(mongo.name))}
1553
1896
  `;
1554
- content += `MONGO_PORT=${mongo.port}
1897
+ content += `MONGO_PORT=${envValue(String(mongo.port))}
1555
1898
  `;
1556
- content += `MONGO_USER=${mongo.env.MONGO_INITDB_ROOT_USERNAME || "mongo"}
1899
+ content += `MONGO_USER=${envValue(String(mongo.env.MONGO_INITDB_ROOT_USERNAME || "mongo"))}
1557
1900
  `;
1558
- content += `MONGO_PASSWORD=${mongo.env.MONGO_INITDB_ROOT_PASSWORD || "mongo"}
1901
+ content += `MONGO_PASSWORD=${envValue(String(mongo.env.MONGO_INITDB_ROOT_PASSWORD || "mongo"))}
1559
1902
  `;
1560
- content += `MONGO_DATABASE=${mongo.env.MONGO_INITDB_DATABASE || config.name}
1903
+ content += `MONGO_DATABASE=${envValue(String(mongo.env.MONGO_INITDB_DATABASE || config.name))}
1561
1904
  `;
1562
1905
  }
1563
1906
  if (config.services.redis) {
@@ -1565,14 +1908,14 @@ PORT=${config.app.port}
1565
1908
  content += `
1566
1909
  # Redis
1567
1910
  `;
1568
- content += `REDIS_URL=${redis.connectionString || ""}
1911
+ content += `REDIS_URL=${envValue(String(redis.connectionString || ""))}
1569
1912
  `;
1570
- content += `REDIS_HOST=${redis.name}
1913
+ content += `REDIS_HOST=${envValue(String(redis.name))}
1571
1914
  `;
1572
- content += `REDIS_PORT=${redis.port}
1915
+ content += `REDIS_PORT=${envValue(String(redis.port))}
1573
1916
  `;
1574
1917
  if (redis.env.REDIS_PASSWORD) {
1575
- content += `REDIS_PASSWORD=${redis.env.REDIS_PASSWORD}
1918
+ content += `REDIS_PASSWORD=${envValue(String(redis.env.REDIS_PASSWORD))}
1576
1919
  `;
1577
1920
  }
1578
1921
  }
@@ -1587,7 +1930,7 @@ function generateBuildScript(_config) {
1587
1930
  set -e
1588
1931
 
1589
1932
  echo "Building Docker image..."
1590
- docker-compose build
1933
+ docker compose build
1591
1934
 
1592
1935
  echo "Build complete!"
1593
1936
  `;
@@ -1600,7 +1943,7 @@ function generateUpScript(config) {
1600
1943
  set -e
1601
1944
 
1602
1945
  echo "Starting services..."
1603
- docker-compose up -d ${services2.join(" ")}
1946
+ docker compose up -d ${services2.join(" ")}
1604
1947
 
1605
1948
  echo "Services started!"
1606
1949
  echo ""
@@ -1614,7 +1957,7 @@ function generateDownScript(_config) {
1614
1957
  set -e
1615
1958
 
1616
1959
  echo "Stopping services..."
1617
- docker-compose down
1960
+ docker compose down
1618
1961
 
1619
1962
  echo "Services stopped!"
1620
1963
  `;
@@ -1626,9 +1969,9 @@ function generateLogsScript(_config) {
1626
1969
  set -e
1627
1970
 
1628
1971
  if [ -n "$1" ]; then
1629
- docker-compose logs -f "$1"
1972
+ docker compose logs -f "$1"
1630
1973
  else
1631
- docker-compose logs -f
1974
+ docker compose logs -f
1632
1975
  fi
1633
1976
  `;
1634
1977
  }
@@ -1655,28 +1998,28 @@ help:
1655
1998
  @echo " make restart - Restart all services"
1656
1999
  @echo " make logs - Show logs from all services"
1657
2000
  @echo " make shell - Open shell in app container"
1658
- @echo " make clean - Remove containers and volumes"
2001
+ @echo " make clean - Remove this project's containers and volumes"
1659
2002
  @echo " make install - Install dependencies"
1660
2003
 
1661
2004
  # Build Docker images
1662
2005
  build:
1663
- docker-compose build
2006
+ docker compose build
1664
2007
 
1665
2008
  # Start all services
1666
2009
  up:
1667
- docker-compose up -d
2010
+ docker compose up -d
1668
2011
  @echo "App running at http://localhost:${config.app.port}"
1669
2012
 
1670
2013
  # Stop all services
1671
2014
  down:
1672
- docker-compose down
2015
+ docker compose down
1673
2016
 
1674
2017
  # Restart all services
1675
2018
  restart: down up
1676
2019
 
1677
2020
  # Show logs from all services
1678
2021
  logs:
1679
- docker-compose logs -f
2022
+ docker compose logs -f
1680
2023
  `;
1681
2024
  if (services2.length > 0) {
1682
2025
  content += "\n";
@@ -1684,23 +2027,22 @@ logs:
1684
2027
  content += `
1685
2028
  logs-${service}:
1686
2029
  `;
1687
- content += ` docker-compose logs -f ${service}
2030
+ content += ` docker compose logs -f ${service}
1688
2031
  `;
1689
2032
  }
1690
2033
  }
1691
2034
  content += `
1692
- # Clean up containers and volumes
2035
+ # Remove this project's containers, networks and volumes
1693
2036
  clean:
1694
- docker-compose down -v
1695
- docker system prune -f
2037
+ docker compose down -v --remove-orphans
1696
2038
 
1697
2039
  # Install dependencies (in running container)
1698
2040
  shell:
1699
- docker-compose exec app sh
2041
+ docker compose exec app sh
1700
2042
 
1701
2043
  # Install dependencies
1702
2044
  install:
1703
- docker-compose exec app npm install
2045
+ docker compose exec app npm install
1704
2046
  `;
1705
2047
  return content;
1706
2048
  }
@@ -1735,24 +2077,27 @@ function generateAll(config, context) {
1735
2077
  }
1736
2078
 
1737
2079
  // src/core/dockcraft.ts
1738
- import { join as join2 } from "path";
2080
+ import { isAbsolute as isAbsolute2, join as join3, normalize } from "path";
2081
+ function validationError(prefix, errors) {
2082
+ const errorMessages = errors.map((e) => ` - ${e.message}`).join("\n");
2083
+ return new ValidationError(`${prefix}:
2084
+ ${errorMessages}`, errors);
2085
+ }
2086
+ function isSafeOutputPath(fileName) {
2087
+ if (typeof fileName !== "string" || fileName === "" || fileName.includes("\0")) return false;
2088
+ if (isAbsolute2(fileName) || /^[a-zA-Z]:/.test(fileName) || fileName.startsWith("\\")) return false;
2089
+ const normalized = normalize(fileName.replace(/\\/g, "/"));
2090
+ return !normalized.split(/[\\/]/).includes("..") && normalized !== ".";
2091
+ }
1739
2092
  async function dockcraft(config, options = {}) {
1740
2093
  const validation = validateConfig(config);
1741
2094
  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
- );
2095
+ throw validationError("Configuration validation failed", validation.errors);
1747
2096
  }
1748
2097
  const resolved = await resolveConfig(config);
1749
2098
  const resolvedValidation = validateResolvedConfig(resolved);
1750
2099
  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
- );
2100
+ throw validationError("Resolved configuration validation failed", resolvedValidation.errors);
1756
2101
  }
1757
2102
  const context = {
1758
2103
  config: resolved,
@@ -1760,22 +2105,38 @@ ${errorMessages}`
1760
2105
  Object.entries(resolved.services).map(([name, svc]) => [name, svc.port])
1761
2106
  ),
1762
2107
  strings: new Map(
1763
- Object.entries(resolved.services).filter(([, svc]) => svc.connectionString).map(([name, svc]) => [name, svc.connectionString])
2108
+ Object.entries(resolved.services).filter((entry) => Boolean(entry[1].connectionString)).map(([name, svc]) => [name, svc.connectionString])
1764
2109
  )
1765
2110
  };
1766
2111
  context.ports.set("app", resolved.app.port);
1767
2112
  const generated = generateAll(resolved, context);
2113
+ for (const plugin of config.plugins ?? []) {
2114
+ for (const output of plugin.outputs ?? []) {
2115
+ if (!isSafeOutputPath(output.file)) {
2116
+ throw new ConfigError(
2117
+ `Plugin '${plugin.name}' output '${output.name}' has an unsafe file name '${output.file}'. Use a relative path inside the output directory.`,
2118
+ "UNSAFE_OUTPUT_PATH"
2119
+ );
2120
+ }
2121
+ if (output.file in generated) {
2122
+ throw new ConfigError(
2123
+ `Plugin '${plugin.name}' output '${output.name}' would overwrite generated file '${output.file}'.`,
2124
+ "DUPLICATE_OUTPUT"
2125
+ );
2126
+ }
2127
+ generated[output.file] = output.generate(resolved, context);
2128
+ }
2129
+ }
1768
2130
  const written = [];
1769
2131
  const outputDir = resolved.output.dir ?? "./";
1770
2132
  if (!options.dryRun) {
1771
2133
  for (const [fileName, content] of Object.entries(generated)) {
1772
- if (!fileName) continue;
1773
- const filePath = join2(outputDir, fileName);
2134
+ const filePath = join3(outputDir, fileName);
1774
2135
  const exists = await fileExists(filePath);
1775
2136
  if (exists && !resolved.output.overwrite) {
1776
2137
  continue;
1777
2138
  }
1778
- await writeFile(filePath, content);
2139
+ await writeFile(filePath, content, fileName.endsWith(".sh") ? 493 : void 0);
1779
2140
  written.push(filePath);
1780
2141
  }
1781
2142
  }
@@ -1789,41 +2150,43 @@ ${errorMessages}`
1789
2150
  // src/cli/commands/generate.ts
1790
2151
  async function generate(args) {
1791
2152
  title("Dockcraft Generate");
1792
- const configPath = getOption(args, "config", "./dockcraft.config.ts");
2153
+ const configPath = getOption(args, "config") || findConfigFile();
1793
2154
  const dryRun = getBooleanFlag(args, "dry-run");
1794
2155
  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);
2156
+ const outputDir = getOption(args, "output");
2157
+ if (!configPath) {
2158
+ throw new Error(
2159
+ `No config file found. Create one with "dockcraft init" or pass --config <file> (looked for ${DEFAULT_CONFIG_FILES.join(", ")}).`
2160
+ );
2161
+ }
2162
+ subtitle(`Loading config from: ${configPath}`);
2163
+ const config = await loadConfig(configPath);
2164
+ if (force) {
2165
+ config.output = { ...config.output, overwrite: true };
2166
+ }
2167
+ if (outputDir) {
2168
+ config.output = { ...config.output, dir: outputDir };
2169
+ }
2170
+ const result = await dockcraft(config, { dryRun });
2171
+ if (dryRun) {
2172
+ subtitle("Preview (dry-run mode):");
2173
+ for (const [fileName, content] of result.files) {
1820
2174
  console.log("");
1821
- success('Done! Run "docker-compose up -d" to start services');
2175
+ console.log(`File: ${fileName}`);
2176
+ console.log("\u2500".repeat(50));
2177
+ console.log(content);
2178
+ console.log("\u2500".repeat(50));
1822
2179
  }
1823
- } catch (err) {
1824
- error(err instanceof Error ? err.message : String(err));
1825
- process.exit(1);
2180
+ return;
1826
2181
  }
2182
+ success(`Generated ${result.written.length} files:`);
2183
+ list(result.written);
2184
+ const skipped = result.files.size - result.written.length;
2185
+ if (skipped > 0) {
2186
+ info(`Skipped ${skipped} existing file(s); use --force to overwrite them.`);
2187
+ }
2188
+ console.log("");
2189
+ success('Done! Run "docker compose up -d" to start services');
1827
2190
  }
1828
2191
 
1829
2192
  // src/ports/defaults.ts
@@ -1845,12 +2208,20 @@ function listDefaultPorts() {
1845
2208
 
1846
2209
  // src/cli/commands/ports.ts
1847
2210
  async function ports(args) {
1848
- title("Port Utilities");
1849
2211
  const checkOption = getOption(args, "check");
1850
2212
  const rangeOption = getOption(args, "range");
1851
2213
  const asJson = getBooleanFlag(args, "json");
2214
+ if (!asJson) {
2215
+ title("Port Utilities");
2216
+ }
1852
2217
  if (checkOption) {
1853
- const portsToCheck = checkOption.split(",").map((s) => parseInt(s.trim(), 10));
2218
+ const portsToCheck = checkOption.split(",").map((s) => s.trim()).filter(Boolean).map((value) => {
2219
+ const port = /^\d+$/.test(value) ? Number(value) : NaN;
2220
+ if (!isPort(port)) {
2221
+ throw new Error(`Invalid port '${value}'. Ports must be numbers between 1-65535.`);
2222
+ }
2223
+ return port;
2224
+ });
1854
2225
  const results = await checkPorts(portsToCheck);
1855
2226
  if (asJson) {
1856
2227
  json(Object.fromEntries(results));
@@ -1866,21 +2237,18 @@ async function ports(args) {
1866
2237
  }
1867
2238
  if (rangeOption) {
1868
2239
  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)");
2240
+ const start = Number(match?.[1]);
2241
+ const end = Number(match?.[2]);
2242
+ if (!match || !isPort(start) || !isPort(end) || start > end) {
2243
+ throw new Error("Invalid range format. Use: --range START-END with ports 1-65535 (e.g., 3000-3010)");
1871
2244
  }
1872
- const start = parseInt(match[1], 10);
1873
- const end = parseInt(match[2], 10);
2245
+ const port = await findAvailablePortInRange(start, end);
1874
2246
  if (asJson) {
1875
- const port = await findAvailablePortInRange(start, end);
1876
- json({ available: port });
2247
+ json({ available: port ?? null });
2248
+ } else if (port !== void 0) {
2249
+ success(`Found available port: ${port} in range ${start}-${end}`);
1877
2250
  } 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
- }
2251
+ console.log(`No available port in range ${start}-${end}`);
1884
2252
  }
1885
2253
  return;
1886
2254
  }
@@ -1901,8 +2269,7 @@ function presets2(args) {
1901
2269
  if (presetName) {
1902
2270
  const preset = getPreset(presetName);
1903
2271
  if (!preset) {
1904
- console.log(`Preset '${presetName}' not found`);
1905
- return;
2272
+ throw new Error(`Preset '${presetName}' not found. Run "dockcraft presets" to list available presets.`);
1906
2273
  }
1907
2274
  title(`Preset: ${presetName}`);
1908
2275
  if (preset.description) {
@@ -1931,7 +2298,6 @@ function presets2(args) {
1931
2298
  }
1932
2299
 
1933
2300
  // src/cli/index.ts
1934
- var VERSION = "1.0.0";
1935
2301
  var commands = /* @__PURE__ */ new Map();
1936
2302
  commands.set("init", init);
1937
2303
  commands.set("generate", generate);
@@ -1979,7 +2345,8 @@ OPTIONS:
1979
2345
  --name <name> Project name
1980
2346
  --port <port> App port
1981
2347
  --services <list> Comma-separated service list
1982
- --output <dir> Output directory
2348
+ --output <dir> Directory to write dockcraft.config.mts to
2349
+ --force Overwrite an existing config file
1983
2350
  -y, --yes Skip prompts, use defaults
1984
2351
  `);
1985
2352
  break;
@@ -1989,7 +2356,7 @@ USAGE:
1989
2356
  dockcraft generate [options]
1990
2357
 
1991
2358
  OPTIONS:
1992
- --config <file> Config file path (default: dockcraft.config.ts)
2359
+ --config <file> Config file path (default: first of dockcraft.config.{ts,mts,js,mjs,cjs})
1993
2360
  --dry-run Preview without writing
1994
2361
  --force Overwrite existing files
1995
2362
  --output <dir> Output directory
@@ -2016,7 +2383,7 @@ ARGUMENTS:
2016
2383
  `);
2017
2384
  break;
2018
2385
  default:
2019
- console.log(`Unknown command: ${command}`);
2386
+ showGeneralHelp();
2020
2387
  }
2021
2388
  }
2022
2389
  function showVersion() {
@@ -2024,19 +2391,25 @@ function showVersion() {
2024
2391
  }
2025
2392
  async function main(cliArgs = process.argv.slice(2)) {
2026
2393
  const args = parseArgs(cliArgs);
2394
+ const wantsHelp = args.flags.has("help") || args.flags.has("h");
2395
+ const wantsVersion = args.flags.has("version") || args.flags.has("v");
2027
2396
  if (!args.command) {
2028
- if (args.flags.has("version") || args.flags.has("v")) {
2397
+ if (wantsVersion && !wantsHelp) {
2029
2398
  showVersion();
2030
2399
  return;
2031
2400
  }
2032
2401
  showHelp();
2033
2402
  return;
2034
2403
  }
2035
- if (args.flags.has("help") || args.flags.has("h")) {
2404
+ if (args.command === "help") {
2405
+ showHelp(args.positionals[0]);
2406
+ return;
2407
+ }
2408
+ if (wantsHelp) {
2036
2409
  showHelp(args.command);
2037
2410
  return;
2038
2411
  }
2039
- if (args.flags.has("version") || args.flags.has("v")) {
2412
+ if (wantsVersion) {
2040
2413
  showVersion();
2041
2414
  return;
2042
2415
  }
@@ -2044,22 +2417,20 @@ async function main(cliArgs = process.argv.slice(2)) {
2044
2417
  if (!handler) {
2045
2418
  error(`Unknown command: ${args.command}`);
2046
2419
  console.log('Run "dockcraft --help" for usage information.');
2047
- process.exit(1);
2420
+ process.exitCode = 1;
2421
+ return;
2048
2422
  }
2049
2423
  try {
2050
2424
  await handler(args);
2051
2425
  } catch (err) {
2052
2426
  error(err instanceof Error ? err.message : String(err));
2053
- process.exit(1);
2427
+ process.exitCode = 1;
2054
2428
  }
2055
2429
  }
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
- };
2430
+
2431
+ // src/cli/bin.ts
2432
+ main().catch((err) => {
2433
+ error(err instanceof Error ? err.message : String(err));
2434
+ process.exitCode = 1;
2435
+ });
2065
2436
  //# sourceMappingURL=index.js.map