@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/index.cjs CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
- * @oxog/dockcraft - Zero-Dependency NPM Package
3
- * GitHub: https://github.com/ersinkoc/dockcraft
4
- * License: MIT
5
- */
2
+ * @oxog/dockcraft - Zero-Dependency NPM Package
3
+ * GitHub: https://github.com/ersinkoc/DockCraft
4
+ * License: MIT
5
+ */
6
6
  "use strict";
7
7
  var __defProp = Object.defineProperty;
8
8
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -23,8 +23,8 @@ var __copyProps = (to, from, except, desc) => {
23
23
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
24
24
 
25
25
  // src/index.ts
26
- var index_exports = {};
27
- __export(index_exports, {
26
+ var src_exports = {};
27
+ __export(src_exports, {
28
28
  ConfigError: () => ConfigError,
29
29
  DockcraftError: () => DockcraftError,
30
30
  FileWriteError: () => FileWriteError,
@@ -48,7 +48,59 @@ __export(index_exports, {
48
48
  registerService: () => registerService,
49
49
  resolvePort: () => resolvePort
50
50
  });
51
- module.exports = __toCommonJS(index_exports);
51
+ module.exports = __toCommonJS(src_exports);
52
+
53
+ // src/types.ts
54
+ var DockcraftError = class extends Error {
55
+ constructor(message, code) {
56
+ super(message);
57
+ this.code = code;
58
+ this.name = "DockcraftError";
59
+ }
60
+ };
61
+ var ConfigError = class extends DockcraftError {
62
+ constructor(message, code = "CONFIG_ERROR") {
63
+ super(message, code);
64
+ this.name = "ConfigError";
65
+ }
66
+ };
67
+ var ValidationError = class extends DockcraftError {
68
+ constructor(message, errors, code = "VALIDATION_ERROR") {
69
+ super(message, code);
70
+ this.errors = errors;
71
+ this.name = "ValidationError";
72
+ }
73
+ };
74
+ var PortConflictError = class extends DockcraftError {
75
+ constructor(port, code = "PORT_CONFLICT") {
76
+ super(`Port ${port} is already in use`, code);
77
+ this.name = "PortConflictError";
78
+ }
79
+ };
80
+ var NoPortAvailableError = class extends DockcraftError {
81
+ constructor(range, code = "NO_PORT_AVAILABLE") {
82
+ super(`No available port in range ${range[0]}-${range[1]}`, code);
83
+ this.name = "NoPortAvailableError";
84
+ }
85
+ };
86
+ var FileWriteError = class extends DockcraftError {
87
+ constructor(path, code = "FILE_WRITE_ERROR") {
88
+ super(`Failed to write file: ${path}`, code);
89
+ this.name = "FileWriteError";
90
+ }
91
+ };
92
+ var PresetNotFoundError = class extends DockcraftError {
93
+ constructor(name, code = "PRESET_NOT_FOUND") {
94
+ super(`Preset '${name}' not found`, code);
95
+ this.name = "PresetNotFoundError";
96
+ }
97
+ };
98
+ var ServiceNotFoundError = class extends DockcraftError {
99
+ constructor(name, code = "SERVICE_NOT_FOUND") {
100
+ super(`Service '${name}' not found`, code);
101
+ this.name = "ServiceNotFoundError";
102
+ }
103
+ };
52
104
 
53
105
  // src/presets/express-postgres.ts
54
106
  var expressPostgresPreset = {
@@ -288,10 +340,24 @@ registerPreset("nest-postgres", nestPostgresPreset);
288
340
  registerPreset("nest-mongo", nestMongoPreset);
289
341
  registerPreset("node-minimal", nodeMinimalPreset);
290
342
 
343
+ // src/services/image.ts
344
+ function variantImage(repository, version, variant) {
345
+ if (version === "latest") {
346
+ return `${repository}:${variant}`;
347
+ }
348
+ if (version === variant || version.includes("-")) {
349
+ return `${repository}:${version}`;
350
+ }
351
+ return `${repository}:${version}-${variant}`;
352
+ }
353
+ function urlPart(value) {
354
+ return encodeURIComponent(value);
355
+ }
356
+
291
357
  // src/services/postgres.ts
292
358
  var postgresService = {
293
359
  name: "postgres",
294
- image: (version) => `postgres:${version}-alpine`,
360
+ image: (version) => variantImage("postgres", version, "alpine"),
295
361
  defaultPort: 5432,
296
362
  defaultVersion: "16",
297
363
  env: {
@@ -308,7 +374,7 @@ var postgresService = {
308
374
  const database = config.env.POSTGRES_DB || "myapp";
309
375
  const host = config.name;
310
376
  const port = config.port;
311
- return `postgres://${user}:${password}@${host}:${port}/${database}`;
377
+ return `postgres://${urlPart(user)}:${urlPart(password)}@${host}:${port}/${urlPart(database)}`;
312
378
  }
313
379
  };
314
380
 
@@ -333,7 +399,7 @@ var mysqlService = {
333
399
  const database = config.env.MYSQL_DATABASE || "myapp";
334
400
  const host = config.name;
335
401
  const port = config.port;
336
- return `mysql://${user}:${password}@${host}:${port}/${database}`;
402
+ return `mysql://${urlPart(user)}:${urlPart(password)}@${host}:${port}/${urlPart(database)}`;
337
403
  }
338
404
  };
339
405
 
@@ -357,14 +423,14 @@ var mongoService = {
357
423
  const database = config.env.MONGO_INITDB_DATABASE || "myapp";
358
424
  const host = config.name;
359
425
  const port = config.port;
360
- return `mongodb://${user}:${password}@${host}:${port}/${database}`;
426
+ return `mongodb://${urlPart(user)}:${urlPart(password)}@${host}:${port}/${urlPart(database)}?authSource=admin`;
361
427
  }
362
428
  };
363
429
 
364
430
  // src/services/redis.ts
365
431
  var redisService = {
366
432
  name: "redis",
367
- image: (version) => `redis:${version}-alpine`,
433
+ image: (version) => variantImage("redis", version, "alpine"),
368
434
  defaultPort: 6379,
369
435
  defaultVersion: "7",
370
436
  env: {},
@@ -374,7 +440,9 @@ var redisService = {
374
440
  connectionString: (config) => {
375
441
  const host = config.name;
376
442
  const port = config.port;
377
- return `redis://${host}:${port}`;
443
+ const password = config.env.REDIS_PASSWORD;
444
+ const auth = password ? `:${urlPart(password)}@` : "";
445
+ return `redis://${auth}${host}:${port}`;
378
446
  }
379
447
  };
380
448
 
@@ -395,12 +463,13 @@ registerService(mongoService);
395
463
  registerService(redisService);
396
464
 
397
465
  // src/utils/merge.ts
466
+ var UNSAFE_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
398
467
  function deepMerge(...objects) {
399
468
  const result = {};
400
469
  for (const obj of objects) {
401
470
  if (obj === null || typeof obj !== "object") continue;
402
471
  for (const [key, value] of Object.entries(obj)) {
403
- if (value === void 0) continue;
472
+ if (value === void 0 || UNSAFE_KEYS.has(key)) continue;
404
473
  if (value && typeof value === "object" && !Array.isArray(value) && result[key] && typeof result[key] === "object" && !Array.isArray(result[key])) {
405
474
  result[key] = deepMerge(result[key], value);
406
475
  } else {
@@ -414,21 +483,30 @@ function deepMerge(...objects) {
414
483
  // src/ports/scanner.ts
415
484
  var import_net = require("net");
416
485
  async function isPortAvailable(port) {
486
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
487
+ throw new RangeError(`Invalid port: ${String(port)}. Must be an integer between 1 and 65535.`);
488
+ }
417
489
  return new Promise((resolve) => {
418
490
  const server = (0, import_net.createServer)();
491
+ let settled = false;
492
+ const finish = (available) => {
493
+ if (settled) return;
494
+ settled = true;
495
+ clearTimeout(timer);
496
+ resolve(available);
497
+ };
498
+ const timer = setTimeout(() => {
499
+ server.close();
500
+ finish(false);
501
+ }, 1e3);
502
+ timer.unref();
419
503
  server.once("error", () => {
420
- resolve(false);
504
+ finish(false);
421
505
  });
422
506
  server.once("listening", () => {
423
- server.close(() => {
424
- resolve(true);
425
- });
507
+ server.close(() => finish(true));
426
508
  });
427
509
  server.listen(port, "127.0.0.1");
428
- setTimeout(() => {
429
- server.close();
430
- resolve(false);
431
- }, 1e3);
432
510
  });
433
511
  }
434
512
  async function checkPorts(ports) {
@@ -471,20 +549,21 @@ async function resolvePort(options = {}) {
471
549
  case "range":
472
550
  if (range) {
473
551
  const [start, end = start + 100] = range;
474
- const port2 = await findAvailablePortInRange(start, end);
475
- if (port2 !== void 0) {
476
- return port2;
552
+ const port = await findAvailablePortInRange(start, end);
553
+ if (port !== void 0) {
554
+ return port;
477
555
  }
478
556
  throw new Error(`No available port in range ${start}-${end}`);
479
557
  }
480
558
  // Fall through to auto if no range specified
481
559
  case "auto":
482
- default:
560
+ default: {
483
561
  const port = await findNextAvailablePort(preferred);
484
562
  if (port !== void 0) {
485
563
  return port;
486
564
  }
487
565
  throw new Error(`No available port found starting from ${preferred}`);
566
+ }
488
567
  }
489
568
  }
490
569
 
@@ -499,9 +578,9 @@ var DEFAULT_APP_CONFIG = {
499
578
  volumes: [],
500
579
  multiStage: true
501
580
  };
502
- function normalizeAppConfig(config) {
581
+ function normalizeAppConfig(config = {}) {
503
582
  return {
504
- port: config.port === "auto" ? 3e3 : config.port,
583
+ port: typeof config.port === "number" ? config.port : DEFAULT_APP_CONFIG.port,
505
584
  node: config.node ?? DEFAULT_APP_CONFIG.node,
506
585
  workdir: config.workdir ?? DEFAULT_APP_CONFIG.workdir,
507
586
  command: config.command ?? DEFAULT_APP_CONFIG.command,
@@ -523,7 +602,7 @@ function normalizeConfig(config) {
523
602
  return {
524
603
  name: config.name,
525
604
  preset: config.preset,
526
- app: config.app,
605
+ app: config.app ?? {},
527
606
  services: config.services ?? {},
528
607
  output: normalizeOutputConfig(config.output),
529
608
  plugins: config.plugins ?? []
@@ -531,10 +610,11 @@ function normalizeConfig(config) {
531
610
  }
532
611
 
533
612
  // src/core/resolver.ts
613
+ var REDIS_AUTH_COMMAND = `sh -c 'exec redis-server --requirepass "$$REDIS_PASSWORD"'`;
534
614
  function mergePreset(config, presetName) {
535
615
  const preset = getPreset(presetName);
536
616
  if (!preset) {
537
- throw new Error(`Preset '${presetName}' not found`);
617
+ throw new PresetNotFoundError(presetName);
538
618
  }
539
619
  const merged = deepMerge(
540
620
  {
@@ -547,55 +627,65 @@ function mergePreset(config, presetName) {
547
627
  );
548
628
  return merged;
549
629
  }
550
- async function resolveServiceConfig(name, config, projectName) {
630
+ async function resolveServicePorts(portConfig, containerPort) {
631
+ if (portConfig === "auto") {
632
+ return {
633
+ port: containerPort,
634
+ hostPort: await resolvePort({ preferred: containerPort, strategy: "auto" })
635
+ };
636
+ }
637
+ if (typeof portConfig === "number") {
638
+ return { port: containerPort, hostPort: portConfig };
639
+ }
640
+ if (portConfig && typeof portConfig === "object") {
641
+ const startPort = portConfig.start ?? containerPort;
642
+ const endPort = portConfig.end ?? startPort + 100;
643
+ return {
644
+ port: containerPort,
645
+ hostPort: await resolvePort({ preferred: startPort, strategy: "range", range: [startPort, endPort] })
646
+ };
647
+ }
648
+ return { port: containerPort };
649
+ }
650
+ async function resolveServiceConfig(name, config, projectName, definitions) {
551
651
  if ("image" in config && config.image) {
552
652
  return resolveCustomService(name, config);
553
653
  }
554
- const definition = getService(name);
654
+ const definition = definitions?.get(name) ?? getService(name);
555
655
  if (!definition) {
556
- throw new Error(`Unknown service: ${name}`);
557
- }
558
- const defaultPort = definition.defaultPort;
559
- let port = defaultPort;
560
- let hostPort;
561
- if (config.port === "auto") {
562
- port = await resolvePort({ preferred: defaultPort, strategy: "auto" });
563
- hostPort = port;
564
- } else if (typeof config.port === "number") {
565
- port = config.port;
566
- hostPort = config.port;
567
- } else if (config.port && typeof config.port === "object") {
568
- const { start, end } = config.port;
569
- const startPort = start ?? defaultPort;
570
- const endPort = end ?? startPort + 100;
571
- port = await resolvePort({ preferred: startPort, strategy: "range", range: [startPort, endPort] });
572
- hostPort = port;
656
+ throw new ServiceNotFoundError(name);
573
657
  }
658
+ const { port, hostPort } = await resolveServicePorts(config.port, definition.defaultPort);
574
659
  const version = config.version ?? definition.defaultVersion;
575
660
  const image = typeof definition.image === "function" ? definition.image(version) : definition.image;
576
661
  const env = { ...definition.env, ...config.env };
662
+ let command = config.command;
577
663
  if (name === "postgres") {
578
664
  const pgConfig = config;
579
665
  if (pgConfig.database) env.POSTGRES_DB = pgConfig.database;
580
666
  if (pgConfig.user) env.POSTGRES_USER = pgConfig.user;
581
667
  if (pgConfig.password) env.POSTGRES_PASSWORD = pgConfig.password;
582
- if (!env.POSTGRES_DB) env.POSTGRES_DB = projectName;
668
+ if (!pgConfig.database && !config.env?.POSTGRES_DB) env.POSTGRES_DB = projectName;
583
669
  } else if (name === "mysql") {
584
670
  const mysqlConfig = config;
585
671
  if (mysqlConfig.database) env.MYSQL_DATABASE = mysqlConfig.database;
586
672
  if (mysqlConfig.user) env.MYSQL_USER = mysqlConfig.user;
587
673
  if (mysqlConfig.password) env.MYSQL_PASSWORD = mysqlConfig.password;
588
674
  if (mysqlConfig.rootPassword) env.MYSQL_ROOT_PASSWORD = mysqlConfig.rootPassword;
589
- if (!env.MYSQL_DATABASE) env.MYSQL_DATABASE = projectName;
675
+ if (!mysqlConfig.database && !config.env?.MYSQL_DATABASE) env.MYSQL_DATABASE = projectName;
590
676
  } else if (name === "mongo") {
591
677
  const mongoConfig = config;
592
678
  if (mongoConfig.database) env.MONGO_INITDB_DATABASE = mongoConfig.database;
593
679
  if (mongoConfig.user) env.MONGO_INITDB_ROOT_USERNAME = mongoConfig.user;
594
680
  if (mongoConfig.password) env.MONGO_INITDB_ROOT_PASSWORD = mongoConfig.password;
595
- if (!env.MONGO_INITDB_DATABASE) env.MONGO_INITDB_DATABASE = projectName;
681
+ if (!mongoConfig.database && !config.env?.MONGO_INITDB_DATABASE) env.MONGO_INITDB_DATABASE = projectName;
596
682
  } else if (name === "redis") {
597
683
  const redisConfig = config;
598
684
  if (redisConfig.password) env.REDIS_PASSWORD = redisConfig.password;
685
+ if (env.REDIS_PASSWORD) {
686
+ env.REDISCLI_AUTH = env.REDIS_PASSWORD;
687
+ command ??= REDIS_AUTH_COMMAND;
688
+ }
599
689
  }
600
690
  const volumes = [...definition.volumes ?? [], ...config.volumes ?? []];
601
691
  const resolvedConfig = {
@@ -605,7 +695,7 @@ async function resolveServiceConfig(name, config, projectName) {
605
695
  hostPort,
606
696
  env,
607
697
  volumes,
608
- command: config.command,
698
+ command,
609
699
  healthcheck: definition.healthcheck,
610
700
  ports: definition.ports
611
701
  };
@@ -615,53 +705,53 @@ async function resolveServiceConfig(name, config, projectName) {
615
705
  return resolvedConfig;
616
706
  }
617
707
  async function resolveCustomService(name, config) {
618
- const imageMatch = config.image.match(/:(\d+)$/);
619
- const defaultPort = imageMatch && imageMatch[1] ? parseInt(imageMatch[1], 10) : 80;
620
- let port = defaultPort;
621
- let hostPort;
622
- if (config.port === "auto") {
623
- port = await resolvePort({ preferred: defaultPort, strategy: "auto" });
624
- hostPort = port;
625
- } else if (typeof config.port === "number") {
626
- port = config.port;
627
- hostPort = config.port;
628
- } else if (config.port && typeof config.port === "object") {
629
- const { start, end } = config.port;
630
- const startPort = start ?? defaultPort;
631
- const endPort = end ?? startPort + 100;
632
- port = await resolvePort({ preferred: startPort, strategy: "range", range: [startPort, endPort] });
633
- hostPort = port;
708
+ let containerPort = 80;
709
+ if (typeof config.port === "number") {
710
+ containerPort = config.port;
711
+ } else if (config.port && typeof config.port === "object" && config.port.start) {
712
+ containerPort = config.port.start;
634
713
  }
714
+ const { port, hostPort } = await resolveServicePorts(config.port, containerPort);
635
715
  return {
636
716
  name,
637
717
  image: config.image,
638
718
  port,
639
719
  hostPort,
640
- env: config.env ?? {},
641
- volumes: config.volumes ?? [],
720
+ env: { ...config.env },
721
+ volumes: [...config.volumes ?? []],
642
722
  command: config.command,
643
- healthcheck: config.command,
723
+ healthcheck: config.healthcheck,
644
724
  ports: []
645
725
  };
646
726
  }
727
+ function pluginServiceDefinitions(plugins) {
728
+ const definitions = /* @__PURE__ */ new Map();
729
+ for (const plugin of plugins ?? []) {
730
+ for (const [name, def] of Object.entries(plugin.services ?? {})) {
731
+ definitions.set(name, { ...def, name });
732
+ }
733
+ }
734
+ return definitions;
735
+ }
647
736
  async function resolveConfig(config) {
648
737
  let finalConfig = config;
649
738
  if (config.preset) {
650
739
  finalConfig = mergePreset(config, config.preset);
651
740
  }
652
741
  finalConfig = normalizeConfig(finalConfig);
653
- const appPort = finalConfig.app.port === "auto" ? await resolvePort({ preferred: 3e3, strategy: "auto" }) : finalConfig.app.port;
654
- const app = normalizeAppConfig({ ...finalConfig.app, port: appPort });
742
+ const appConfig = finalConfig.app ?? {};
743
+ const appPort = appConfig.port === "auto" ? await resolvePort({ preferred: 3e3, strategy: "auto" }) : appConfig.port;
744
+ const app = normalizeAppConfig({ ...appConfig, port: appPort });
745
+ const definitions = pluginServiceDefinitions(finalConfig.plugins);
655
746
  const services2 = {};
656
- if (finalConfig.services) {
657
- for (const [name, serviceConfig] of Object.entries(finalConfig.services)) {
658
- if (serviceConfig) {
659
- services2[name] = await resolveServiceConfig(
660
- name,
661
- serviceConfig,
662
- finalConfig.name
663
- );
664
- }
747
+ for (const [name, serviceConfig] of Object.entries(finalConfig.services ?? {})) {
748
+ if (serviceConfig) {
749
+ services2[name] = await resolveServiceConfig(
750
+ name,
751
+ serviceConfig,
752
+ finalConfig.name,
753
+ definitions
754
+ );
665
755
  }
666
756
  }
667
757
  return {
@@ -684,31 +774,73 @@ function isEnvVarName(value) {
684
774
  }
685
775
  function isVersion(value) {
686
776
  if (typeof value !== "string") return false;
687
- if (value.length === 0) return false;
688
- return /^[a-zA-Z0-9.\-]+$/.test(value);
777
+ return /^\w[\w.-]{0,127}$/.test(value);
689
778
  }
690
779
  function isProjectName(value) {
691
780
  if (typeof value !== "string") return false;
692
781
  if (value.length === 0 || value.length > 100) return false;
693
782
  return /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(value);
694
783
  }
784
+ function isComposeServiceName(value) {
785
+ if (typeof value !== "string") return false;
786
+ return /^[a-zA-Z0-9][\w.-]{0,62}$/.test(value);
787
+ }
788
+ var DOMAIN_COMPONENT = "(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])";
789
+ var DOMAIN = `${DOMAIN_COMPONENT}(?:\\.${DOMAIN_COMPONENT})*(?::[0-9]+)?`;
790
+ var PATH_COMPONENT = "[a-z0-9]+(?:(?:[._]|__|[-]+)[a-z0-9]+)*";
791
+ var TAG = "\\w[\\w.-]{0,127}";
792
+ var DIGEST = "[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*:[0-9a-fA-F]{32,}";
793
+ var IMAGE_REFERENCE = new RegExp(
794
+ `^(?:${DOMAIN}/)?${PATH_COMPONENT}(?:/${PATH_COMPONENT})*(?::${TAG})?(?:@${DIGEST})?$`
795
+ );
796
+ function isDockerImage(value) {
797
+ if (typeof value !== "string") return false;
798
+ if (value.length === 0 || value.length > 255) return false;
799
+ return IMAGE_REFERENCE.test(value);
800
+ }
801
+ function isHealthcheckPath(value) {
802
+ if (typeof value !== "string") return false;
803
+ return value.length <= 2048 && /^\/[\w\-.~%/?=&+,;:@]*$/.test(value);
804
+ }
805
+ function isSingleLine(value) {
806
+ return typeof value === "string" && !/[\r\n\0]/.test(value);
807
+ }
808
+ function isContainerPath(value) {
809
+ return typeof value === "string" && /^\/[\w./-]*$/.test(value);
810
+ }
811
+ function namedVolume(spec) {
812
+ const index = spec.indexOf(":");
813
+ if (index <= 0) return void 0;
814
+ const source = spec.slice(0, index);
815
+ return /^[a-zA-Z0-9][\w.-]*$/.test(source) ? source : void 0;
816
+ }
695
817
 
696
818
  // src/core/validator.ts
819
+ var VALID_OUTPUT_FILES = ["dockerfile", "compose", "dockerignore", "env", "scripts", "makefile"];
697
820
  function validateProjectName(name) {
698
- const errors = [];
699
- if (!isProjectName(name)) {
700
- errors.push({
701
- code: "INVALID_NAME",
702
- message: `Invalid project name '${name}'. Must start with a letter and contain only letters, numbers, hyphens, and underscores.`,
703
- path: "name",
704
- value: name
705
- });
706
- }
707
- return errors;
821
+ if (isProjectName(name)) return [];
822
+ return [{
823
+ code: "INVALID_NAME",
824
+ message: `Invalid project name '${String(name)}'. Must start with a letter and contain only letters, numbers, hyphens, and underscores.`,
825
+ path: "name",
826
+ value: name
827
+ }];
828
+ }
829
+ function validateStringList(value, path) {
830
+ if (value === void 0) return [];
831
+ if (!Array.isArray(value)) {
832
+ return [{ code: "INVALID_TYPE", message: `'${path}' must be an array of strings.`, path, value }];
833
+ }
834
+ return value.filter((item) => !isSingleLine(item) || item === "").map((item) => ({
835
+ code: "INVALID_VALUE",
836
+ message: `Invalid entry ${JSON.stringify(item)} in '${path}'. Entries must be non-empty single-line strings.`,
837
+ path,
838
+ value: item
839
+ }));
708
840
  }
709
841
  function validateAppConfig(config) {
710
842
  const errors = [];
711
- if (config.port !== "auto" && !isPort(config.port)) {
843
+ if (config.port !== void 0 && config.port !== "auto" && !isPort(config.port)) {
712
844
  errors.push({
713
845
  code: "INVALID_PORT",
714
846
  message: `Invalid app port '${String(config.port)}'. Must be a number between 1-65535 or 'auto'.`,
@@ -719,54 +851,163 @@ function validateAppConfig(config) {
719
851
  if (config.node !== void 0 && !isVersion(config.node)) {
720
852
  errors.push({
721
853
  code: "INVALID_VERSION",
722
- message: `Invalid Node.js version '${config.node}'.`,
854
+ message: `Invalid Node.js version '${String(config.node)}'. Must be a valid Docker image tag.`,
723
855
  path: "app.node",
724
856
  value: config.node
725
857
  });
726
858
  }
727
- if (config.env) {
728
- for (const envVar of config.env) {
729
- if (!isEnvVarName(envVar)) {
730
- errors.push({
731
- code: "INVALID_ENV_VAR",
732
- message: `Invalid environment variable name '${envVar}'. Must be uppercase letters, numbers, and underscores.`,
733
- path: "app.env",
734
- value: envVar
735
- });
859
+ if (config.workdir !== void 0 && !isContainerPath(config.workdir)) {
860
+ errors.push({
861
+ code: "INVALID_WORKDIR",
862
+ message: `Invalid workdir '${String(config.workdir)}'. Must be an absolute path made of letters, numbers, '.', '_', '-' and '/'.`,
863
+ path: "app.workdir",
864
+ value: config.workdir
865
+ });
866
+ }
867
+ for (const key of ["command", "buildCommand"]) {
868
+ const value = config[key];
869
+ if (value !== void 0 && !isSingleLine(value)) {
870
+ errors.push({
871
+ code: "INVALID_COMMAND",
872
+ message: `Invalid app.${key}: must be a single-line string.`,
873
+ path: `app.${key}`,
874
+ value
875
+ });
876
+ }
877
+ }
878
+ if (config.command !== void 0 && config.command.trim() === "") {
879
+ errors.push({
880
+ code: "INVALID_COMMAND",
881
+ message: "Invalid app.command: must not be empty.",
882
+ path: "app.command",
883
+ value: config.command
884
+ });
885
+ }
886
+ if (config.healthcheck !== void 0 && !isHealthcheckPath(config.healthcheck)) {
887
+ errors.push({
888
+ code: "INVALID_HEALTHCHECK",
889
+ message: `Invalid health check path '${String(config.healthcheck)}'. Must start with '/' and contain only URL path characters (no quotes, spaces, '$' or backslashes).`,
890
+ path: "app.healthcheck",
891
+ value: config.healthcheck
892
+ });
893
+ }
894
+ if (config.env !== void 0) {
895
+ if (!Array.isArray(config.env)) {
896
+ errors.push({ code: "INVALID_TYPE", message: `'app.env' must be an array of variable names.`, path: "app.env", value: config.env });
897
+ } else {
898
+ for (const envVar of config.env) {
899
+ if (!isEnvVarName(envVar)) {
900
+ errors.push({
901
+ code: "INVALID_ENV_VAR",
902
+ message: `Invalid environment variable name '${String(envVar)}'. Must be uppercase letters, numbers, and underscores.`,
903
+ path: "app.env",
904
+ value: envVar
905
+ });
906
+ }
736
907
  }
737
908
  }
738
909
  }
910
+ errors.push(...validateStringList(config.volumes, "app.volumes"));
739
911
  return errors;
740
912
  }
913
+ function validateServicePort(name, port) {
914
+ if (port === void 0 || port === "auto" || isPort(port)) return [];
915
+ if (port && typeof port === "object" && !Array.isArray(port)) {
916
+ const { start, end } = port;
917
+ if (isPort(start) && (end === void 0 || isPort(end) && end >= start)) {
918
+ return [];
919
+ }
920
+ }
921
+ return [{
922
+ code: "INVALID_PORT",
923
+ message: `Invalid port configuration for service '${name}'. Must be a port number (1-65535), 'auto', or a range { start, end } with start <= end.`,
924
+ path: `services.${name}.port`,
925
+ value: port
926
+ }];
927
+ }
741
928
  function validateServiceConfig(name, config) {
742
929
  const errors = [];
743
- if (config.version !== void 0 && !isVersion(config.version)) {
930
+ if (!isComposeServiceName(name)) {
931
+ errors.push({
932
+ code: "INVALID_SERVICE_NAME",
933
+ message: `Invalid service name '${name}'. Must start with a letter or digit and contain only letters, digits, '.', '_' and '-'.`,
934
+ path: `services.${name}`,
935
+ value: name
936
+ });
937
+ }
938
+ if (typeof config !== "object" || config === null || Array.isArray(config)) {
939
+ errors.push({
940
+ code: "INVALID_TYPE",
941
+ message: `Service '${name}' must be configured with an object.`,
942
+ path: `services.${name}`,
943
+ value: config
944
+ });
945
+ return errors;
946
+ }
947
+ const svc = config;
948
+ if (svc.version !== void 0 && !isVersion(svc.version)) {
744
949
  errors.push({
745
950
  code: "INVALID_VERSION",
746
- message: `Invalid version '${config.version}' for service '${name}'.`,
951
+ message: `Invalid version '${String(svc.version)}' for service '${name}'. Must be a valid Docker image tag.`,
747
952
  path: `services.${name}.version`,
748
- value: config.version
953
+ value: svc.version
749
954
  });
750
955
  }
751
- if (config.port !== void 0 && config.port !== "auto" && typeof config.port !== "number" && typeof config.port !== "object") {
956
+ if (svc.image !== void 0 && !isDockerImage(svc.image)) {
752
957
  errors.push({
753
- code: "INVALID_PORT",
754
- message: `Invalid port configuration for service '${name}'. Must be a number, 'auto', or a range object.`,
755
- path: `services.${name}.port`,
756
- value: config.port
958
+ code: "INVALID_IMAGE",
959
+ message: `Invalid image '${String(svc.image)}' for service '${name}'. Must be a Docker image reference such as 'elasticsearch:8.11.0'.`,
960
+ path: `services.${name}.image`,
961
+ value: svc.image
757
962
  });
758
963
  }
964
+ errors.push(...validateServicePort(name, svc.port));
965
+ if (svc.env !== void 0) {
966
+ if (typeof svc.env !== "object" || svc.env === null || Array.isArray(svc.env)) {
967
+ errors.push({ code: "INVALID_TYPE", message: `'services.${name}.env' must be an object of strings.`, path: `services.${name}.env`, value: svc.env });
968
+ } else {
969
+ for (const [key, value] of Object.entries(svc.env)) {
970
+ if (key === "" || /[=\s]/.test(key) || typeof value !== "string") {
971
+ errors.push({
972
+ code: "INVALID_ENV_VAR",
973
+ message: `Invalid environment variable '${key}' for service '${name}'. Names must not be empty or contain '=' or whitespace, and values must be strings.`,
974
+ path: `services.${name}.env.${key}`,
975
+ value
976
+ });
977
+ }
978
+ }
979
+ }
980
+ }
981
+ for (const key of ["user", "password", "database", "rootPassword", "command", "healthcheck"]) {
982
+ const value = svc[key];
983
+ if (value !== void 0 && typeof value !== "string") {
984
+ errors.push({
985
+ code: "INVALID_TYPE",
986
+ message: `'services.${name}.${key}' must be a string.`,
987
+ path: `services.${name}.${key}`,
988
+ value
989
+ });
990
+ }
991
+ }
992
+ errors.push(...validateStringList(svc.volumes, `services.${name}.volumes`));
759
993
  return errors;
760
994
  }
761
995
  function validateOutputConfig(config) {
762
996
  const errors = [];
763
- if (config?.files) {
764
- const validFiles = ["dockerfile", "compose", "dockerignore", "env", "scripts", "makefile"];
997
+ if (config.dir !== void 0 && (typeof config.dir !== "string" || config.dir === "" || config.dir.includes("\0"))) {
998
+ errors.push({
999
+ code: "INVALID_OUTPUT_DIR",
1000
+ message: "output.dir must be a non-empty path.",
1001
+ path: "output.dir",
1002
+ value: config.dir
1003
+ });
1004
+ }
1005
+ if (config.files) {
765
1006
  for (const file of config.files) {
766
- if (!validFiles.includes(file)) {
1007
+ if (!VALID_OUTPUT_FILES.includes(file)) {
767
1008
  errors.push({
768
1009
  code: "INVALID_OUTPUT_FILE",
769
- message: `Invalid output file '${file}'. Must be one of: ${validFiles.join(", ")}.`,
1010
+ message: `Invalid output file '${String(file)}'. Must be one of: ${VALID_OUTPUT_FILES.join(", ")}.`,
770
1011
  path: "output.files",
771
1012
  value: file
772
1013
  });
@@ -777,13 +1018,19 @@ function validateOutputConfig(config) {
777
1018
  }
778
1019
  function validateConfig(config) {
779
1020
  const errors = [];
1021
+ if (typeof config !== "object" || config === null) {
1022
+ return {
1023
+ valid: false,
1024
+ errors: [{ code: "INVALID_CONFIG", message: "Configuration must be an object.", value: config }]
1025
+ };
1026
+ }
780
1027
  errors.push(...validateProjectName(config.name));
781
1028
  if (config.app) {
782
1029
  errors.push(...validateAppConfig(config.app));
783
1030
  }
784
1031
  if (config.services) {
785
1032
  for (const [name, serviceConfig] of Object.entries(config.services)) {
786
- if (serviceConfig) {
1033
+ if (serviceConfig !== void 0) {
787
1034
  errors.push(...validateServiceConfig(name, serviceConfig));
788
1035
  }
789
1036
  }
@@ -798,18 +1045,23 @@ function validateConfig(config) {
798
1045
  }
799
1046
  function validateResolvedConfig(config) {
800
1047
  const errors = [];
801
- const usedPorts = /* @__PURE__ */ new Set();
802
- usedPorts.add(config.app.port);
1048
+ const usedPorts = /* @__PURE__ */ new Map();
1049
+ usedPorts.set(config.app.port, "app");
803
1050
  for (const [serviceName, serviceConfig] of Object.entries(config.services)) {
804
- if (usedPorts.has(serviceConfig.port)) {
805
- errors.push({
806
- code: "PORT_CONFLICT",
807
- message: `Port ${serviceConfig.port} is already in use by ${serviceName}.`,
808
- path: `services.${serviceName}.port`,
809
- value: serviceConfig.port
810
- });
1051
+ const published = [serviceConfig.hostPort ?? serviceConfig.port, ...serviceConfig.ports ?? []];
1052
+ for (const port of published) {
1053
+ const owner = usedPorts.get(port);
1054
+ if (owner !== void 0) {
1055
+ errors.push({
1056
+ code: "PORT_CONFLICT",
1057
+ message: `Host port ${port} of service '${serviceName}' is already published by '${owner}'.`,
1058
+ path: `services.${serviceName}.port`,
1059
+ value: port
1060
+ });
1061
+ } else {
1062
+ usedPorts.set(port, serviceName);
1063
+ }
811
1064
  }
812
- usedPorts.add(serviceConfig.port);
813
1065
  }
814
1066
  return {
815
1067
  valid: errors.length === 0,
@@ -817,11 +1069,24 @@ function validateResolvedConfig(config) {
817
1069
  };
818
1070
  }
819
1071
 
1072
+ // src/generators/healthcheck.ts
1073
+ function nodeHealthcheckScript(port, path) {
1074
+ 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))`;
1075
+ }
1076
+
820
1077
  // src/generators/dockerfile.ts
1078
+ function dockerCmd(command) {
1079
+ const words = command.trim().split(/\s+/);
1080
+ if (words.every((word) => /^[\w@%+=:,./-]+$/.test(word))) {
1081
+ return `CMD ${JSON.stringify(words).replace(/","/g, '", "')}`;
1082
+ }
1083
+ return `CMD ${command.trim()}`;
1084
+ }
821
1085
  function generateDockerfile(config, _context) {
822
- const { app, name } = config;
1086
+ const { app } = config;
823
1087
  const { node, workdir, command, buildCommand, multiStage, healthcheck } = app;
824
1088
  const port = app.port;
1089
+ const hasBuild = buildCommand.trim() !== "";
825
1090
  let dockerfile = "";
826
1091
  if (multiStage) {
827
1092
  dockerfile += `# Builder stage
@@ -847,11 +1112,13 @@ function generateDockerfile(config, _context) {
847
1112
  dockerfile += `COPY . .
848
1113
 
849
1114
  `;
850
- dockerfile += `# Build application
1115
+ if (hasBuild) {
1116
+ dockerfile += `# Build application
851
1117
  `;
852
- dockerfile += `RUN npm run build 2>/dev/null || true
1118
+ dockerfile += `RUN ${buildCommand.trim()}
853
1119
 
854
1120
  `;
1121
+ }
855
1122
  dockerfile += `# Production stage
856
1123
  `;
857
1124
  dockerfile += `FROM node:${node}
@@ -865,13 +1132,19 @@ function generateDockerfile(config, _context) {
865
1132
  `;
866
1133
  dockerfile += `# Copy from builder
867
1134
  `;
868
- dockerfile += `COPY --from=builder ${workdir}/node_modules ./node_modules
1135
+ if (hasBuild) {
1136
+ dockerfile += `COPY --from=builder ${workdir}/node_modules ./node_modules
869
1137
  `;
870
- dockerfile += `COPY --from=builder ${workdir}/dist ./dist
1138
+ dockerfile += `COPY --from=builder ${workdir}/dist ./dist
1139
+ `;
1140
+ dockerfile += `COPY --from=builder ${workdir}/package*.json ./
1141
+
871
1142
  `;
872
- dockerfile += `COPY --from=builder ${workdir}/package*.json ./
1143
+ } else {
1144
+ dockerfile += `COPY --from=builder ${workdir} ./
873
1145
 
874
1146
  `;
1147
+ }
875
1148
  } else {
876
1149
  dockerfile += `FROM node:${node}
877
1150
 
@@ -902,180 +1175,196 @@ function generateDockerfile(config, _context) {
902
1175
 
903
1176
  `;
904
1177
  if (healthcheck) {
1178
+ const script = JSON.stringify(nodeHealthcheckScript(port, healthcheck));
905
1179
  dockerfile += `HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \\
906
- CMD node -e "require('http').get('http://localhost:${port}${healthcheck}', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})" || exit 1
1180
+ `;
1181
+ dockerfile += ` CMD ["node", "-e", ${script}]
907
1182
 
908
1183
  `;
909
1184
  }
910
- dockerfile += `CMD ["npm", "start"]
1185
+ dockerfile += `${dockerCmd(command)}
911
1186
  `;
912
1187
  return dockerfile;
913
1188
  }
914
1189
 
915
1190
  // src/utils/yaml.ts
1191
+ var PLAIN_SCALAR = /^[A-Za-z_/.][\w./=@+~-]*$/;
1192
+ var NUMBER_LIKE = /^\.(?:\d|inf$|nan$)/i;
1193
+ var DURATION = /^\d+(?:\.\d+)?(?:ns|us|ms|s|m|h)$/;
1194
+ var RESERVED_WORD = /^(?:y|n|yes|no|on|off|true|false|null)$/i;
916
1195
  function toYaml(obj, indent = 0) {
917
- const spaces = " ".repeat(indent);
918
- if (obj === null) {
1196
+ if (isInline(obj)) {
1197
+ return inlineValue(obj);
1198
+ }
1199
+ if (Array.isArray(obj)) {
1200
+ return arrayToYaml(obj, indent);
1201
+ }
1202
+ return objectToYaml(obj, indent);
1203
+ }
1204
+ function isInline(value) {
1205
+ if (value === null || typeof value !== "object") {
1206
+ return true;
1207
+ }
1208
+ if (Array.isArray(value)) {
1209
+ return value.every((item) => item === null || item === void 0 || typeof item !== "object");
1210
+ }
1211
+ return Object.values(value).every((item) => item === void 0);
1212
+ }
1213
+ function inlineValue(value) {
1214
+ if (value === null || value === void 0) {
919
1215
  return "null";
920
1216
  }
921
- if (typeof obj === "string") {
922
- return quoteStringIfNeeded(obj);
1217
+ if (typeof value === "string") {
1218
+ return yamlScalar(value);
923
1219
  }
924
- if (typeof obj === "number" || typeof obj === "boolean") {
925
- return String(obj);
1220
+ if (typeof value === "number") {
1221
+ if (Number.isFinite(value)) return String(value);
1222
+ if (Number.isNaN(value)) return ".nan";
1223
+ return value > 0 ? ".inf" : "-.inf";
926
1224
  }
927
- if (Array.isArray(obj)) {
928
- return arrayToYaml(obj, indent);
1225
+ if (typeof value === "boolean") {
1226
+ return String(value);
1227
+ }
1228
+ if (Array.isArray(value)) {
1229
+ return `[${value.map((item) => inlineValue(item)).join(", ")}]`;
929
1230
  }
930
- if (typeof obj === "object") {
931
- return objectToYaml(obj, indent);
1231
+ if (typeof value === "object") {
1232
+ return "{}";
932
1233
  }
933
- return String(obj);
1234
+ return JSON.stringify(String(value));
934
1235
  }
935
1236
  function arrayToYaml(arr, indent) {
936
1237
  const spaces = " ".repeat(indent);
937
- const innerSpaces = " ".repeat(indent + 2);
938
- if (arr.length === 0) {
939
- return "[]";
940
- }
941
- if (arr.every(
942
- (item) => typeof item === "string" || typeof item === "number" || typeof item === "boolean" || item === null
943
- )) {
944
- const items = arr.map((item) => toYaml(item, 0)).join(", ");
945
- return `[${items}]`;
946
- }
947
1238
  const lines = [];
948
1239
  for (const item of arr) {
949
- const value = toYaml(item, indent + 2);
950
- if (value.includes("\n")) {
951
- lines.push(`${spaces}- ${value.slice(indent + 2)}`);
1240
+ if (isInline(item)) {
1241
+ lines.push(`${spaces}- ${inlineValue(item)}`);
952
1242
  } else {
953
- lines.push(`${spaces}- ${value}`);
1243
+ const block = toYaml(item, indent + 2);
1244
+ lines.push(`${spaces}- ${block.slice(indent + 2)}`);
954
1245
  }
955
1246
  }
956
1247
  return lines.join("\n");
957
1248
  }
958
1249
  function objectToYaml(obj, indent) {
959
- const keys = Object.keys(obj);
960
- if (keys.length === 0) {
961
- return "{}";
962
- }
963
1250
  const spaces = " ".repeat(indent);
964
1251
  const lines = [];
965
- for (const key of keys) {
966
- const value = obj[key];
967
- const valueStr = toYaml(value, indent + 2);
968
- if (valueStr.includes("\n")) {
969
- lines.push(`${spaces}${key}:`);
970
- lines.push(valueStr);
1252
+ for (const [key, value] of Object.entries(obj)) {
1253
+ if (value === void 0) continue;
1254
+ const yamlKey = yamlScalar(key);
1255
+ if (isInline(value)) {
1256
+ lines.push(`${spaces}${yamlKey}: ${inlineValue(value)}`);
971
1257
  } else {
972
- lines.push(`${spaces}${key}: ${valueStr}`);
1258
+ lines.push(`${spaces}${yamlKey}:`);
1259
+ lines.push(toYaml(value, indent + 2));
973
1260
  }
974
1261
  }
975
1262
  return lines.join("\n");
976
1263
  }
977
- function quoteStringIfNeeded(str) {
978
- if (str === "" || str.startsWith('"') || str.startsWith("'")) {
979
- return `"${escapeString(str)}"`;
980
- }
981
- if (/^[\-\?:\[\]{},&*#|!<>@%'"`]/.test(str)) {
982
- return `"${escapeString(str)}"`;
983
- }
984
- if (/[:\s#]/.test(str)) {
985
- return `"${escapeString(str)}"`;
1264
+ function yamlScalar(str) {
1265
+ if ((PLAIN_SCALAR.test(str) || DURATION.test(str)) && !RESERVED_WORD.test(str) && !NUMBER_LIKE.test(str)) {
1266
+ return str;
986
1267
  }
987
- if (/^(true|false|null|NaN|Infinity|\-?\d+(\.\d+)?)$/.test(str)) {
988
- return `"${escapeString(str)}"`;
989
- }
990
- return escapeString(str);
991
- }
992
- function escapeString(str) {
993
- return str.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
1268
+ return JSON.stringify(str);
994
1269
  }
995
1270
 
996
1271
  // src/generators/compose.ts
997
- function generateCompose(config, context) {
998
- const { name, app, services: services2 } = config;
999
- const compose = {
1000
- version: "3.9",
1001
- services: {
1002
- app: {
1003
- build: ".",
1004
- ports: [`${app.port}:${app.port}`],
1005
- environment: generateAppEnvironment(config, context),
1006
- depends_on: Object.keys(services2),
1007
- volumes: app.volumes.length > 0 ? app.volumes : void 0
1008
- }
1009
- },
1010
- volumes: generateVolumeDefinitions(services2)
1272
+ function composeLiteral(value) {
1273
+ return value.replace(/\$/g, "$$$$");
1274
+ }
1275
+ function generateCompose(config, _context) {
1276
+ const { app, services: services2 } = config;
1277
+ const appService = {
1278
+ build: ".",
1279
+ ports: [`${app.port}:${app.port}`],
1280
+ environment: generateAppEnvironment(config),
1281
+ depends_on: Object.keys(services2),
1282
+ volumes: app.volumes.length > 0 ? app.volumes : void 0
1011
1283
  };
1012
- const servicesRecord = compose.services;
1013
- if (app.healthcheck && servicesRecord.app) {
1014
- servicesRecord.app.healthcheck = {
1015
- test: [`CMD`, `curl`, `-f`, `http://localhost:${app.port}${app.healthcheck}`],
1284
+ if (app.healthcheck) {
1285
+ appService.healthcheck = {
1286
+ test: ["CMD", "node", "-e", nodeHealthcheckScript(app.port, app.healthcheck)],
1016
1287
  interval: "30s",
1017
1288
  timeout: "3s",
1018
1289
  retries: 3
1019
1290
  };
1020
1291
  }
1292
+ const composeServices = { app: appService };
1021
1293
  for (const [serviceName, serviceConfig] of Object.entries(services2)) {
1022
- servicesRecord[serviceName] = generateServiceConfig(serviceName, serviceConfig);
1294
+ composeServices[serviceName] = generateServiceConfig(serviceConfig);
1023
1295
  }
1024
- return toYaml(compose);
1296
+ const compose = {
1297
+ version: "3.9",
1298
+ services: composeServices,
1299
+ volumes: generateVolumeDefinitions(config)
1300
+ };
1301
+ return `${toYaml(compose)}
1302
+ `;
1025
1303
  }
1026
- function generateAppEnvironment(config, context) {
1304
+ function generateAppEnvironment(config) {
1027
1305
  const env = ["NODE_ENV=production", `PORT=${config.app.port}`];
1306
+ const add = (key, value) => {
1307
+ env.push(`${key}=${composeLiteral(String(value))}`);
1308
+ };
1028
1309
  for (const [serviceName, serviceConfig] of Object.entries(config.services)) {
1029
1310
  if (serviceConfig.connectionString) {
1030
- const key = `${serviceName.toUpperCase()}_URL`;
1031
- env.push(`${key}=${serviceConfig.connectionString}`);
1311
+ const key = `${serviceName.toUpperCase().replace(/[^A-Z0-9_]/g, "_")}_URL`;
1312
+ add(key, serviceConfig.connectionString);
1032
1313
  }
1033
1314
  }
1034
1315
  if (config.services.postgres) {
1035
1316
  const pg = config.services.postgres;
1036
- env.push(`POSTGRES_HOST=${pg.name}`);
1037
- env.push(`POSTGRES_PORT=${pg.port}`);
1038
- env.push(`POSTGRES_USER=${pg.env.POSTGRES_USER || "postgres"}`);
1039
- env.push(`POSTGRES_PASSWORD=${pg.env.POSTGRES_PASSWORD || "postgres"}`);
1040
- env.push(`POSTGRES_DB=${pg.env.POSTGRES_DB || config.name}`);
1317
+ add("POSTGRES_HOST", pg.name);
1318
+ add("POSTGRES_PORT", pg.port);
1319
+ add("POSTGRES_USER", pg.env.POSTGRES_USER || "postgres");
1320
+ add("POSTGRES_PASSWORD", pg.env.POSTGRES_PASSWORD || "postgres");
1321
+ add("POSTGRES_DB", pg.env.POSTGRES_DB || config.name);
1041
1322
  }
1042
1323
  if (config.services.mysql) {
1043
1324
  const mysql = config.services.mysql;
1044
- env.push(`MYSQL_HOST=${mysql.name}`);
1045
- env.push(`MYSQL_PORT=${mysql.port}`);
1046
- env.push(`MYSQL_USER=${mysql.env.MYSQL_USER || "root"}`);
1047
- env.push(`MYSQL_PASSWORD=${mysql.env.MYSQL_PASSWORD || mysql.env.MYSQL_ROOT_PASSWORD || "root"}`);
1048
- env.push(`MYSQL_DATABASE=${mysql.env.MYSQL_DATABASE || config.name}`);
1325
+ add("MYSQL_HOST", mysql.name);
1326
+ add("MYSQL_PORT", mysql.port);
1327
+ add("MYSQL_USER", mysql.env.MYSQL_USER || "root");
1328
+ add("MYSQL_PASSWORD", mysql.env.MYSQL_PASSWORD || mysql.env.MYSQL_ROOT_PASSWORD || "root");
1329
+ add("MYSQL_DATABASE", mysql.env.MYSQL_DATABASE || config.name);
1049
1330
  }
1050
1331
  if (config.services.mongo) {
1051
1332
  const mongo = config.services.mongo;
1052
- env.push(`MONGO_HOST=${mongo.name}`);
1053
- env.push(`MONGO_PORT=${mongo.port}`);
1054
- env.push(`MONGO_USER=${mongo.env.MONGO_INITDB_ROOT_USERNAME || "mongo"}`);
1055
- env.push(`MONGO_PASSWORD=${mongo.env.MONGO_INITDB_ROOT_PASSWORD || "mongo"}`);
1056
- env.push(`MONGO_DATABASE=${mongo.env.MONGO_INITDB_DATABASE || config.name}`);
1333
+ add("MONGO_HOST", mongo.name);
1334
+ add("MONGO_PORT", mongo.port);
1335
+ add("MONGO_USER", mongo.env.MONGO_INITDB_ROOT_USERNAME || "mongo");
1336
+ add("MONGO_PASSWORD", mongo.env.MONGO_INITDB_ROOT_PASSWORD || "mongo");
1337
+ add("MONGO_DATABASE", mongo.env.MONGO_INITDB_DATABASE || config.name);
1057
1338
  }
1058
1339
  if (config.services.redis) {
1059
1340
  const redis = config.services.redis;
1060
- env.push(`REDIS_HOST=${redis.name}`);
1061
- env.push(`REDIS_PORT=${redis.port}`);
1341
+ add("REDIS_HOST", redis.name);
1342
+ add("REDIS_PORT", redis.port);
1343
+ if (redis.env.REDIS_PASSWORD) {
1344
+ add("REDIS_PASSWORD", redis.env.REDIS_PASSWORD);
1345
+ }
1346
+ }
1347
+ for (const name of config.app.env) {
1348
+ if (!env.some((entry) => entry.startsWith(`${name}=`))) {
1349
+ env.push(name);
1350
+ }
1062
1351
  }
1063
1352
  return env;
1064
1353
  }
1065
- function generateServiceConfig(name, config) {
1354
+ function generateServiceConfig(config) {
1355
+ const environment = {};
1356
+ for (const [key, value] of Object.entries(config.env)) {
1357
+ environment[key] = composeLiteral(value);
1358
+ }
1359
+ const portMappings = [`${config.hostPort ?? config.port}:${config.port}`];
1360
+ for (const extraPort of config.ports ?? []) {
1361
+ portMappings.push(`${extraPort}:${extraPort}`);
1362
+ }
1066
1363
  const service = {
1067
1364
  image: config.image,
1068
- ports: [],
1069
- environment: config.env
1365
+ ports: portMappings,
1366
+ environment
1070
1367
  };
1071
- const portMappings = [];
1072
- portMappings.push(`${config.hostPort ?? config.port}:${config.port}`);
1073
- if (config.ports) {
1074
- for (const extraPort of config.ports) {
1075
- portMappings.push(`${extraPort}:${extraPort}`);
1076
- }
1077
- }
1078
- service.ports = portMappings;
1079
1368
  if (config.volumes.length > 0) {
1080
1369
  service.volumes = config.volumes;
1081
1370
  }
@@ -1092,16 +1381,16 @@ function generateServiceConfig(name, config) {
1092
1381
  }
1093
1382
  return service;
1094
1383
  }
1095
- function generateVolumeDefinitions(services2) {
1384
+ function generateVolumeDefinitions(config) {
1096
1385
  const volumes = {};
1097
- for (const serviceConfig of Object.values(services2)) {
1098
- for (const volume of serviceConfig.volumes) {
1099
- if (volume.includes(":")) {
1100
- const [name] = volume.split(":");
1101
- if (name) {
1102
- volumes[name] = null;
1103
- }
1104
- }
1386
+ const specs = [
1387
+ ...config.app.volumes,
1388
+ ...Object.values(config.services).flatMap((service) => service.volumes)
1389
+ ];
1390
+ for (const spec of specs) {
1391
+ const name = namedVolume(spec);
1392
+ if (name) {
1393
+ volumes[name] = {};
1105
1394
  }
1106
1395
  }
1107
1396
  return volumes;
@@ -1116,10 +1405,10 @@ yarn-debug.log*
1116
1405
  yarn-error.log*
1117
1406
  pnpm-debug.log*
1118
1407
 
1119
- # Environment
1408
+ # Environment (secrets must never be copied into the image)
1120
1409
  .env
1121
- .env.local
1122
- .env.*.local
1410
+ .env.*
1411
+ !.env.example
1123
1412
 
1124
1413
  # Git
1125
1414
  .git/
@@ -1179,6 +1468,16 @@ docker-compose.yml
1179
1468
  }
1180
1469
 
1181
1470
  // src/generators/env.ts
1471
+ function envValue(value) {
1472
+ if (/^[\w@%+=:,./?&-]*$/.test(value)) {
1473
+ return value;
1474
+ }
1475
+ if (!/['\r\n]/.test(value)) {
1476
+ return `'${value}'`;
1477
+ }
1478
+ const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r");
1479
+ return `"${escaped}"`;
1480
+ }
1182
1481
  function generateEnvExample(config) {
1183
1482
  let content = `# Application Configuration
1184
1483
  NODE_ENV=production
@@ -1198,17 +1497,17 @@ PORT=${config.app.port}
1198
1497
  content += `
1199
1498
  # PostgreSQL
1200
1499
  `;
1201
- content += `DATABASE_URL=${pg.connectionString || ""}
1500
+ content += `DATABASE_URL=${envValue(String(pg.connectionString || ""))}
1202
1501
  `;
1203
- content += `POSTGRES_HOST=${pg.name}
1502
+ content += `POSTGRES_HOST=${envValue(String(pg.name))}
1204
1503
  `;
1205
- content += `POSTGRES_PORT=${pg.port}
1504
+ content += `POSTGRES_PORT=${envValue(String(pg.port))}
1206
1505
  `;
1207
- content += `POSTGRES_USER=${pg.env.POSTGRES_USER || "postgres"}
1506
+ content += `POSTGRES_USER=${envValue(String(pg.env.POSTGRES_USER || "postgres"))}
1208
1507
  `;
1209
- content += `POSTGRES_PASSWORD=${pg.env.POSTGRES_PASSWORD || "postgres"}
1508
+ content += `POSTGRES_PASSWORD=${envValue(String(pg.env.POSTGRES_PASSWORD || "postgres"))}
1210
1509
  `;
1211
- content += `POSTGRES_DB=${pg.env.POSTGRES_DB || config.name}
1510
+ content += `POSTGRES_DB=${envValue(String(pg.env.POSTGRES_DB || config.name))}
1212
1511
  `;
1213
1512
  }
1214
1513
  if (config.services.mysql) {
@@ -1216,17 +1515,17 @@ PORT=${config.app.port}
1216
1515
  content += `
1217
1516
  # MySQL
1218
1517
  `;
1219
- content += `MYSQL_URL=${mysql.connectionString || ""}
1518
+ content += `MYSQL_URL=${envValue(String(mysql.connectionString || ""))}
1220
1519
  `;
1221
- content += `MYSQL_HOST=${mysql.name}
1520
+ content += `MYSQL_HOST=${envValue(String(mysql.name))}
1222
1521
  `;
1223
- content += `MYSQL_PORT=${mysql.port}
1522
+ content += `MYSQL_PORT=${envValue(String(mysql.port))}
1224
1523
  `;
1225
- content += `MYSQL_USER=${mysql.env.MYSQL_USER || "root"}
1524
+ content += `MYSQL_USER=${envValue(String(mysql.env.MYSQL_USER || "root"))}
1226
1525
  `;
1227
- content += `MYSQL_PASSWORD=${mysql.env.MYSQL_PASSWORD || mysql.env.MYSQL_ROOT_PASSWORD || "root"}
1526
+ content += `MYSQL_PASSWORD=${envValue(String(mysql.env.MYSQL_PASSWORD || mysql.env.MYSQL_ROOT_PASSWORD || "root"))}
1228
1527
  `;
1229
- content += `MYSQL_DATABASE=${mysql.env.MYSQL_DATABASE || config.name}
1528
+ content += `MYSQL_DATABASE=${envValue(String(mysql.env.MYSQL_DATABASE || config.name))}
1230
1529
  `;
1231
1530
  }
1232
1531
  if (config.services.mongo) {
@@ -1234,17 +1533,17 @@ PORT=${config.app.port}
1234
1533
  content += `
1235
1534
  # MongoDB
1236
1535
  `;
1237
- content += `MONGO_URL=${mongo.connectionString || ""}
1536
+ content += `MONGO_URL=${envValue(String(mongo.connectionString || ""))}
1238
1537
  `;
1239
- content += `MONGO_HOST=${mongo.name}
1538
+ content += `MONGO_HOST=${envValue(String(mongo.name))}
1240
1539
  `;
1241
- content += `MONGO_PORT=${mongo.port}
1540
+ content += `MONGO_PORT=${envValue(String(mongo.port))}
1242
1541
  `;
1243
- content += `MONGO_USER=${mongo.env.MONGO_INITDB_ROOT_USERNAME || "mongo"}
1542
+ content += `MONGO_USER=${envValue(String(mongo.env.MONGO_INITDB_ROOT_USERNAME || "mongo"))}
1244
1543
  `;
1245
- content += `MONGO_PASSWORD=${mongo.env.MONGO_INITDB_ROOT_PASSWORD || "mongo"}
1544
+ content += `MONGO_PASSWORD=${envValue(String(mongo.env.MONGO_INITDB_ROOT_PASSWORD || "mongo"))}
1246
1545
  `;
1247
- content += `MONGO_DATABASE=${mongo.env.MONGO_INITDB_DATABASE || config.name}
1546
+ content += `MONGO_DATABASE=${envValue(String(mongo.env.MONGO_INITDB_DATABASE || config.name))}
1248
1547
  `;
1249
1548
  }
1250
1549
  if (config.services.redis) {
@@ -1252,14 +1551,14 @@ PORT=${config.app.port}
1252
1551
  content += `
1253
1552
  # Redis
1254
1553
  `;
1255
- content += `REDIS_URL=${redis.connectionString || ""}
1554
+ content += `REDIS_URL=${envValue(String(redis.connectionString || ""))}
1256
1555
  `;
1257
- content += `REDIS_HOST=${redis.name}
1556
+ content += `REDIS_HOST=${envValue(String(redis.name))}
1258
1557
  `;
1259
- content += `REDIS_PORT=${redis.port}
1558
+ content += `REDIS_PORT=${envValue(String(redis.port))}
1260
1559
  `;
1261
1560
  if (redis.env.REDIS_PASSWORD) {
1262
- content += `REDIS_PASSWORD=${redis.env.REDIS_PASSWORD}
1561
+ content += `REDIS_PASSWORD=${envValue(String(redis.env.REDIS_PASSWORD))}
1263
1562
  `;
1264
1563
  }
1265
1564
  }
@@ -1274,7 +1573,7 @@ function generateBuildScript(_config) {
1274
1573
  set -e
1275
1574
 
1276
1575
  echo "Building Docker image..."
1277
- docker-compose build
1576
+ docker compose build
1278
1577
 
1279
1578
  echo "Build complete!"
1280
1579
  `;
@@ -1287,7 +1586,7 @@ function generateUpScript(config) {
1287
1586
  set -e
1288
1587
 
1289
1588
  echo "Starting services..."
1290
- docker-compose up -d ${services2.join(" ")}
1589
+ docker compose up -d ${services2.join(" ")}
1291
1590
 
1292
1591
  echo "Services started!"
1293
1592
  echo ""
@@ -1301,7 +1600,7 @@ function generateDownScript(_config) {
1301
1600
  set -e
1302
1601
 
1303
1602
  echo "Stopping services..."
1304
- docker-compose down
1603
+ docker compose down
1305
1604
 
1306
1605
  echo "Services stopped!"
1307
1606
  `;
@@ -1313,9 +1612,9 @@ function generateLogsScript(_config) {
1313
1612
  set -e
1314
1613
 
1315
1614
  if [ -n "$1" ]; then
1316
- docker-compose logs -f "$1"
1615
+ docker compose logs -f "$1"
1317
1616
  else
1318
- docker-compose logs -f
1617
+ docker compose logs -f
1319
1618
  fi
1320
1619
  `;
1321
1620
  }
@@ -1342,28 +1641,28 @@ help:
1342
1641
  @echo " make restart - Restart all services"
1343
1642
  @echo " make logs - Show logs from all services"
1344
1643
  @echo " make shell - Open shell in app container"
1345
- @echo " make clean - Remove containers and volumes"
1644
+ @echo " make clean - Remove this project's containers and volumes"
1346
1645
  @echo " make install - Install dependencies"
1347
1646
 
1348
1647
  # Build Docker images
1349
1648
  build:
1350
- docker-compose build
1649
+ docker compose build
1351
1650
 
1352
1651
  # Start all services
1353
1652
  up:
1354
- docker-compose up -d
1653
+ docker compose up -d
1355
1654
  @echo "App running at http://localhost:${config.app.port}"
1356
1655
 
1357
1656
  # Stop all services
1358
1657
  down:
1359
- docker-compose down
1658
+ docker compose down
1360
1659
 
1361
1660
  # Restart all services
1362
1661
  restart: down up
1363
1662
 
1364
1663
  # Show logs from all services
1365
1664
  logs:
1366
- docker-compose logs -f
1665
+ docker compose logs -f
1367
1666
  `;
1368
1667
  if (services2.length > 0) {
1369
1668
  content += "\n";
@@ -1371,23 +1670,22 @@ logs:
1371
1670
  content += `
1372
1671
  logs-${service}:
1373
1672
  `;
1374
- content += ` docker-compose logs -f ${service}
1673
+ content += ` docker compose logs -f ${service}
1375
1674
  `;
1376
1675
  }
1377
1676
  }
1378
1677
  content += `
1379
- # Clean up containers and volumes
1678
+ # Remove this project's containers, networks and volumes
1380
1679
  clean:
1381
- docker-compose down -v
1382
- docker system prune -f
1680
+ docker compose down -v --remove-orphans
1383
1681
 
1384
1682
  # Install dependencies (in running container)
1385
1683
  shell:
1386
- docker-compose exec app sh
1684
+ docker compose exec app sh
1387
1685
 
1388
1686
  # Install dependencies
1389
1687
  install:
1390
- docker-compose exec app npm install
1688
+ docker compose exec app npm install
1391
1689
  `;
1392
1690
  return content;
1393
1691
  }
@@ -1434,18 +1732,20 @@ async function ensureDir(path) {
1434
1732
  }
1435
1733
  }
1436
1734
  }
1437
- async function writeFile(filePath, content) {
1735
+ async function writeFile(filePath, content, mode) {
1438
1736
  const dir = (0, import_path.dirname)(filePath);
1439
1737
  await ensureDir(dir);
1440
- const tempPath = (0, import_path.join)(dir, `.${(0, import_path.basename)(filePath)}.tmp`);
1738
+ const suffix = `${process.pid}.${Date.now().toString(36)}.${Math.random().toString(36).slice(2)}`;
1739
+ const tempPath = (0, import_path.join)(dir, `.${(0, import_path.basename)(filePath)}.${suffix}.tmp`);
1441
1740
  try {
1442
- await import_fs.promises.writeFile(tempPath, content, "utf8");
1741
+ await import_fs.promises.writeFile(tempPath, content, { encoding: "utf8", mode });
1742
+ if (mode !== void 0) {
1743
+ await import_fs.promises.chmod(tempPath, mode);
1744
+ }
1443
1745
  await import_fs.promises.rename(tempPath, filePath);
1444
1746
  } catch (error) {
1445
- try {
1446
- await import_fs.promises.unlink(tempPath);
1447
- } catch {
1448
- }
1747
+ await import_fs.promises.unlink(tempPath).catch(() => {
1748
+ });
1449
1749
  throw error;
1450
1750
  }
1451
1751
  }
@@ -1460,23 +1760,26 @@ async function fileExists(filePath) {
1460
1760
 
1461
1761
  // src/core/dockcraft.ts
1462
1762
  var import_path2 = require("path");
1763
+ function validationError(prefix, errors) {
1764
+ const errorMessages = errors.map((e) => ` - ${e.message}`).join("\n");
1765
+ return new ValidationError(`${prefix}:
1766
+ ${errorMessages}`, errors);
1767
+ }
1768
+ function isSafeOutputPath(fileName) {
1769
+ if (typeof fileName !== "string" || fileName === "" || fileName.includes("\0")) return false;
1770
+ if ((0, import_path2.isAbsolute)(fileName) || /^[a-zA-Z]:/.test(fileName) || fileName.startsWith("\\")) return false;
1771
+ const normalized = (0, import_path2.normalize)(fileName.replace(/\\/g, "/"));
1772
+ return !normalized.split(/[\\/]/).includes("..") && normalized !== ".";
1773
+ }
1463
1774
  async function dockcraft(config, options = {}) {
1464
1775
  const validation = validateConfig(config);
1465
1776
  if (!validation.valid) {
1466
- const errorMessages = validation.errors.map((e) => ` - ${e.message}`).join("\n");
1467
- throw new Error(
1468
- `Configuration validation failed:
1469
- ${errorMessages}`
1470
- );
1777
+ throw validationError("Configuration validation failed", validation.errors);
1471
1778
  }
1472
1779
  const resolved = await resolveConfig(config);
1473
1780
  const resolvedValidation = validateResolvedConfig(resolved);
1474
1781
  if (!resolvedValidation.valid) {
1475
- const errorMessages = resolvedValidation.errors.map((e) => ` - ${e.message}`).join("\n");
1476
- throw new Error(
1477
- `Resolved configuration validation failed:
1478
- ${errorMessages}`
1479
- );
1782
+ throw validationError("Resolved configuration validation failed", resolvedValidation.errors);
1480
1783
  }
1481
1784
  const context = {
1482
1785
  config: resolved,
@@ -1484,22 +1787,38 @@ ${errorMessages}`
1484
1787
  Object.entries(resolved.services).map(([name, svc]) => [name, svc.port])
1485
1788
  ),
1486
1789
  strings: new Map(
1487
- Object.entries(resolved.services).filter(([, svc]) => svc.connectionString).map(([name, svc]) => [name, svc.connectionString])
1790
+ Object.entries(resolved.services).filter((entry) => Boolean(entry[1].connectionString)).map(([name, svc]) => [name, svc.connectionString])
1488
1791
  )
1489
1792
  };
1490
1793
  context.ports.set("app", resolved.app.port);
1491
1794
  const generated = generateAll(resolved, context);
1795
+ for (const plugin of config.plugins ?? []) {
1796
+ for (const output of plugin.outputs ?? []) {
1797
+ if (!isSafeOutputPath(output.file)) {
1798
+ throw new ConfigError(
1799
+ `Plugin '${plugin.name}' output '${output.name}' has an unsafe file name '${output.file}'. Use a relative path inside the output directory.`,
1800
+ "UNSAFE_OUTPUT_PATH"
1801
+ );
1802
+ }
1803
+ if (output.file in generated) {
1804
+ throw new ConfigError(
1805
+ `Plugin '${plugin.name}' output '${output.name}' would overwrite generated file '${output.file}'.`,
1806
+ "DUPLICATE_OUTPUT"
1807
+ );
1808
+ }
1809
+ generated[output.file] = output.generate(resolved, context);
1810
+ }
1811
+ }
1492
1812
  const written = [];
1493
1813
  const outputDir = resolved.output.dir ?? "./";
1494
1814
  if (!options.dryRun) {
1495
1815
  for (const [fileName, content] of Object.entries(generated)) {
1496
- if (!fileName) continue;
1497
1816
  const filePath = (0, import_path2.join)(outputDir, fileName);
1498
1817
  const exists = await fileExists(filePath);
1499
1818
  if (exists && !resolved.output.overwrite) {
1500
1819
  continue;
1501
1820
  }
1502
- await writeFile(filePath, content);
1821
+ await writeFile(filePath, content, fileName.endsWith(".sh") ? 493 : void 0);
1503
1822
  written.push(filePath);
1504
1823
  }
1505
1824
  }
@@ -1546,79 +1865,37 @@ function listDefaultPorts() {
1546
1865
  return { ...DEFAULT_PORTS };
1547
1866
  }
1548
1867
 
1549
- // src/types.ts
1550
- var DockcraftError = class extends Error {
1551
- constructor(message, code) {
1552
- super(message);
1553
- this.code = code;
1554
- this.name = "DockcraftError";
1555
- }
1556
- };
1557
- var ConfigError = class extends DockcraftError {
1558
- constructor(message, code = "CONFIG_ERROR") {
1559
- super(message, code);
1560
- this.name = "ConfigError";
1561
- }
1562
- };
1563
- var ValidationError = class extends DockcraftError {
1564
- constructor(message, errors, code = "VALIDATION_ERROR") {
1565
- super(message, code);
1566
- this.errors = errors;
1567
- this.name = "ValidationError";
1568
- }
1569
- };
1570
- var PortConflictError = class extends DockcraftError {
1571
- constructor(port, code = "PORT_CONFLICT") {
1572
- super(`Port ${port} is already in use`, code);
1573
- this.name = "PortConflictError";
1574
- }
1575
- };
1576
- var NoPortAvailableError = class extends DockcraftError {
1577
- constructor(range, code = "NO_PORT_AVAILABLE") {
1578
- super(`No available port in range ${range[0]}-${range[1]}`, code);
1579
- this.name = "NoPortAvailableError";
1580
- }
1581
- };
1582
- var FileWriteError = class extends DockcraftError {
1583
- constructor(path, code = "FILE_WRITE_ERROR") {
1584
- super(`Failed to write file: ${path}`, code);
1585
- this.name = "FileWriteError";
1586
- }
1587
- };
1588
- var PresetNotFoundError = class extends DockcraftError {
1589
- constructor(name, code = "PRESET_NOT_FOUND") {
1590
- super(`Preset '${name}' not found`, code);
1591
- this.name = "PresetNotFoundError";
1592
- }
1593
- };
1594
- var ServiceNotFoundError = class extends DockcraftError {
1595
- constructor(name, code = "SERVICE_NOT_FOUND") {
1596
- super(`Service '${name}' not found`, code);
1597
- this.name = "ServiceNotFoundError";
1598
- }
1599
- };
1600
-
1601
1868
  // src/index.ts
1602
1869
  function getConnectionString(service, config) {
1870
+ const enc = encodeURIComponent;
1871
+ const { host, port } = config;
1603
1872
  switch (service) {
1604
- case "postgres":
1605
- const pgUser = config.user ?? "postgres";
1606
- const pgPass = config.password ?? "postgres";
1607
- const pgDb = config.database ?? "myapp";
1608
- return `postgres://${pgUser}:${pgPass}@${config.host}:${config.port}/${pgDb}`;
1609
- case "mysql":
1610
- const mysqlUser = config.user ?? "root";
1611
- const mysqlPass = config.password ?? "root";
1612
- const mysqlDb = config.database ?? "myapp";
1613
- return `mysql://${mysqlUser}:${mysqlPass}@${config.host}:${config.port}/${mysqlDb}`;
1873
+ case "postgres": {
1874
+ const user = config.user ?? "postgres";
1875
+ const password = config.password ?? "postgres";
1876
+ const database = config.database ?? "myapp";
1877
+ return `postgres://${enc(user)}:${enc(password)}@${host}:${port}/${enc(database)}`;
1878
+ }
1879
+ case "mysql": {
1880
+ const user = config.user ?? "root";
1881
+ const password = config.password ?? "root";
1882
+ const database = config.database ?? "myapp";
1883
+ return `mysql://${enc(user)}:${enc(password)}@${host}:${port}/${enc(database)}`;
1884
+ }
1614
1885
  case "mongo":
1615
- case "mongodb":
1616
- const mongoUser = config.user ?? "mongo";
1617
- const mongoPass = config.password ?? "mongo";
1618
- const mongoDb = config.database ?? "myapp";
1619
- return `mongodb://${mongoUser}:${mongoPass}@${config.host}:${config.port}/${mongoDb}`;
1620
- case "redis":
1621
- return `redis://${config.host}:${config.port}`;
1886
+ case "mongodb": {
1887
+ const user = config.user ?? "mongo";
1888
+ const password = config.password ?? "mongo";
1889
+ const database = config.database ?? "myapp";
1890
+ return `mongodb://${enc(user)}:${enc(password)}@${host}:${port}/${enc(database)}?authSource=admin`;
1891
+ }
1892
+ case "redis": {
1893
+ if (config.password === void 0 || config.password === "") {
1894
+ return `redis://${host}:${port}`;
1895
+ }
1896
+ const user = config.user ? enc(config.user) : "";
1897
+ return `redis://${user}:${enc(config.password)}@${host}:${port}`;
1898
+ }
1622
1899
  default:
1623
1900
  throw new Error(`Unknown service: ${service}`);
1624
1901
  }