@oxog/dockcraft 1.1.0 → 1.2.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
@@ -84,9 +84,12 @@ var NoPortAvailableError = class extends DockcraftError {
84
84
  }
85
85
  };
86
86
  var FileWriteError = class extends DockcraftError {
87
- constructor(path, code = "FILE_WRITE_ERROR") {
88
- super(`Failed to write file: ${path}`, code);
87
+ constructor(path, code = "FILE_WRITE_ERROR", cause) {
88
+ super(`Failed to write file: ${path}${cause instanceof Error ? ` (${cause.message})` : ""}`, code);
89
89
  this.name = "FileWriteError";
90
+ if (cause !== void 0) {
91
+ this.cause = cause;
92
+ }
90
93
  }
91
94
  };
92
95
  var PresetNotFoundError = class extends DockcraftError {
@@ -545,7 +548,8 @@ async function resolvePort(options = {}) {
545
548
  if (await isPortAvailable(preferred)) {
546
549
  return preferred;
547
550
  }
548
- throw new Error(`Port ${preferred} is already in use`);
551
+ throw new PortConflictError(preferred);
552
+ // @ts-expect-error -- TS7029: the fall-through to 'auto' (no range given) is intended
549
553
  case "range":
550
554
  if (range) {
551
555
  const [start, end = start + 100] = range;
@@ -553,7 +557,7 @@ async function resolvePort(options = {}) {
553
557
  if (port !== void 0) {
554
558
  return port;
555
559
  }
556
- throw new Error(`No available port in range ${start}-${end}`);
560
+ throw new NoPortAvailableError([start, end]);
557
561
  }
558
562
  // Fall through to auto if no range specified
559
563
  case "auto":
@@ -562,7 +566,7 @@ async function resolvePort(options = {}) {
562
566
  if (port !== void 0) {
563
567
  return port;
564
568
  }
565
- throw new Error(`No available port found starting from ${preferred}`);
569
+ throw new NoPortAvailableError([preferred, 65535]);
566
570
  }
567
571
  }
568
572
  }
@@ -930,8 +934,8 @@ function validateServiceConfig(name, config) {
930
934
  if (!isComposeServiceName(name)) {
931
935
  errors.push({
932
936
  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}`,
937
+ message: `Invalid service name '${String(name)}'. Must start with a letter or digit and contain only letters, digits, '.', '_' and '-'.`,
938
+ path: `services.${String(name)}`,
935
939
  value: name
936
940
  });
937
941
  }
@@ -948,6 +952,7 @@ function validateServiceConfig(name, config) {
948
952
  if (svc.version !== void 0 && !isVersion(svc.version)) {
949
953
  errors.push({
950
954
  code: "INVALID_VERSION",
955
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string -- echoes whatever invalid value was given
951
956
  message: `Invalid version '${String(svc.version)}' for service '${name}'. Must be a valid Docker image tag.`,
952
957
  path: `services.${name}.version`,
953
958
  value: svc.version
@@ -956,6 +961,7 @@ function validateServiceConfig(name, config) {
956
961
  if (svc.image !== void 0 && !isDockerImage(svc.image)) {
957
962
  errors.push({
958
963
  code: "INVALID_IMAGE",
964
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string -- echoes whatever invalid value was given
959
965
  message: `Invalid image '${String(svc.image)}' for service '${name}'. Must be a Docker image reference such as 'elasticsearch:8.11.0'.`,
960
966
  path: `services.${name}.image`,
961
967
  value: svc.image
@@ -1268,14 +1274,41 @@ function yamlScalar(str) {
1268
1274
  return JSON.stringify(str);
1269
1275
  }
1270
1276
 
1277
+ // src/generators/paths.ts
1278
+ var import_path = require("path");
1279
+ function currentDir() {
1280
+ return typeof process !== "undefined" && typeof process.cwd === "function" ? process.cwd() : "/";
1281
+ }
1282
+ function outputSubdir(dir) {
1283
+ if (!dir) {
1284
+ return void 0;
1285
+ }
1286
+ const root = currentDir();
1287
+ const subdir = (0, import_path.relative)(root, (0, import_path.isAbsolute)(dir) ? dir : (0, import_path.join)(root, dir)).replace(/\\/g, "/");
1288
+ if (subdir === "" || subdir === ".." || subdir.startsWith("../") || (0, import_path.isAbsolute)(subdir)) {
1289
+ return void 0;
1290
+ }
1291
+ return subdir;
1292
+ }
1293
+ function pathToRoot(subdir) {
1294
+ return subdir.split("/").map(() => "..").join("/");
1295
+ }
1296
+
1271
1297
  // src/generators/compose.ts
1272
1298
  function composeLiteral(value) {
1273
1299
  return value.replace(/\$/g, "$$$$");
1274
1300
  }
1301
+ function composeBuild(outputDir) {
1302
+ const subdir = outputSubdir(outputDir);
1303
+ if (subdir === void 0) {
1304
+ return ".";
1305
+ }
1306
+ return { context: pathToRoot(subdir), dockerfile: `${subdir}/Dockerfile` };
1307
+ }
1275
1308
  function generateCompose(config, _context) {
1276
1309
  const { app, services: services2 } = config;
1277
1310
  const appService = {
1278
- build: ".",
1311
+ build: composeBuild(config.output.dir),
1279
1312
  ports: [`${app.port}:${app.port}`],
1280
1313
  environment: generateAppEnvironment(config),
1281
1314
  depends_on: Object.keys(services2),
@@ -1294,13 +1327,20 @@ function generateCompose(config, _context) {
1294
1327
  composeServices[serviceName] = generateServiceConfig(serviceConfig);
1295
1328
  }
1296
1329
  const compose = {
1297
- version: "3.9",
1298
1330
  services: composeServices,
1299
1331
  volumes: generateVolumeDefinitions(config)
1300
1332
  };
1301
1333
  return `${toYaml(compose)}
1302
1334
  `;
1303
1335
  }
1336
+ function connectionStringVar(serviceName) {
1337
+ return `${serviceName.toUpperCase().replace(/[^A-Z0-9_]/g, "_")}_URL`;
1338
+ }
1339
+ function hasDatabaseUrlAlias(config) {
1340
+ return config.services.postgres !== void 0 && !Object.entries(config.services).some(
1341
+ ([name, service]) => Boolean(service.connectionString) && connectionStringVar(name) === "DATABASE_URL"
1342
+ );
1343
+ }
1304
1344
  function generateAppEnvironment(config) {
1305
1345
  const env = ["NODE_ENV=production", `PORT=${config.app.port}`];
1306
1346
  const add = (key, value) => {
@@ -1308,12 +1348,14 @@ function generateAppEnvironment(config) {
1308
1348
  };
1309
1349
  for (const [serviceName, serviceConfig] of Object.entries(config.services)) {
1310
1350
  if (serviceConfig.connectionString) {
1311
- const key = `${serviceName.toUpperCase().replace(/[^A-Z0-9_]/g, "_")}_URL`;
1312
- add(key, serviceConfig.connectionString);
1351
+ add(connectionStringVar(serviceName), serviceConfig.connectionString);
1313
1352
  }
1314
1353
  }
1315
1354
  if (config.services.postgres) {
1316
1355
  const pg = config.services.postgres;
1356
+ if (pg.connectionString && hasDatabaseUrlAlias(config)) {
1357
+ add("DATABASE_URL", pg.connectionString);
1358
+ }
1317
1359
  add("POSTGRES_HOST", pg.name);
1318
1360
  add("POSTGRES_PORT", pg.port);
1319
1361
  add("POSTGRES_USER", pg.env.POSTGRES_USER || "postgres");
@@ -1397,7 +1439,19 @@ function generateVolumeDefinitions(config) {
1397
1439
  }
1398
1440
 
1399
1441
  // src/generators/dockerignore.ts
1400
- function generateDockerignore(_config) {
1442
+ var DOCKERFILE_IGNORE_FILE = "Dockerfile.dockerignore";
1443
+ function dockerignoreFileName(outputDir) {
1444
+ return outputSubdir(outputDir) === void 0 ? ".dockerignore" : DOCKERFILE_IGNORE_FILE;
1445
+ }
1446
+ function outputDirPatterns(outputDir) {
1447
+ const subdir = outputSubdir(outputDir);
1448
+ if (subdir === void 0) {
1449
+ return "";
1450
+ }
1451
+ return ["Dockerfile", "docker-compose.yml", DOCKERFILE_IGNORE_FILE, ".env", ".env.*"].map((file) => `${subdir}/${file}
1452
+ `).join("");
1453
+ }
1454
+ function generateDockerignore(config) {
1401
1455
  return `# Dependencies
1402
1456
  node_modules/
1403
1457
  npm-debug.log*
@@ -1459,7 +1513,7 @@ temp/
1459
1513
  Dockerfile
1460
1514
  docker-compose.yml
1461
1515
  .dockerignore
1462
-
1516
+ ${outputDirPatterns(config.output.dir)}
1463
1517
  # Package manager lockfiles (optional - uncomment if you want to exclude)
1464
1518
  # package-lock.json
1465
1519
  # yarn.lock
@@ -1468,6 +1522,7 @@ docker-compose.yml
1468
1522
  }
1469
1523
 
1470
1524
  // src/generators/env.ts
1525
+ var BUILT_IN_SERVICES = /* @__PURE__ */ new Set(["postgres", "mysql", "mongo", "redis"]);
1471
1526
  function envValue(value) {
1472
1527
  if (/^[\w@%+=:,./?&-]*$/.test(value)) {
1473
1528
  return value;
@@ -1497,7 +1552,11 @@ PORT=${config.app.port}
1497
1552
  content += `
1498
1553
  # PostgreSQL
1499
1554
  `;
1500
- content += `DATABASE_URL=${envValue(String(pg.connectionString || ""))}
1555
+ if (hasDatabaseUrlAlias(config)) {
1556
+ content += `DATABASE_URL=${envValue(String(pg.connectionString || ""))}
1557
+ `;
1558
+ }
1559
+ content += `POSTGRES_URL=${envValue(String(pg.connectionString || ""))}
1501
1560
  `;
1502
1561
  content += `POSTGRES_HOST=${envValue(String(pg.name))}
1503
1562
  `;
@@ -1559,6 +1618,15 @@ PORT=${config.app.port}
1559
1618
  `;
1560
1619
  if (redis.env.REDIS_PASSWORD) {
1561
1620
  content += `REDIS_PASSWORD=${envValue(String(redis.env.REDIS_PASSWORD))}
1621
+ `;
1622
+ }
1623
+ }
1624
+ for (const [serviceName, service] of Object.entries(config.services)) {
1625
+ if (!BUILT_IN_SERVICES.has(serviceName) && service.connectionString) {
1626
+ content += `
1627
+ # ${serviceName}
1628
+ `;
1629
+ content += `${connectionStringVar(serviceName)}=${envValue(service.connectionString)}
1562
1630
  `;
1563
1631
  }
1564
1632
  }
@@ -1712,7 +1780,8 @@ function generateAll(config, context) {
1712
1780
  } else {
1713
1781
  const generator = GENERATORS[fileType];
1714
1782
  if (generator) {
1715
- result[generator.file] = generator.generate(config, context);
1783
+ const file = fileType === "dockerignore" ? dockerignoreFileName(config.output.dir) : generator.file;
1784
+ result[file] = generator.generate(config, context);
1716
1785
  }
1717
1786
  }
1718
1787
  }
@@ -1721,7 +1790,7 @@ function generateAll(config, context) {
1721
1790
 
1722
1791
  // src/utils/fs.ts
1723
1792
  var import_fs = require("fs");
1724
- var import_path = require("path");
1793
+ var import_path2 = require("path");
1725
1794
  async function ensureDir(path) {
1726
1795
  try {
1727
1796
  await import_fs.promises.mkdir(path, { recursive: true });
@@ -1733,10 +1802,17 @@ async function ensureDir(path) {
1733
1802
  }
1734
1803
  }
1735
1804
  async function writeFile(filePath, content, mode) {
1736
- const dir = (0, import_path.dirname)(filePath);
1805
+ try {
1806
+ await writeFileAtomic(filePath, content, mode);
1807
+ } catch (error) {
1808
+ throw new FileWriteError(filePath, "FILE_WRITE_ERROR", error);
1809
+ }
1810
+ }
1811
+ async function writeFileAtomic(filePath, content, mode) {
1812
+ const dir = (0, import_path2.dirname)(filePath);
1737
1813
  await ensureDir(dir);
1738
1814
  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`);
1815
+ const tempPath = (0, import_path2.join)(dir, `.${(0, import_path2.basename)(filePath)}.${suffix}.tmp`);
1740
1816
  try {
1741
1817
  await import_fs.promises.writeFile(tempPath, content, { encoding: "utf8", mode });
1742
1818
  if (mode !== void 0) {
@@ -1759,7 +1835,7 @@ async function fileExists(filePath) {
1759
1835
  }
1760
1836
 
1761
1837
  // src/core/dockcraft.ts
1762
- var import_path2 = require("path");
1838
+ var import_path3 = require("path");
1763
1839
  function validationError(prefix, errors) {
1764
1840
  const errorMessages = errors.map((e) => ` - ${e.message}`).join("\n");
1765
1841
  return new ValidationError(`${prefix}:
@@ -1767,8 +1843,8 @@ ${errorMessages}`, errors);
1767
1843
  }
1768
1844
  function isSafeOutputPath(fileName) {
1769
1845
  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, "/"));
1846
+ if ((0, import_path3.isAbsolute)(fileName) || /^[a-zA-Z]:/.test(fileName) || fileName.startsWith("\\")) return false;
1847
+ const normalized = (0, import_path3.normalize)(fileName.replace(/\\/g, "/"));
1772
1848
  return !normalized.split(/[\\/]/).includes("..") && normalized !== ".";
1773
1849
  }
1774
1850
  async function dockcraft(config, options = {}) {
@@ -1813,7 +1889,7 @@ async function dockcraft(config, options = {}) {
1813
1889
  const outputDir = resolved.output.dir ?? "./";
1814
1890
  if (!options.dryRun) {
1815
1891
  for (const [fileName, content] of Object.entries(generated)) {
1816
- const filePath = (0, import_path2.join)(outputDir, fileName);
1892
+ const filePath = (0, import_path3.join)(outputDir, fileName);
1817
1893
  const exists = await fileExists(filePath);
1818
1894
  if (exists && !resolved.output.overwrite) {
1819
1895
  continue;