@solid-stack/builder 1.2.0 → 2.0.1

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.
Files changed (156) hide show
  1. package/README.md +66 -197
  2. package/dist/bin.js +1768 -2587
  3. package/dist/bin.js.map +1 -1
  4. package/dist/commands/mesh/commands/up/command.d.ts.map +1 -1
  5. package/dist/commands/mesh/commands/up/handler.d.ts.map +1 -1
  6. package/dist/commands/service/commands/down/handler.d.ts.map +1 -1
  7. package/dist/commands/service/commands/export/command.d.ts.map +1 -1
  8. package/dist/commands/service/commands/up/command.d.ts.map +1 -1
  9. package/dist/core/buildSchema.d.ts +1029 -110
  10. package/dist/core/buildSchema.d.ts.map +1 -1
  11. package/dist/core/checkers/checkDockerfile.d.ts.map +1 -1
  12. package/dist/core/checkers/checkDockerfileContract.d.ts +1 -1
  13. package/dist/core/checkers/checkDockerfileContract.d.ts.map +1 -1
  14. package/dist/core/checkers/checkEffectiveServiceStages.d.ts +2 -0
  15. package/dist/core/checkers/checkEffectiveServiceStages.d.ts.map +1 -0
  16. package/dist/core/checkers/checkYamlFiles.d.ts +1 -1
  17. package/dist/core/checkers/checkYamlFiles.d.ts.map +1 -1
  18. package/dist/core/checkers/getDeclaredYamlFiles.d.ts +3 -1
  19. package/dist/core/checkers/getDeclaredYamlFiles.d.ts.map +1 -1
  20. package/dist/core/compileEnvironment.d.ts +1 -1
  21. package/dist/core/compileEnvironment.d.ts.map +1 -1
  22. package/dist/core/composition/compileServiceComposition.d.ts +18 -0
  23. package/dist/core/composition/compileServiceComposition.d.ts.map +1 -0
  24. package/dist/core/composition/composeEnvironment.d.ts +4 -0
  25. package/dist/core/composition/composeEnvironment.d.ts.map +1 -0
  26. package/dist/core/composition/composeNetworks.d.ts +2 -0
  27. package/dist/core/composition/composeNetworks.d.ts.map +1 -0
  28. package/dist/core/composition/composePaths.d.ts +3 -0
  29. package/dist/core/composition/composePaths.d.ts.map +1 -0
  30. package/dist/core/composition/composeVolumes.d.ts +15 -0
  31. package/dist/core/composition/composeVolumes.d.ts.map +1 -0
  32. package/dist/core/composition/dependencyLifecycle.d.ts +4 -0
  33. package/dist/core/composition/dependencyLifecycle.d.ts.map +1 -0
  34. package/dist/core/composition/loadCompose.d.ts +8 -0
  35. package/dist/core/composition/loadCompose.d.ts.map +1 -0
  36. package/dist/core/composition/namespaceDependencyCompose.d.ts +15 -0
  37. package/dist/core/composition/namespaceDependencyCompose.d.ts.map +1 -0
  38. package/dist/core/composition/serviceEndpoints.d.ts +5 -0
  39. package/dist/core/composition/serviceEndpoints.d.ts.map +1 -0
  40. package/dist/core/composition/types.d.ts +64 -0
  41. package/dist/core/composition/types.d.ts.map +1 -0
  42. package/dist/core/composition/validateDependencyCompose.d.ts +8 -0
  43. package/dist/core/composition/validateDependencyCompose.d.ts.map +1 -0
  44. package/dist/core/composition/validateOverrideCompose.d.ts +11 -0
  45. package/dist/core/composition/validateOverrideCompose.d.ts.map +1 -0
  46. package/dist/core/config/constants.d.ts +13 -0
  47. package/dist/core/config/constants.d.ts.map +1 -0
  48. package/dist/core/config/endpointProperties.d.ts +16 -0
  49. package/dist/core/config/endpointProperties.d.ts.map +1 -0
  50. package/dist/core/config/hostPorts.d.ts +10 -0
  51. package/dist/core/config/hostPorts.d.ts.map +1 -0
  52. package/dist/core/config/lifecycleGraph.d.ts +7 -0
  53. package/dist/core/config/lifecycleGraph.d.ts.map +1 -0
  54. package/dist/core/config/pathSafety.d.ts +7 -0
  55. package/dist/core/config/pathSafety.d.ts.map +1 -0
  56. package/dist/core/config/references.d.ts +15 -0
  57. package/dist/core/config/references.d.ts.map +1 -0
  58. package/dist/core/config/resolveBuildStage.d.ts +4 -0
  59. package/dist/core/config/resolveBuildStage.d.ts.map +1 -0
  60. package/dist/core/config/resolveMeshStage.d.ts +4 -0
  61. package/dist/core/config/resolveMeshStage.d.ts.map +1 -0
  62. package/dist/core/config/stageMerge.d.ts +4 -0
  63. package/dist/core/config/stageMerge.d.ts.map +1 -0
  64. package/dist/core/config/types.d.ts +44 -0
  65. package/dist/core/config/types.d.ts.map +1 -0
  66. package/dist/core/mesh/MeshRunOptions.d.ts +0 -1
  67. package/dist/core/mesh/MeshRunOptions.d.ts.map +1 -1
  68. package/dist/core/mesh/checkers/checkMeshJson.d.ts +1 -1
  69. package/dist/core/mesh/checkers/checkMeshJson.d.ts.map +1 -1
  70. package/dist/core/mesh/checkers/checkMeshServices.d.ts +1 -1
  71. package/dist/core/mesh/checkers/checkMeshServices.d.ts.map +1 -1
  72. package/dist/core/mesh/checkers/checkMeshTester.d.ts +1 -1
  73. package/dist/core/mesh/checkers/checkMeshTester.d.ts.map +1 -1
  74. package/dist/core/mesh/compileMeshEnvironment.d.ts +1 -3
  75. package/dist/core/mesh/compileMeshEnvironment.d.ts.map +1 -1
  76. package/dist/core/mesh/getMeshJson.d.ts.map +1 -1
  77. package/dist/core/mesh/meshSchema.d.ts +267 -334
  78. package/dist/core/mesh/meshSchema.d.ts.map +1 -1
  79. package/dist/core/mesh/runners/runMeshDev.d.ts.map +1 -1
  80. package/dist/core/mesh/runners/runMeshProd.d.ts.map +1 -1
  81. package/dist/core/mesh/runners/runMeshTest.d.ts.map +1 -1
  82. package/dist/core/mesh/runners/runMeshTestE2e.d.ts.map +1 -1
  83. package/dist/core/mesh/runners/runMeshTestUnit.d.ts.map +1 -1
  84. package/dist/core/mesh/types.d.ts +34 -40
  85. package/dist/core/mesh/types.d.ts.map +1 -1
  86. package/dist/core/mesh/v2/compileMeshComposition.d.ts +6 -0
  87. package/dist/core/mesh/v2/compileMeshComposition.d.ts.map +1 -0
  88. package/dist/core/mesh/v2/compileMeshTester.d.ts +14 -0
  89. package/dist/core/mesh/v2/compileMeshTester.d.ts.map +1 -0
  90. package/dist/core/mesh/v2/lifecycle.d.ts +10 -0
  91. package/dist/core/mesh/v2/lifecycle.d.ts.map +1 -0
  92. package/dist/core/mesh/v2/loadMeshServices.d.ts +5 -0
  93. package/dist/core/mesh/v2/loadMeshServices.d.ts.map +1 -0
  94. package/dist/core/mesh/v2/meshReferences.d.ts +15 -0
  95. package/dist/core/mesh/v2/meshReferences.d.ts.map +1 -0
  96. package/dist/core/mesh/v2/publication.d.ts +3 -0
  97. package/dist/core/mesh/v2/publication.d.ts.map +1 -0
  98. package/dist/core/mesh/v2/substitution.d.ts +5 -0
  99. package/dist/core/mesh/v2/substitution.d.ts.map +1 -0
  100. package/dist/core/mesh/v2/types.d.ts +40 -0
  101. package/dist/core/mesh/v2/types.d.ts.map +1 -0
  102. package/dist/core/runners/runDev.d.ts.map +1 -1
  103. package/dist/core/runners/runProd.d.ts.map +1 -1
  104. package/dist/core/runners/runTestE2e.d.ts.map +1 -1
  105. package/dist/core/runners/runTestUnit.d.ts.map +1 -1
  106. package/dist/core/teardownCompose.d.ts +1 -0
  107. package/dist/core/teardownCompose.d.ts.map +1 -1
  108. package/dist/core/templates.d.ts +1 -0
  109. package/dist/core/templates.d.ts.map +1 -1
  110. package/dist/errors/ConfigError.d.ts +15 -0
  111. package/dist/errors/ConfigError.d.ts.map +1 -0
  112. package/dist/errors/PortConflictError.d.ts +8 -0
  113. package/dist/errors/PortConflictError.d.ts.map +1 -0
  114. package/dist/index.d.ts +2 -0
  115. package/dist/index.d.ts.map +1 -1
  116. package/dist/index.js +1770 -2589
  117. package/dist/index.js.map +1 -1
  118. package/dist/templates/docker/docker-compose.base.yml +4 -4
  119. package/dist/templates/docker/docker-compose.dev.yml +1 -5
  120. package/dist/templates/docker/docker-compose.e2e.yml +9 -8
  121. package/dist/templates/docker/docker-compose.prod.yml +1 -6
  122. package/dist/templates/docker/docker-compose.test.yml +3 -8
  123. package/dist/templates/policy/dockerfile/dockerfile.rego +64 -0
  124. package/dist/types/index.d.ts +60 -50
  125. package/dist/types/index.d.ts.map +1 -1
  126. package/dist/utils/checkPortCollision.d.ts.map +1 -1
  127. package/dist/utils/getBuildJson.d.ts.map +1 -1
  128. package/dist/utils/paths.d.ts +2 -0
  129. package/dist/utils/paths.d.ts.map +1 -1
  130. package/dist/utils/runState.d.ts +1 -0
  131. package/dist/utils/runState.d.ts.map +1 -1
  132. package/package.json +7 -2
  133. package/schemas/build-schema.json +620 -101
  134. package/schemas/mesh-schema.json +225 -133
  135. package/templates/docker/docker-compose.base.yml +4 -4
  136. package/templates/docker/docker-compose.dev.yml +1 -5
  137. package/templates/docker/docker-compose.e2e.yml +9 -8
  138. package/templates/docker/docker-compose.prod.yml +1 -6
  139. package/templates/docker/docker-compose.test.yml +3 -8
  140. package/templates/policy/dockerfile/dockerfile.rego +64 -0
  141. package/dist/core/checkers/checkComposeContract.d.ts +0 -3
  142. package/dist/core/checkers/checkComposeContract.d.ts.map +0 -1
  143. package/dist/templates/docker/docker-compose.standalone.yml +0 -5
  144. package/dist/utils/dependencyPorts.d.ts +0 -10
  145. package/dist/utils/dependencyPorts.d.ts.map +0 -1
  146. package/dist/utils/extractBuildDeps.d.ts +0 -3
  147. package/dist/utils/extractBuildDeps.d.ts.map +0 -1
  148. package/dist/utils/extractOverrides.d.ts +0 -3
  149. package/dist/utils/extractOverrides.d.ts.map +0 -1
  150. package/dist/utils/ymlMods/addDependenciesToAppService.d.ts +0 -3
  151. package/dist/utils/ymlMods/addDependenciesToAppService.d.ts.map +0 -1
  152. package/dist/utils/ymlMods/makeE2eDependOnApp.d.ts +0 -2
  153. package/dist/utils/ymlMods/makeE2eDependOnApp.d.ts.map +0 -1
  154. package/dist/utils/ymlMods/renameServicesWithDependencies.d.ts +0 -3
  155. package/dist/utils/ymlMods/renameServicesWithDependencies.d.ts.map +0 -1
  156. package/templates/docker/docker-compose.standalone.yml +0 -5
package/dist/index.js CHANGED
@@ -1,25 +1,19 @@
1
1
  import { Command, Argument } from 'commander';
2
2
  import pc22 from 'picocolors';
3
- import fs, { existsSync, readFileSync, mkdirSync, writeFileSync, unlinkSync, statSync } from 'fs';
4
- import path13 from 'path';
5
- import { spawnSync, spawn } from 'child_process';
6
- import { parse, stringify, parseAllDocuments } from 'yaml';
3
+ import fs, { existsSync, readFileSync, mkdirSync, writeFileSync, renameSync, statSync, realpathSync, lstatSync, readlinkSync, unlinkSync } from 'fs';
4
+ import path from 'path';
7
5
  import { z } from 'zod';
8
- import 'crypto';
6
+ import { spawnSync, spawn } from 'child_process';
7
+ import { fileURLToPath } from 'url';
8
+ import { stringify, parse, parseAllDocuments } from 'yaml';
9
+ import crypto from 'crypto';
9
10
  import os from 'os';
10
11
  import net from 'net';
11
- import { fileURLToPath } from 'url';
12
12
  import { createInterface } from 'readline/promises';
13
13
  import { createRequire } from 'module';
14
14
 
15
15
  // src/types/index.ts
16
- var SERVICE_STAGES = [
17
- "dev",
18
- "prod",
19
- "test",
20
- "test-unit",
21
- "test-e2e"
22
- ];
16
+ var SERVICE_STAGES = ["dev", "prod", "test", "test-unit", "test-e2e"];
23
17
 
24
18
  // src/errors/ScriptError.ts
25
19
  var ScriptError = class extends Error {
@@ -39,6 +33,43 @@ var NotFoundError = class extends ScriptError {
39
33
  }
40
34
  };
41
35
 
36
+ // src/errors/ConfigError.ts
37
+ var ConfigError = class extends ScriptError {
38
+ context;
39
+ constructor(context, options) {
40
+ const details = [context.sourceFile ? `source=${context.sourceFile}` : void 0, context.configPath ? `path=${context.configPath}` : void 0, context.stage ? `stage=${context.stage}` : void 0, context.composition ? `composition=${context.composition}` : void 0, context.referencedObject ? `reference=${context.referencedObject}` : void 0, context.value !== void 0 ? `value=${JSON.stringify(context.value)}` : void 0].filter(Boolean);
41
+ super(`${context.reason}${details.length ? ` (${details.join(", ")})` : ""}`, options);
42
+ this.name = "ConfigError";
43
+ this.context = context;
44
+ }
45
+ };
46
+
47
+ // src/core/config/constants.ts
48
+ var BUILDER_IDENTIFIER_PATTERN = /^[a-z][a-z0-9-]*$/;
49
+ var ENDPOINT_SCHEME_PATTERN = /^[A-Za-z][A-Za-z0-9+.-]*$/;
50
+ var DEPENDENCY_REFERENCE_PATTERN = /^dependencies\.([a-z][a-z0-9-]*)$/;
51
+ var ENDPOINT_PROPERTIES = ["network_host", "network_port", "network_address", "network_url", "public_host", "public_port", "public_address", "public_url"];
52
+ var PUBLIC_ENDPOINT_PROPERTIES = /* @__PURE__ */ new Set(["public_host", "public_port", "public_address", "public_url"]);
53
+ var RESERVED_MESH_SERVICE_NAMES = /* @__PURE__ */ new Set(["app", "dependencies", "tester", "services", "dev", "prod", "test", "e2e"]);
54
+ var PUBLIC_HOST = "127.0.0.1";
55
+ var AUTO_PORT_CACHE_VERSION = 1;
56
+ var AUTO_PORT_CACHE_RELATIVE_PATH = ".builder/ports-v2.json";
57
+ var AUTO_PORT_SCAN_START = 2e4;
58
+
59
+ // src/core/buildSchema.ts
60
+ var identifierSchema = z.string().regex(BUILDER_IDENTIFIER_PATTERN, "must match ^[a-z][a-z0-9-]*$");
61
+ var envSchema = z.record(z.string(), z.string());
62
+ var portSchema = z.number().int().min(1).max(65535);
63
+ var publicPortSchema = z.union([portSchema, z.literal("AUTO")]);
64
+ var appEndpointSchema = z.object({ port: portSchema, publicPort: publicPortSchema.optional(), primary: z.boolean().optional(), scheme: z.string().regex(ENDPOINT_SCHEME_PATTERN).optional() }).strict();
65
+ var dependencyEndpointSchema = appEndpointSchema.extend({ service: z.string().min(1) }).strict();
66
+ var dependencySchema = z.object({ compose: z.string().min(1), env: envSchema.optional(), endpoints: z.record(identifierSchema, dependencyEndpointSchema).optional(), dependsOn: z.array(z.string()).optional() }).strict();
67
+ var appStageEndpointSchema = appEndpointSchema.partial().strict();
68
+ var dependencyStageEndpointSchema = dependencyEndpointSchema.partial().strict();
69
+ var dependencyStageSchema = z.object({ compose: z.string().min(1).optional(), env: envSchema.optional(), endpoints: z.record(identifierSchema, dependencyStageEndpointSchema).optional(), dependsOn: z.array(z.string()).optional() }).strict();
70
+ var buildStageSchema = z.object({ "override-compose": z.string().min(1).optional(), app: z.object({ env: envSchema.optional(), endpoints: z.record(identifierSchema, appStageEndpointSchema).optional() }).strict().optional(), dependencies: z.record(identifierSchema, dependencyStageSchema).optional() }).strict();
71
+ var buildJsonSchema = z.object({ $schema: z.string().optional(), name: z.string().optional(), dockerfile: z.string().min(1).optional(), app: z.object({ env: envSchema.optional(), endpoints: z.record(identifierSchema, appEndpointSchema).optional() }).strict(), dependencies: z.record(identifierSchema, dependencySchema).optional(), tester: z.object({ env: envSchema.optional() }).strict().optional(), dev: buildStageSchema.optional(), prod: buildStageSchema.optional(), test: buildStageSchema.optional(), e2e: buildStageSchema.optional() }).strict();
72
+
42
73
  // src/utils/errorMessage.ts
43
74
  function errorMessage(err) {
44
75
  if (err instanceof Error) {
@@ -50,27 +81,11 @@ function errorMessage(err) {
50
81
  return String(err);
51
82
  }
52
83
  function resolveProjectDir(projectDir) {
53
- return path13.resolve(projectDir ?? process.cwd());
54
- }
55
- function toComposePath(baseDir, targetPath) {
56
- const absBase = path13.resolve(baseDir);
57
- const absTarget = path13.resolve(absBase, targetPath);
58
- let rel = path13.relative(absBase, absTarget);
59
- if (!rel || rel === ".") {
60
- return ".";
61
- }
62
- rel = rel.replace(/\\/g, "/");
63
- if (path13.isAbsolute(rel) || /^[a-zA-Z]:\//.test(rel)) {
64
- return rel;
65
- }
66
- if (rel.startsWith("./") || rel.startsWith("../") || rel.startsWith("/")) {
67
- return rel;
68
- }
69
- return `./${rel}`;
84
+ return path.resolve(projectDir ?? process.cwd());
70
85
  }
71
86
  function isBindMount(source) {
72
87
  if (!source) return false;
73
- if (source.startsWith(".") || source.startsWith("/") || source.startsWith("~")) {
88
+ if (source.startsWith(".") || source.startsWith("/") || source.startsWith("~") || source.startsWith("\\")) {
74
89
  return true;
75
90
  }
76
91
  if (/^[a-zA-Z]:[\\/]/.test(source)) {
@@ -79,68 +94,63 @@ function isBindMount(source) {
79
94
  return false;
80
95
  }
81
96
  function isPathInside(parentDir, childPath) {
82
- const absParent = path13.resolve(parentDir);
83
- const absChild = path13.resolve(absParent, childPath);
84
- const rel = path13.relative(absParent, absChild);
85
- return rel !== ".." && !rel.startsWith(".." + path13.sep) && !rel.startsWith("../") && !path13.isAbsolute(rel);
97
+ const absParent = canonicalPath(parentDir);
98
+ const absChild = canonicalPath(path.resolve(parentDir, childPath));
99
+ const rel = path.relative(absParent, absChild);
100
+ return rel !== ".." && !rel.startsWith(".." + path.sep) && !rel.startsWith("../") && !path.isAbsolute(rel);
86
101
  }
87
-
88
- // src/utils/ymlMods/normalizeDependsOn.ts
89
- function normalizeDependsOn(service) {
90
- if (!service || typeof service !== "object" || !service.depends_on) {
91
- return;
92
- }
93
- if (Array.isArray(service.depends_on)) {
94
- const obj = {};
95
- for (const dep of service.depends_on) {
96
- if (typeof dep === "string") {
97
- obj[dep] = { condition: "service_started" };
98
- }
102
+ function canonicalPath(value) {
103
+ const absolute = path.resolve(value);
104
+ try {
105
+ return realpathSync(absolute);
106
+ } catch (error) {
107
+ if (error.code !== "ENOENT") throw error;
108
+ try {
109
+ if (lstatSync(absolute).isSymbolicLink()) return canonicalPath(path.resolve(path.dirname(absolute), readlinkSync(absolute)));
110
+ } catch (linkError) {
111
+ if (linkError.code !== "ENOENT") throw linkError;
99
112
  }
100
- service.depends_on = obj;
113
+ const parent = path.dirname(absolute);
114
+ if (parent === absolute) throw error;
115
+ return path.join(canonicalPath(parent), path.basename(absolute));
101
116
  }
102
117
  }
103
118
 
104
119
  // src/utils/getBuildJson.ts
105
120
  var getBuildJson = (projectDir = process.cwd()) => {
106
- const absProjectDir = resolveProjectDir(projectDir);
107
- const buildJsonPath = path13.join(absProjectDir, "build.json");
108
- if (!existsSync(buildJsonPath)) {
109
- throw new NotFoundError(
110
- `Build JSON file not found at ${buildJsonPath}. Please make sure build.json exists in the project root.`
111
- );
112
- }
121
+ const absProjectDir = resolveProjectDir(projectDir), buildJsonPath = path.join(absProjectDir, "build.json");
122
+ if (!existsSync(buildJsonPath)) throw new NotFoundError(`Build JSON file not found at ${buildJsonPath}. Please make sure build.json exists in the project root.`);
113
123
  let rawData;
114
124
  try {
115
125
  rawData = readFileSync(buildJsonPath, "utf-8");
116
126
  } catch (error) {
117
- throw new ScriptError(
118
- `Failed to read build.json at ${buildJsonPath}: ${errorMessage(error)}`
119
- );
127
+ throw new ScriptError(`Failed to read build.json at ${buildJsonPath}: ${errorMessage(error)}`);
120
128
  }
121
- let buildJson;
129
+ let parsed;
122
130
  try {
123
- buildJson = JSON.parse(rawData);
131
+ parsed = JSON.parse(rawData);
124
132
  } catch (error) {
125
- throw new ScriptError(
126
- `Failed to parse build.json at ${buildJsonPath}: ${errorMessage(error)}`
127
- );
133
+ throw new ScriptError(`Failed to parse build.json at ${buildJsonPath}: ${errorMessage(error)}`);
128
134
  }
129
- if (!buildJson || typeof buildJson !== "object" || Array.isArray(buildJson)) {
130
- throw new ScriptError(
131
- `Invalid build.json at ${buildJsonPath}: root must be a JSON object.`
132
- );
133
- }
134
- const typedBuildJson = buildJson;
135
- if (typedBuildJson.services && typeof typedBuildJson.services === "object") {
136
- for (const serviceConfig of Object.values(typedBuildJson.services)) {
137
- if (serviceConfig && typeof serviceConfig === "object") {
138
- normalizeDependsOn(serviceConfig);
139
- }
140
- }
135
+ const result = buildJsonSchema.safeParse(parsed);
136
+ if (!result.success) {
137
+ const reason = result.error.issues.map((issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`).join("; ");
138
+ throw new ConfigError({ sourceFile: buildJsonPath, configPath: "<root>", composition: "service", reason: `Invalid build.json: ${reason}` });
141
139
  }
142
- return typedBuildJson;
140
+ return result.data;
143
141
  };
142
+ function resolveInsideProject(projectDir, relativePath, context) {
143
+ if (!relativePath.trim()) throw new ConfigError({ ...context, value: relativePath, reason: "Path must not be empty" });
144
+ const resolved = path.resolve(projectDir, relativePath);
145
+ if (!isPathInside(projectDir, relativePath)) throw new ConfigError({ ...context, value: relativePath, reason: "Path escapes the project directory" });
146
+ return resolved;
147
+ }
148
+ function resolveApplicationDockerfile(projectDir, relativePath = "Dockerfile", stage) {
149
+ const context = { sourceFile: path.join(projectDir, "build.json"), configPath: "dockerfile", ...stage ? { stage } : {} };
150
+ const resolved = resolveInsideProject(projectDir, relativePath, context);
151
+ if (!existsSync(resolved) || !statSync(resolved).isFile()) throw new ConfigError({ ...context, value: relativePath, reason: `Application Dockerfile not found or not a regular file: ${resolved}` });
152
+ return resolved;
153
+ }
144
154
 
145
155
  // src/core/checkers/constants.ts
146
156
  var HADOLINT_IMAGE = process.env.HADOLINT_IMAGE || "hadolint/hadolint:v2.12.0";
@@ -185,23 +195,7 @@ ${ctx.detail}`);
185
195
  // src/core/checkers/checkDockerfile.ts
186
196
  function checkDockerfile(buildJson, projectDir) {
187
197
  const dockerfileRel = buildJson.dockerfile || "Dockerfile";
188
- const dockerfilePath = path13.resolve(projectDir, dockerfileRel);
189
- if (!isPathInside(projectDir, dockerfilePath)) {
190
- throw new ScriptError(
191
- `Security error: Dockerfile path "${dockerfileRel}" escapes the project directory.`
192
- );
193
- }
194
- if (!existsSync(dockerfilePath)) {
195
- if (buildJson.dockerfile) {
196
- throw new ScriptError(
197
- `Dockerfile declared in build.json not found at: ${dockerfilePath}`
198
- );
199
- }
200
- console.log(
201
- pc22.yellow(`\u26A0\uFE0F No ${dockerfileRel} found in project directory. Skipping Dockerfile checks.`)
202
- );
203
- return;
204
- }
198
+ const dockerfilePath = resolveApplicationDockerfile(projectDir, dockerfileRel);
205
199
  const content = readFileSync(dockerfilePath, "utf-8");
206
200
  console.log(pc22.cyan(`
207
201
  \u{1F50D} Linting Dockerfile (${dockerfileRel})...`));
@@ -212,171 +206,891 @@ function checkDockerfile(buildJson, projectDir) {
212
206
  { stepName: "Dockerfile Linting", targetFile: dockerfileRel, input: content }
213
207
  );
214
208
  }
215
- function checkDockerfileContract(buildJson, projectDir) {
216
- const absProjectDir = resolveProjectDir(projectDir);
217
- const dockerfileRel = buildJson.dockerfile || "Dockerfile";
218
- const dockerfilePath = path13.resolve(absProjectDir, dockerfileRel);
219
- const policyRel = buildJson.policy?.dockerfile || buildJson.policies?.dockerfile || "policy/dockerfile";
220
- const policyDir = path13.resolve(absProjectDir, policyRel);
221
- if (!isPathInside(absProjectDir, dockerfilePath)) {
222
- throw new ScriptError(
223
- `Security error: Dockerfile path "${dockerfileRel}" escapes the project directory.`
224
- );
209
+ var cachedTemplatesDir = null;
210
+ var lastEnvTemplatesDir = void 0;
211
+ function getTemplatesDir() {
212
+ const envVal = process.env.BUILDER_TEMPLATES_DIR;
213
+ if (envVal !== lastEnvTemplatesDir) {
214
+ cachedTemplatesDir = null;
215
+ lastEnvTemplatesDir = envVal;
225
216
  }
226
- if (!existsSync(dockerfilePath) || !existsSync(policyDir)) {
227
- return;
217
+ if (envVal) {
218
+ const envDir = path.resolve(envVal);
219
+ if (!fs.existsSync(envDir) || !fs.existsSync(path.join(envDir, "docker"))) {
220
+ throw new ScriptError(
221
+ `BUILDER_TEMPLATES_DIR is set to "${envVal}" but directory does not exist or lacks a "docker/" subdirectory (resolved: "${envDir}").`
222
+ );
223
+ }
224
+ return envDir;
228
225
  }
229
- console.log(pc22.cyan(`
230
- \u{1F50D} Validating Dockerfile Contract (${policyRel})...`));
231
- runStep(
232
- "docker",
233
- [
234
- "run",
235
- "--rm",
236
- "--network",
237
- "none",
238
- "--mount",
239
- `type=bind,src=${absProjectDir},dst=/project,readonly`,
240
- "-w",
241
- "/project",
242
- CONFTEST_IMAGE,
243
- "test",
244
- dockerfileRel,
245
- "-p",
246
- `${policyRel}/`
247
- ],
248
- absProjectDir,
249
- { stepName: "Dockerfile Contract", targetFile: dockerfileRel }
226
+ if (cachedTemplatesDir && fs.existsSync(cachedTemplatesDir)) {
227
+ return cachedTemplatesDir;
228
+ }
229
+ const currentDir = typeof __dirname !== "undefined" ? __dirname : path.dirname(fileURLToPath(import.meta.url));
230
+ const candidates = [
231
+ // When executing compiled output in dist/ (e.g. dist/templates)
232
+ path.resolve(currentDir, "templates"),
233
+ path.resolve(currentDir, "../templates"),
234
+ // When executing from src/ (e.g. src/core/templates.ts -> ../../templates)
235
+ path.resolve(currentDir, "../../templates"),
236
+ // Fallback relative to cwd
237
+ path.resolve(process.cwd(), "templates")
238
+ ];
239
+ for (const cand of candidates) {
240
+ if (fs.existsSync(cand) && fs.existsSync(path.join(cand, "docker"))) {
241
+ cachedTemplatesDir = cand;
242
+ return cand;
243
+ }
244
+ }
245
+ throw new ScriptError(
246
+ `Templates directory not found. Searched candidates:
247
+ ${candidates.join("\n")}`
250
248
  );
251
249
  }
252
- function getDeclaredYamlFiles(buildJson, projectDir) {
250
+ function getDockerComposeTemplate(filename) {
251
+ const templatesDir = getTemplatesDir();
252
+ const filePath = path.join(templatesDir, "docker", filename);
253
+ if (!fs.existsSync(filePath)) {
254
+ throw new ScriptError(`Docker compose template not found: ${filePath}`);
255
+ }
256
+ return filePath;
257
+ }
258
+ function getDockerfilePolicyDir() {
259
+ const policyDir = path.join(getTemplatesDir(), "policy", "dockerfile");
260
+ if (!fs.existsSync(path.join(policyDir, "dockerfile.rego"))) throw new ScriptError(`Builder Dockerfile policy not found: ${policyDir}`);
261
+ return policyDir;
262
+ }
263
+
264
+ // src/core/checkers/checkDockerfileContract.ts
265
+ function checkDockerfileContract(build, projectDir) {
266
+ const root = resolveProjectDir(projectDir);
267
+ const relative = build.dockerfile ?? "Dockerfile";
268
+ resolveApplicationDockerfile(root, relative);
269
+ const policyDir = getDockerfilePolicyDir();
270
+ console.log(pc22.cyan(`
271
+ \u{1F50D} Validating Builder Dockerfile contract (${relative})...`));
272
+ runStep("docker", ["run", "--rm", "--network", "none", "--mount", `type=bind,src=${root},dst=/project,readonly`, "--mount", `type=bind,src=${policyDir},dst=/builder-policy,readonly`, "-w", "/project", CONFTEST_IMAGE, "test", relative, "-p", "/builder-policy"], root, { stepName: "Dockerfile Contract", targetFile: relative });
273
+ }
274
+ function loadComposeDocument(absolutePath, context) {
275
+ const fail = (reason, value) => {
276
+ throw new ConfigError({ ...context, sourceFile: absolutePath, ...{} , reason });
277
+ };
278
+ if (!existsSync(absolutePath) || !statSync(absolutePath).isFile()) fail("Compose file does not exist or is not a regular file");
279
+ let text = "";
280
+ try {
281
+ text = readFileSync(absolutePath, "utf8");
282
+ } catch (e) {
283
+ fail(`Failed to read Compose file: ${String(e)}`);
284
+ }
285
+ let docs = [];
286
+ try {
287
+ docs = parseAllDocuments(text, { prettyErrors: true });
288
+ } catch (e) {
289
+ fail(`Invalid Compose YAML: ${String(e)}`);
290
+ }
291
+ if (docs.length !== 1) fail("Compose file must contain exactly one YAML document");
292
+ const errors = docs[0].errors;
293
+ if (errors.length) fail(`Invalid Compose YAML: ${errors.map((e) => e.message).join("; ")}`);
294
+ let parsed;
295
+ try {
296
+ parsed = parse(text);
297
+ } catch (e) {
298
+ fail(`Invalid Compose YAML: ${String(e)}`);
299
+ }
300
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) fail("Compose root must be an object");
301
+ return parsed;
302
+ }
303
+ function getDeclaredYamlFiles(build, projectDir) {
253
304
  const files = [];
254
305
  const seen = /* @__PURE__ */ new Set();
255
- const addFile = (relPath, source) => {
256
- const normalized = path13.normalize(relPath);
257
- if (seen.has(normalized)) return;
258
- seen.add(normalized);
259
- files.push({
260
- relativePath: relPath,
261
- absolutePath: path13.resolve(projectDir, relPath),
262
- source
263
- });
306
+ const add = (relativePath, source, kind, stage) => {
307
+ const absolutePath = path.resolve(projectDir, relativePath);
308
+ if (seen.has(absolutePath)) return;
309
+ seen.add(absolutePath);
310
+ files.push({ relativePath, absolutePath, source, kind, ...stage ? { stage } : {} });
264
311
  };
265
- if (buildJson.dependencies && typeof buildJson.dependencies === "object") {
266
- for (const [depName, dep] of Object.entries(buildJson.dependencies)) {
267
- if (dep && typeof dep === "object" && typeof dep.path === "string") {
268
- addFile(dep.path, `dependency "${depName}"`);
269
- }
312
+ for (const [name, dep] of Object.entries(build.dependencies ?? {})) add(dep.compose, `dependencies.${name}.compose`, "dependency-compose");
313
+ for (const stage of ["dev", "prod", "test", "e2e"]) {
314
+ const overlay = build[stage];
315
+ if (overlay?.["override-compose"]) add(overlay["override-compose"], `${stage}.override-compose`, "override-compose", stage);
316
+ for (const [name, dep] of Object.entries(overlay?.dependencies ?? {})) if (dep.compose) add(dep.compose, `${stage}.dependencies.${name}.compose`, "dependency-compose", stage);
317
+ }
318
+ return files;
319
+ }
320
+
321
+ // src/core/checkers/checkYamlFiles.ts
322
+ function checkYamlFiles(build, projectDir) {
323
+ const root = resolveProjectDir(projectDir);
324
+ const files = getDeclaredYamlFiles(build, root);
325
+ if (files.length) console.log(pc22.cyan(`
326
+ \u{1F50D} Validating ${files.length} declared V2 Compose file(s)...`));
327
+ for (const file of files) {
328
+ const absolutePath = resolveInsideProject(root, file.relativePath, { sourceFile: `${root}/build.json`, configPath: file.source, ...file.stage ? { stage: file.stage } : {} });
329
+ loadComposeDocument(absolutePath, { sourceFile: `${root}/build.json`, configPath: file.source, stage: file.stage ?? "base", composition: "service" });
330
+ }
331
+ }
332
+
333
+ // src/core/composition/composeNetworks.ts
334
+ function normalizeNetworks(value) {
335
+ if (Array.isArray(value)) return Object.fromEntries(value.filter((name) => typeof name === "string").map((name) => [name, null]));
336
+ return value && typeof value === "object" ? { ...value } : {};
337
+ }
338
+
339
+ // src/core/config/endpointProperties.ts
340
+ function resolveEndpointProperty(endpoint, property, context) {
341
+ const published = () => {
342
+ if (!endpoint.effectivelyPublished || endpoint.publicHost === void 0 || endpoint.publicPort === void 0) throw new ConfigError({ ...context, configPath: context.configPath, referencedObject: endpoint.logicalPath, reason: `Endpoint property ${property} requires effective publication` });
343
+ };
344
+ const scheme = () => {
345
+ if (!endpoint.scheme) throw new ConfigError({ ...context, referencedObject: endpoint.logicalPath, reason: `Endpoint property ${property} requires an endpoint scheme` });
346
+ return endpoint.scheme;
347
+ };
348
+ switch (property) {
349
+ case "network_host":
350
+ return endpoint.networkHost;
351
+ case "network_port":
352
+ return String(endpoint.networkPort);
353
+ case "network_address":
354
+ return `${endpoint.networkHost}:${endpoint.networkPort}`;
355
+ case "network_url":
356
+ return `${scheme()}://${endpoint.networkHost}:${endpoint.networkPort}`;
357
+ case "public_host":
358
+ published();
359
+ return endpoint.publicHost;
360
+ case "public_port":
361
+ published();
362
+ return String(endpoint.publicPort);
363
+ case "public_address":
364
+ published();
365
+ return `${endpoint.publicHost}:${endpoint.publicPort}`;
366
+ case "public_url":
367
+ published();
368
+ return `${scheme()}://${endpoint.publicHost}:${endpoint.publicPort}`;
369
+ }
370
+ }
371
+ function assertPrimaryEndpointInvariant(endpoints, context) {
372
+ const primaries = Object.entries(endpoints).filter(([, e]) => e.primary === true);
373
+ if (Object.keys(endpoints).length && primaries.length !== 1) throw new ConfigError({ ...context, value: primaries.map(([n]) => n), reason: `Expected exactly one primary endpoint; found ${primaries.length}` });
374
+ }
375
+ function getPrimaryEndpoint(endpoints) {
376
+ return Object.entries(endpoints).find(([, endpoint]) => endpoint.primary === true);
377
+ }
378
+
379
+ // src/core/config/lifecycleGraph.ts
380
+ function assertAcyclicGraph(graph, context) {
381
+ const visiting = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set(), stack = [];
382
+ const visit = (node) => {
383
+ if (visiting.has(node)) {
384
+ const start = stack.indexOf(node);
385
+ const cycle = [...stack.slice(start), node];
386
+ throw new ConfigError({ ...context, configPath: "dependsOn", referencedObject: cycle.join(" -> "), reason: `Lifecycle cycle detected: ${cycle.join(" -> ")}` });
387
+ }
388
+ if (visited.has(node)) return;
389
+ visiting.add(node);
390
+ stack.push(node);
391
+ for (const next of graph.get(node) ?? []) visit(next);
392
+ stack.pop();
393
+ visiting.delete(node);
394
+ visited.add(node);
395
+ };
396
+ for (const node of graph.keys()) visit(node);
397
+ }
398
+
399
+ // src/core/config/stageMerge.ts
400
+ function unionStable(base = [], overlay = []) {
401
+ return [.../* @__PURE__ */ new Set([...base, ...overlay])];
402
+ }
403
+ function mergeStringMap(base, overlay) {
404
+ return { ...base ?? {}, ...overlay ?? {} };
405
+ }
406
+
407
+ // src/core/config/resolveBuildStage.ts
408
+ function resolveBuildStage(build, stage, sourceFile) {
409
+ const overlay = build[stage] ?? {};
410
+ const appEndpoints = structuredClone(build.app.endpoints ?? {});
411
+ for (const [name, endpoint] of Object.entries(overlay.app?.endpoints ?? {})) appEndpoints[name] = { ...appEndpoints[name] ?? {}, ...endpoint };
412
+ const dependencies = {};
413
+ for (const [name, dep] of Object.entries(build.dependencies ?? {})) dependencies[name] = { ...dep, env: { ...dep.env ?? {} }, endpoints: structuredClone(dep.endpoints ?? {}), dependsOn: [...dep.dependsOn ?? []] };
414
+ for (const [name, patch] of Object.entries(overlay.dependencies ?? {})) {
415
+ const prior = dependencies[name] ?? { compose: void 0, env: {}, endpoints: {}, dependsOn: [] };
416
+ prior.compose = patch.compose ?? prior.compose;
417
+ prior.env = mergeStringMap(prior.env, patch.env);
418
+ for (const [ep, epPatch] of Object.entries(patch.endpoints ?? {})) prior.endpoints[ep] = { ...prior.endpoints[ep] ?? {}, ...epPatch };
419
+ prior.dependsOn = unionStable(prior.dependsOn, patch.dependsOn);
420
+ dependencies[name] = prior;
421
+ }
422
+ const effective = { ...build, app: { env: mergeStringMap(build.app.env, overlay.app?.env), endpoints: appEndpoints }, dependencies, tester: build.tester ? { env: { ...build.tester.env ?? {} } } : void 0, overrideCompose: overlay["override-compose"] };
423
+ delete effective.dev;
424
+ delete effective.prod;
425
+ delete effective.test;
426
+ delete effective.e2e;
427
+ const context = (configPath, value, reason, referencedObject) => new ConfigError({ sourceFile, configPath, stage, composition: "service", value, ...referencedObject ? { referencedObject } : {}, reason });
428
+ for (const [name, ep] of Object.entries(appEndpoints)) if (!Number.isInteger(ep.port) || ep.port < 1 || ep.port > 65535) throw context(`app.endpoints.${name}.port`, ep.port, "Effective endpoint requires a port in 1..65535");
429
+ assertPrimaryEndpointInvariant(appEndpoints, { sourceFile, configPath: "app.endpoints", stage });
430
+ const graph = /* @__PURE__ */ new Map();
431
+ for (const [name, dep] of Object.entries(dependencies)) {
432
+ if (typeof dep.compose !== "string" || !dep.compose.trim()) throw context(`dependencies.${name}.compose`, dep.compose, "Effective dependency requires compose");
433
+ const endpoints = Object.entries(dep.endpoints);
434
+ for (const [epName, ep] of endpoints) if (!ep.service || !Number.isInteger(ep.port) || ep.port < 1 || ep.port > 65535) throw context(`dependencies.${name}.endpoints.${epName}`, ep, "Effective dependency endpoint requires service and port");
435
+ assertPrimaryEndpointInvariant(dep.endpoints, { sourceFile, configPath: `dependencies.${name}.endpoints`, stage });
436
+ const node = `dependencies.${name}`;
437
+ graph.set(node, /* @__PURE__ */ new Set());
438
+ for (const ref of dep.dependsOn) {
439
+ const match = DEPENDENCY_REFERENCE_PATTERN.exec(ref);
440
+ if (!match) throw context(`dependencies.${name}.dependsOn`, ref, "Expected dependencies.<name> lifecycle reference", ref);
441
+ const targetName = match[1];
442
+ if (targetName === name) throw context(`dependencies.${name}.dependsOn`, ref, "Dependency cannot depend on itself", ref);
443
+ const target = dependencies[targetName];
444
+ if (!target) throw context(`dependencies.${name}.dependsOn`, ref, "Unknown dependency", ref);
445
+ if (!Object.keys(target.endpoints).length) throw context(`dependencies.${name}.dependsOn`, ref, "Lifecycle target is inert and has no endpoints", ref);
446
+ graph.get(node).add(`dependencies.${targetName}`);
447
+ }
448
+ }
449
+ assertAcyclicGraph(graph, { sourceFile, stage, composition: "service" });
450
+ return effective;
451
+ }
452
+
453
+ // src/core/config/references.ts
454
+ var BUILD_APP = /^app\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
455
+ var BUILD_DEP = /^dependencies\.([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
456
+ var MESH_APP = /^([a-z][a-z0-9-]*)\.app\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
457
+ var MESH_DEP = /^([a-z][a-z0-9-]*)\.dependencies\.([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
458
+ function parse2(raw, scope, sourcePath) {
459
+ let m;
460
+ if (scope === "build" && (m = BUILD_APP.exec(raw))) return valid({ raw, scope, target: "app", endpoint: m[1], property: m[2] }, sourcePath);
461
+ if (scope === "build" && (m = BUILD_DEP.exec(raw))) return valid({ raw, scope, target: "dependency", dependency: m[1], endpoint: m[2], property: m[3] }, sourcePath);
462
+ if (scope === "mesh" && (m = MESH_APP.exec(raw))) return valid({ raw, scope, meshService: m[1], target: "app", endpoint: m[2], property: m[3] }, sourcePath);
463
+ if (scope === "mesh" && (m = MESH_DEP.exec(raw))) return valid({ raw, scope, meshService: m[1], target: "dependency", dependency: m[2], endpoint: m[3], property: m[4] }, sourcePath);
464
+ throw new ConfigError({ configPath: sourcePath, value: raw, reason: `Invalid ${scope} endpoint reference` });
465
+ }
466
+ function valid(ref, sourcePath) {
467
+ if (!ENDPOINT_PROPERTIES.includes(ref.property)) throw new ConfigError({ configPath: sourcePath, value: ref.property, reason: "Unknown endpoint property" });
468
+ return ref;
469
+ }
470
+ function collectBuilderReferences(value, scope, sourcePath) {
471
+ const protectedValue = value.replace(/\$\$/g, "\0DOLLAR\0"), refs2 = [];
472
+ for (const match of protectedValue.matchAll(/\$\{([^}]*)\}/g)) refs2.push(parse2(match[1], scope, sourcePath));
473
+ return refs2;
474
+ }
475
+ function interpolateBuilderReferences(value, scope, resolve) {
476
+ const sentinel = "\0DOLLAR\0";
477
+ return value.replace(/\$\$/g, sentinel).replace(/\$\{([^}]*)\}/g, (whole, body) => resolve(parse2(body, scope, "environment"))).replaceAll(sentinel, "$");
478
+ }
479
+ function assertTesterReferencesArePublic(env, scope, sourcePrefix) {
480
+ for (const [key, value] of Object.entries(env)) for (const ref of collectBuilderReferences(value, scope, `${sourcePrefix}.${key}`)) if (!PUBLIC_ENDPOINT_PROPERTIES.has(ref.property)) throw new ConfigError({ configPath: `${sourcePrefix}.${key}`, value: ref.raw, reason: "Tester references may use only public endpoint properties" });
481
+ }
482
+
483
+ // src/errors/PortConflictError.ts
484
+ var PortConflictError = class extends ConfigError {
485
+ port;
486
+ firstOwner;
487
+ secondOwner;
488
+ constructor(port, firstOwner, secondOwner, stage) {
489
+ super({ sourceFile: "Builder effective composition", configPath: "publicPort", value: port, stage, reason: `Host port ${port} is claimed by both ${firstOwner} and ${secondOwner}. Builder does not remap fixed public ports.` });
490
+ this.name = "PortConflictError";
491
+ this.port = port;
492
+ this.firstOwner = firstOwner;
493
+ this.secondOwner = secondOwner;
494
+ }
495
+ };
496
+
497
+ // src/core/config/hostPorts.ts
498
+ function isHostPortAvailableSync(port) {
499
+ const script = `const net=require('node:net');const s=net.createServer();s.once('error',()=>process.exit(1));s.listen(${port},'${PUBLIC_HOST}',()=>s.close(()=>process.exit(0)));`;
500
+ const result = spawnSync(process.execPath, ["-e", script], { stdio: "ignore", timeout: 3e3 });
501
+ return result.status === 0;
502
+ }
503
+ function allocateHostPorts(projectDir, stage, intentsInDeterministicOrder, validationMode = false) {
504
+ const reserved = /* @__PURE__ */ new Map(), allocated = /* @__PURE__ */ new Map();
505
+ for (const intent of intentsInDeterministicOrder) if (typeof intent.requested === "number") {
506
+ const owner = reserved.get(intent.requested);
507
+ if (owner) throw new PortConflictError(intent.requested, owner, intent.logicalPath, stage);
508
+ reserved.set(intent.requested, intent.logicalPath);
509
+ allocated.set(intent.logicalPath, intent.requested);
510
+ }
511
+ if (validationMode) {
512
+ let placeholder = 6e4;
513
+ for (const intent of intentsInDeterministicOrder) if (intent.requested === "AUTO") {
514
+ while (reserved.has(placeholder)) placeholder--;
515
+ if (placeholder < 1) throw new ConfigError({ configPath: intent.logicalPath, stage, reason: "No validation placeholder port is available" });
516
+ reserved.set(placeholder, intent.logicalPath);
517
+ allocated.set(intent.logicalPath, placeholder--);
518
+ }
519
+ return allocated;
520
+ }
521
+ const cachePath = path.join(projectDir, AUTO_PORT_CACHE_RELATIVE_PATH);
522
+ let cached = {};
523
+ try {
524
+ if (existsSync(cachePath)) {
525
+ const parsed = JSON.parse(readFileSync(cachePath, "utf8"));
526
+ if (parsed && typeof parsed === "object" && parsed.version === AUTO_PORT_CACHE_VERSION && parsed.allocations && typeof parsed.allocations === "object") cached = parsed.allocations;
270
527
  }
528
+ } catch {
529
+ cached = {};
271
530
  }
272
- if (buildJson.overrides && typeof buildJson.overrides === "object") {
273
- for (const [stage, ovr] of Object.entries(buildJson.overrides)) {
274
- if (ovr && typeof ovr === "object" && typeof ovr.path === "string") {
275
- addFile(ovr.path, `override "${stage}"`);
276
- }
531
+ const nextCache = { ...cached };
532
+ for (const intent of intentsInDeterministicOrder) if (intent.requested === "AUTO") {
533
+ const prior = cached[intent.logicalPath];
534
+ let selected = typeof prior === "number" && Number.isInteger(prior) && prior >= 1 && prior <= 65535 && !reserved.has(prior) && isHostPortAvailableSync(prior) ? prior : void 0;
535
+ if (selected === void 0) {
536
+ const scan = [...Array(65536 - AUTO_PORT_SCAN_START).keys()].map((i) => i + AUTO_PORT_SCAN_START).concat([...Array(19999 - 1024 + 1).keys()].map((i) => i + 1024));
537
+ selected = scan.find((p) => !reserved.has(p) && isHostPortAvailableSync(p));
277
538
  }
539
+ if (selected === void 0) throw new ConfigError({ sourceFile: "Builder effective composition", configPath: intent.logicalPath, stage, reason: "No available host port could be allocated" });
540
+ reserved.set(selected, intent.logicalPath);
541
+ allocated.set(intent.logicalPath, selected);
542
+ nextCache[intent.logicalPath] = selected;
278
543
  }
279
- if (Array.isArray(buildJson.composeFiles)) {
280
- for (const item of buildJson.composeFiles) {
281
- if (typeof item === "string") {
282
- addFile(item, "composeFiles");
283
- }
544
+ if (intentsInDeterministicOrder.some((i) => i.requested === "AUTO")) {
545
+ mkdirSync(path.dirname(cachePath), { recursive: true });
546
+ const temp = `${cachePath}.${process.pid}.tmp`;
547
+ writeFileSync(temp, JSON.stringify({ version: AUTO_PORT_CACHE_VERSION, allocations: nextCache }, null, 2));
548
+ renameSync(temp, cachePath);
549
+ }
550
+ return allocated;
551
+ }
552
+ function normalizeProjectName(name, projectDir) {
553
+ let normalized = name.toLowerCase().replace(/[^a-z0-9_-]/g, "-").replace(/^[-_]+/, "").replace(/[-_]+$/, "");
554
+ if (!normalized || !/^[a-z0-9]/.test(normalized)) {
555
+ if (projectDir) {
556
+ const hash = crypto.createHash("sha1").update(path.resolve(projectDir)).digest("hex").slice(0, 7);
557
+ return `project-${hash}`;
284
558
  }
559
+ return "project";
285
560
  }
286
- return files;
561
+ return normalized;
287
562
  }
288
-
289
- // src/core/checkers/checkYamlFiles.ts
290
- function checkYamlFiles(buildJson, projectDir) {
291
- const absProjectDir = resolveProjectDir(projectDir);
292
- const declaredFiles = getDeclaredYamlFiles(buildJson, absProjectDir);
293
- if (declaredFiles.length === 0) {
294
- return;
563
+ function deriveProjectName(name, stage, projectDir, options = {}) {
564
+ let base = normalizeProjectName(name, projectDir);
565
+ if (options.hash && projectDir) {
566
+ const hash = crypto.createHash("sha1").update(path.resolve(projectDir)).digest("hex").slice(0, 7);
567
+ base = `${base}-${hash}`;
295
568
  }
296
- console.log(
297
- pc22.cyan(
298
- `
299
- \u{1F50D} Validating Declared YAML Files (${declaredFiles.length} file${declaredFiles.length === 1 ? "" : "s"})...`
300
- )
301
- );
302
- const errors = [];
303
- for (const file of declaredFiles) {
304
- if (!existsSync(file.absolutePath)) {
305
- errors.push(
306
- `File "${file.relativePath}" declared in build.json (${file.source}) does not exist (expected at ${file.absolutePath}).`
307
- );
308
- continue;
309
- }
310
- try {
311
- const content = readFileSync(file.absolutePath, "utf-8");
312
- const docs = parseAllDocuments(content);
313
- const docErrors = docs.flatMap((doc) => doc.errors);
314
- if (docErrors.length > 0) {
315
- const errorText = docErrors.map((e) => e.message).join("\n");
316
- errors.push(
317
- `YAML Syntax Error in "${file.relativePath}" (${file.source}): ${errorText}`
318
- );
569
+ if (!stage) {
570
+ return base;
571
+ }
572
+ const s = stage.toLowerCase();
573
+ if (s === "dev") {
574
+ return base;
575
+ }
576
+ if (s === "prod") {
577
+ return `${base}-prod`;
578
+ }
579
+ if (s === "test" || s === "test-unit") {
580
+ return `${base}-test`;
581
+ }
582
+ if (s === "e2e" || s === "test-e2e") {
583
+ return `${base}-e2e`;
584
+ }
585
+ return `${base}-${s}`;
586
+ }
587
+ function parseVolume(mount) {
588
+ if (typeof mount === "string") {
589
+ const separators = [];
590
+ let start = 0;
591
+ for (let i = 0; i < mount.length; i++) {
592
+ if (mount[i] !== ":") continue;
593
+ if (i === start + 1 && /[a-z]/i.test(mount[start]) && /[\\/]/.test(mount[i + 1] ?? "")) continue;
594
+ separators.push(i);
595
+ start = i + 1;
596
+ }
597
+ const first = separators[0];
598
+ if (first === void 0) return { type: "volume", target: mount, suffix: "" };
599
+ const source = mount.slice(0, first), end = separators[1];
600
+ return { type: isBindMount(source) ? "bind" : "volume", source, target: mount.slice(first + 1, end), suffix: mount.slice(first) };
601
+ }
602
+ if (mount && typeof mount === "object") {
603
+ const value = mount;
604
+ return { type: String(value.type ?? "volume"), ...typeof value.source === "string" ? { source: value.source } : {}, target: String(value.target ?? ""), suffix: "" };
605
+ }
606
+ return void 0;
607
+ }
608
+ function rewriteVolumeSource(mount, source) {
609
+ const parsed = parseVolume(mount);
610
+ return typeof mount === "string" ? `${source}${parsed.suffix}` : { ...mount, source };
611
+ }
612
+ function namespaceVolume(mount, names) {
613
+ const parsed = parseVolume(mount);
614
+ const source = parsed?.type === "volume" && parsed.source ? names.get(parsed.source) : void 0;
615
+ return source ? rewriteVolumeSource(mount, source) : mount;
616
+ }
617
+ function isAnonymousVolume(mount) {
618
+ const parsed = parseVolume(mount);
619
+ return parsed?.type === "volume" && !parsed.source;
620
+ }
621
+ function isHostFilesystemRoot(source) {
622
+ const normalized = source.replaceAll("\\", "/");
623
+ if (/^[a-z]:\//i.test(normalized) || normalized.startsWith("//")) {
624
+ const windows = path.win32.normalize(source);
625
+ return windows === path.win32.parse(windows).root;
626
+ }
627
+ return path.posix.normalize(normalized) === "/";
628
+ }
629
+ function anonymousVolumeServices(services) {
630
+ return Object.entries(services).filter(([, service]) => Array.isArray(service.volumes) && service.volumes.some(isAnonymousVolume)).map(([name]) => name);
631
+ }
632
+ var posix = (p) => p.replace(/\\/g, "/");
633
+ function rebase(p, base, out) {
634
+ if (path.isAbsolute(p) || /^[A-Za-z]:[\\/]/.test(p)) return posix(path.normalize(p));
635
+ const abs = path.resolve(base, p);
636
+ const rel = path.relative(out, abs);
637
+ const result = posix(isPathInside(out, rel) ? rel || "." : abs);
638
+ return result !== "." && !result.startsWith(".") && !path.isAbsolute(result) ? `./${result}` : result;
639
+ }
640
+ function volumeShort(v, base, out) {
641
+ const mount = parseVolume(v);
642
+ if (mount?.type !== "bind" || !mount.source || /^(?:[\\/]|~|[a-z]:)/i.test(mount.source)) return v;
643
+ return rewriteVolumeSource(v, rebase(mount.source, base, out));
644
+ }
645
+ function rebaseComposePaths(document, composeFilePath, outputProjectDir) {
646
+ const doc = structuredClone(document), base = path.dirname(composeFilePath), out = path.resolve(outputProjectDir);
647
+ for (const svc of Object.values(doc.services ?? {})) {
648
+ if (typeof svc.build === "string") svc.build = rebase(svc.build, base, out);
649
+ else if (svc.build && typeof svc.build === "object") {
650
+ const b = svc.build;
651
+ const context = typeof b.context === "string" ? b.context : ".";
652
+ b.context = rebase(context, base, out);
653
+ }
654
+ if (typeof svc.env_file === "string") svc.env_file = rebase(svc.env_file, base, out);
655
+ else if (Array.isArray(svc.env_file)) svc.env_file = svc.env_file.map((v) => typeof v === "string" ? rebase(v, base, out) : v && typeof v === "object" && typeof v.path === "string" ? { ...v, path: rebase(v.path, base, out) } : v);
656
+ if (Array.isArray(svc.volumes)) svc.volumes = svc.volumes.map((v) => typeof v === "string" ? volumeShort(v, base, out) : v && typeof v === "object" && v.type === "bind" && typeof v.source === "string" ? { ...v, source: rebase(v.source, base, out) } : v);
657
+ }
658
+ for (const kind of ["configs", "secrets"]) for (const def of Object.values(doc[kind] ?? {})) if (def && typeof def === "object" && typeof def.file === "string") def.file = rebase(def.file, base, out);
659
+ return doc;
660
+ }
661
+
662
+ // src/core/composition/composeEnvironment.ts
663
+ function normalizeComposeEnvironment(value, context) {
664
+ const result = {};
665
+ if (value == null) return result;
666
+ if (Array.isArray(value)) {
667
+ for (const item of value) {
668
+ if (typeof item !== "string") throw new ConfigError({ configPath: context, value: item, reason: "Compose environment entries must be strings" });
669
+ const at = item.indexOf("=");
670
+ if (at < 0) {
671
+ result[item] = process.env[item] ?? "";
672
+ continue;
319
673
  }
320
- } catch (err) {
321
- const msg = errorMessage(err);
322
- errors.push(
323
- `YAML Syntax Error in "${file.relativePath}" (${file.source}): ${msg}`
324
- );
674
+ result[item.slice(0, at)] = item.slice(at + 1);
325
675
  }
676
+ return result;
326
677
  }
327
- if (errors.length > 0) {
328
- throw new ScriptError(errors.join("\n"));
678
+ if (typeof value !== "object") throw new ConfigError({ configPath: context, value, reason: "Compose environment must be a map or list" });
679
+ for (const [key, val] of Object.entries(value)) {
680
+ if (val === null || val === void 0) continue;
681
+ if (typeof val === "object") throw new ConfigError({ configPath: `${context}.${key}`, value: val, reason: "Compose environment value must be scalar" });
682
+ result[key] = String(val);
329
683
  }
684
+ return result;
330
685
  }
331
- function checkComposeContract(buildJson, projectDir) {
332
- const absProjectDir = resolveProjectDir(projectDir);
333
- const policyRel = buildJson.policy?.compose || buildJson.policies?.compose;
334
- if (!policyRel) {
335
- return;
686
+ function mergeComposeEnvironment(service, overlay) {
687
+ service.environment = { ...normalizeComposeEnvironment(service.environment, "service.environment"), ...overlay };
688
+ }
689
+
690
+ // src/core/composition/namespaceDependencyCompose.ts
691
+ var entries = (obj) => obj && typeof obj === "object" && !Array.isArray(obj) ? Object.entries(obj) : [];
692
+ function namespaceDependencyCompose(options) {
693
+ const { document, namespacePrefix: prefix } = options, doc = structuredClone(document);
694
+ const make = (kind, keys) => new Map(keys.map((k) => [k, `${prefix}--${kind}--${k}`]));
695
+ const serviceNameMap = make("", Object.keys(doc.services ?? {}));
696
+ for (const [k, v] of serviceNameMap) serviceNameMap.set(k, `${prefix}--${k}`);
697
+ const volumeNameMap = make("volume", Object.keys(doc.volumes ?? {})), networkNameMap = make("network", Object.keys(doc.networks ?? {})), configNameMap = make("config", Object.keys(doc.configs ?? {})), secretNameMap = make("secret", Object.keys(doc.secrets ?? {}));
698
+ const rewriteKeys = (obj, map) => Object.fromEntries(entries(obj).map(([k, v]) => [map.get(k) ?? k, v]));
699
+ const rewriteResourceRefs = (svc) => {
700
+ if (Array.isArray(svc.depends_on)) {
701
+ svc.depends_on = svc.depends_on.map((v) => typeof v === "string" ? serviceNameMap.get(v) ?? v : v);
702
+ } else if (svc.depends_on && typeof svc.depends_on === "object") svc.depends_on = rewriteKeys(svc.depends_on, serviceNameMap);
703
+ if (Array.isArray(svc.links)) svc.links = svc.links.map((v) => {
704
+ if (typeof v !== "string") return v;
705
+ const [name, ...rest] = v.split(":");
706
+ return [serviceNameMap.get(name) ?? name, ...rest].join(":");
707
+ });
708
+ if (typeof svc.network_mode === "string" && svc.network_mode.startsWith("service:")) {
709
+ const key = svc.network_mode.slice(8);
710
+ svc.network_mode = `service:${serviceNameMap.get(key) ?? key}`;
711
+ }
712
+ if (Array.isArray(svc.volumes_from)) svc.volumes_from = svc.volumes_from.map((v) => typeof v === "string" ? v.replace(/^([^:]+)(.*)$/, (all, n, rest) => `${serviceNameMap.get(n) ?? n}${rest}`) : v);
713
+ if (Array.isArray(svc.volumes)) svc.volumes = svc.volumes.map((v) => namespaceVolume(v, volumeNameMap));
714
+ if (svc.networks === void 0 && svc.network_mode === void 0 && svc.extends === void 0 && networkNameMap.has("default")) svc.networks = { default: null };
715
+ for (const key of ["ipc", "pid"]) if (typeof svc[key] === "string" && svc[key].startsWith("service:")) svc[key] = `service:${serviceNameMap.get(svc[key].slice(8)) ?? svc[key].slice(8)}`;
716
+ if (svc.extends && typeof svc.extends === "object" && !svc.extends.file) {
717
+ const ref = svc.extends;
718
+ if (typeof ref.service === "string") ref.service = serviceNameMap.get(ref.service) ?? ref.service;
719
+ }
720
+ if (Array.isArray(svc.networks)) svc.networks = svc.networks.map((v) => typeof v === "string" ? networkNameMap.get(v) ?? v : v);
721
+ else if (svc.networks && typeof svc.networks === "object") svc.networks = rewriteKeys(svc.networks, networkNameMap);
722
+ for (const key of ["configs", "secrets"]) if (Array.isArray(svc[key])) svc[key] = svc[key].map((v) => typeof v === "string" ? (key === "configs" ? configNameMap : secretNameMap).get(v) ?? v : v && typeof v === "object" ? { ...v, source: (key === "configs" ? configNameMap : secretNameMap).get(v.source) ?? v.source } : v);
723
+ };
724
+ for (const svc of Object.values(doc.services ?? {})) rewriteResourceRefs(svc);
725
+ doc.services = rewriteKeys(doc.services, serviceNameMap);
726
+ if (doc.volumes) doc.volumes = rewriteKeys(doc.volumes, volumeNameMap);
727
+ if (doc.networks) doc.networks = rewriteKeys(doc.networks, networkNameMap);
728
+ if (doc.configs) doc.configs = rewriteKeys(doc.configs, configNameMap);
729
+ if (doc.secrets) doc.secrets = rewriteKeys(doc.secrets, secretNameMap);
730
+ return { document: doc, serviceNameMap, volumeNameMap, networkNameMap, configNameMap, secretNameMap };
731
+ }
732
+
733
+ // src/core/composition/validateDependencyCompose.ts
734
+ function validateDependencyCompose(dependencyKey, dependency, document, context) {
735
+ const fail = (configPath, reason, value) => {
736
+ throw new ConfigError({ sourceFile: context.composePath, configPath, stage: context.stage, composition: "service", ...value === void 0 ? {} : { value }, reason: `Dependency "${dependencyKey}": ${reason}` });
737
+ };
738
+ if (document.include !== void 0) fail("include", "Compose include is unsupported for atomic dependency implementations");
739
+ const services = document.services ?? {};
740
+ for (const [name, svc] of Object.entries(services)) {
741
+ if (svc.ports !== void 0) fail(`services.${name}.ports`, "raw dependency ports are forbidden");
742
+ if (svc.network_mode === "host") fail(`services.${name}.network_mode`, "host network mode is forbidden");
743
+ if (svc.privileged === true) fail(`services.${name}.privileged`, `privileged services are forbidden`);
744
+ if (svc.container_name !== void 0) fail(`services.${name}.container_name`, `fixed container_name is forbidden`);
745
+ for (const v of Array.isArray(svc.volumes) ? svc.volumes : []) {
746
+ const mount = parseVolume(v);
747
+ if (mount?.type === "bind" && mount.source && isHostFilesystemRoot(mount.source)) fail(`services.${name}.volumes`, "host root bind mounts are forbidden", v);
748
+ }
749
+ const internalRefs = [];
750
+ if (Array.isArray(svc.depends_on)) {
751
+ for (const ref of svc.depends_on) if (typeof ref === "string") internalRefs.push(["depends_on", ref]);
752
+ } else if (svc.depends_on && typeof svc.depends_on === "object") {
753
+ for (const ref of Object.keys(svc.depends_on)) internalRefs.push(["depends_on", ref]);
754
+ }
755
+ if (Array.isArray(svc.links)) {
756
+ for (const ref of svc.links) if (typeof ref === "string") internalRefs.push(["links", ref.split(":")[0]]);
757
+ }
758
+ if (typeof svc.network_mode === "string" && svc.network_mode.startsWith("service:")) internalRefs.push(["network_mode", svc.network_mode.slice(8)]);
759
+ if (Array.isArray(svc.volumes_from)) {
760
+ for (const ref of svc.volumes_from) if (typeof ref === "string") internalRefs.push(["volumes_from", ref.split(":")[0]]);
761
+ }
762
+ for (const key of ["ipc", "pid"]) if (typeof svc[key] === "string" && svc[key].startsWith("service:")) internalRefs.push([key, svc[key].slice(8)]);
763
+ if (svc.extends && typeof svc.extends === "object") {
764
+ const ref = svc.extends;
765
+ if (ref.file !== void 0) fail(`services.${name}.extends.file`, "external extends is unsupported for atomic dependency implementations");
766
+ if (typeof ref.service === "string") internalRefs.push(["extends.service", ref.service]);
767
+ }
768
+ for (const [property, target] of internalRefs) if (!services[target]) fail(`services.${name}.${property}`, `internal service reference "${target}" does not exist in this dependency Compose bundle`, target);
336
769
  }
337
- const policyDir = path13.resolve(absProjectDir, policyRel);
338
- if (!existsSync(policyDir)) {
339
- return;
770
+ if (!Object.keys(dependency.endpoints).length) return;
771
+ if (!Object.keys(services).length) fail("services", "endpoint-bearing dependency Compose must define services");
772
+ const owners = /* @__PURE__ */ new Set();
773
+ for (const [endpoint, definition] of Object.entries(dependency.endpoints)) {
774
+ const owner = definition.service;
775
+ if (!services[owner]) fail(`endpoints.${endpoint}.service`, `declared endpoint owner "${owner}" does not exist`, owner);
776
+ owners.add(owner);
340
777
  }
341
- const declaredFiles = getDeclaredYamlFiles(buildJson, absProjectDir);
342
- const existingFiles = declaredFiles.filter((f) => existsSync(f.absolutePath));
343
- if (existingFiles.length === 0) {
344
- return;
778
+ for (const owner of owners) {
779
+ if (services[owner].network_mode !== void 0) fail(`services.${owner}.network_mode`, `endpoint owner cannot use network_mode`);
780
+ const health = services[owner].healthcheck;
781
+ if (!health || health.disable === true || !health.test || typeof health.test === "string" && !health.test.trim() || Array.isArray(health.test) && (!health.test.length || health.test[0] === "NONE" || health.test.every((v) => typeof v === "string" && !v.trim()))) fail(`services.${owner}.healthcheck`, `endpoint owner requires an enabled, non-empty healthcheck`);
345
782
  }
346
- for (const f of existingFiles) {
347
- if (!isPathInside(absProjectDir, f.absolutePath)) {
348
- throw new ScriptError(
349
- `Security error: Compose file path "${f.relativePath}" escapes the project directory.`
350
- );
783
+ }
784
+
785
+ // src/core/composition/validateOverrideCompose.ts
786
+ function validateAndPrepareAppOverride(document, context) {
787
+ const fail = (path19, reason, value) => {
788
+ throw new ConfigError({ sourceFile: context.file, configPath: path19, stage: context.stage, composition: "service", ...{} , reason });
789
+ };
790
+ const keys = Object.keys(document.services ?? {});
791
+ if (keys.length !== 1 || keys[0] !== "app") fail("services", "override must define exactly one service named app");
792
+ const app = structuredClone(document.services.app);
793
+ for (const k of ["ports", "depends_on", "network_mode", "container_name", "privileged"]) if (app[k] !== void 0) fail(`services.app.${k}`, "override cannot own endpoint or lifecycle behavior");
794
+ if (app.healthcheck && typeof app.healthcheck === "object") {
795
+ const health = app.healthcheck;
796
+ for (const key of Object.keys(health)) if (!["interval", "timeout", "retries", "start_period", "start_interval"].includes(key)) fail(`services.app.healthcheck.${key}`, "override may set only healthcheck timing fields");
797
+ }
798
+ if (app.build && typeof app.build === "object") {
799
+ const b = app.build;
800
+ for (const k of ["target", "dockerfile"]) if (b[k] !== void 0) fail(`services.app.build.${k}`, "override cannot change Builder-owned build configuration");
801
+ if (b.context !== void 0 && b.context !== "." && b.context !== context.expectedBuildContext) fail("services.app.build.context", "override cannot change app build context");
802
+ }
803
+ const env = normalizeComposeEnvironment(app.environment, "services.app.environment");
804
+ for (const k of ["EXEC_MODE", "INFRA_MODE"]) if (k in env) fail(`services.app.environment.${k}`, "override cannot set Builder-owned environment");
805
+ app.environment = env;
806
+ const resourceKeys = ["volumes", "networks", "configs", "secrets"];
807
+ const resources = {};
808
+ for (const kind of resourceKeys) {
809
+ const defs = document[kind] ?? {}, refs2 = /* @__PURE__ */ new Set(), value = app[kind];
810
+ if (Array.isArray(value)) for (const ref of value) {
811
+ if (kind === "volumes") {
812
+ const volume = parseVolume(ref);
813
+ if (volume?.type === "volume" && volume.source) refs2.add(volume.source);
814
+ } else if (typeof ref === "string") refs2.add(ref);
815
+ else if (ref && typeof ref === "object" && typeof ref.source === "string") refs2.add(ref.source);
816
+ }
817
+ else if (value && typeof value === "object") for (const name of Object.keys(value)) refs2.add(name);
818
+ const names = /* @__PURE__ */ new Map(), mapped = {};
819
+ for (const [name, definition] of Object.entries(defs)) {
820
+ if (!refs2.has(name)) fail(`${kind}.${name}`, "override resource must be consumed by app");
821
+ const target = `app-override--${context.stage}--${kind.slice(0, -1)}--${name}`;
822
+ names.set(name, target);
823
+ mapped[target] = definition;
824
+ }
825
+ if (names.size) resources[kind] = mapped;
826
+ if (Array.isArray(value)) app[kind] = value.map((ref) => kind === "volumes" ? namespaceVolume(ref, names) : typeof ref === "string" ? names.get(ref) ?? ref : ref && typeof ref === "object" && typeof ref.source === "string" ? { ...ref, source: names.get(ref.source) ?? ref.source } : ref);
827
+ else if (value && typeof value === "object") app[kind] = Object.fromEntries(Object.entries(value).map(([name, definition]) => [names.get(name) ?? name, definition]));
828
+ }
829
+ return { app, resources };
830
+ }
831
+
832
+ // src/core/composition/dependencyLifecycle.ts
833
+ function asMap(value) {
834
+ if (Array.isArray(value)) return Object.fromEntries(value.filter((v) => typeof v === "string").map((v) => [v, {}]));
835
+ if (value && typeof value === "object") return value;
836
+ return {};
837
+ }
838
+ function healthyMerge(target, owners) {
839
+ const current = asMap(target.depends_on);
840
+ for (const owner of owners) {
841
+ const old = current[owner];
842
+ const cond = old && typeof old === "object" ? old.condition : void 0;
843
+ current[owner] = { ...old && typeof old === "object" ? old : {}, condition: cond === "service_healthy" ? cond : "service_healthy" };
844
+ }
845
+ target.depends_on = current;
846
+ }
847
+ function applyDependencyLifecycle(app, materialized, effectiveBuild) {
848
+ const appOwners = /* @__PURE__ */ new Set();
849
+ for (const dep of Object.values(materialized)) for (const owner of dep.endpointOwners) appOwners.add(owner);
850
+ healthyMerge(app, appOwners);
851
+ for (const [key, dep] of Object.entries(materialized)) {
852
+ const config = effectiveBuild.dependencies[key];
853
+ if (!config) continue;
854
+ for (const raw of config.dependsOn) {
855
+ const match = DEPENDENCY_REFERENCE_PATTERN.exec(raw);
856
+ if (!match) continue;
857
+ const target = materialized[match[1]];
858
+ if (!target) continue;
859
+ for (const sourceOwner of dep.endpointOwners) {
860
+ const source = dep.compose.services[sourceOwner];
861
+ if (source) healthyMerge(source, target.endpointOwners);
862
+ }
351
863
  }
352
864
  }
353
- const relativePaths = existingFiles.map((f) => f.relativePath);
354
- console.log(pc22.cyan(`
355
- \u{1F50D} Validating Compose Contract (${policyRel})...`));
356
- runStep(
357
- "docker",
358
- [
359
- "run",
360
- "--rm",
361
- "--network",
362
- "none",
363
- "--mount",
364
- `type=bind,src=${absProjectDir},dst=/project,readonly`,
365
- "-w",
366
- "/project",
367
- CONFTEST_IMAGE,
368
- "test",
369
- ...relativePaths,
370
- "-p",
371
- `${policyRel}/`,
372
- "--all-namespaces"
373
- ],
374
- absProjectDir,
375
- {
376
- stepName: "Compose Contract Validation",
377
- targetFile: relativePaths.join(", ")
378
- }
379
- );
865
+ }
866
+
867
+ // src/core/composition/serviceEndpoints.ts
868
+ function buildStandaloneAppEndpoints(build, stage, host = "app") {
869
+ const out = {};
870
+ for (const [name, e] of Object.entries(build.app.endpoints)) out[name] = { logicalPath: `app.endpoints.${name}`, networkHost: host, networkPort: e.port, ...e.scheme ? { scheme: e.scheme } : {}, ...e.publicPort !== void 0 ? { publicHost: PUBLIC_HOST } : {}, effectivelyPublished: e.publicPort !== void 0 };
871
+ return out;
872
+ }
873
+ function buildStandaloneDependencyEndpoints(key, build, serviceNames, materialized) {
874
+ const out = {};
875
+ for (const [name, e] of Object.entries(build.dependencies[key]?.endpoints ?? {})) {
876
+ const host = serviceNames.get(e.service) ?? e.service;
877
+ out[name] = { logicalPath: `dependencies.${key}.endpoints.${name}`, networkHost: host, networkPort: e.port, ...e.scheme ? { scheme: e.scheme } : {}, ...materialized && e.publicPort !== void 0 ? { publicHost: PUBLIC_HOST } : {}, effectivelyPublished: materialized && e.publicPort !== void 0 };
878
+ }
879
+ return out;
880
+ }
881
+
882
+ // src/core/composition/compileServiceComposition.ts
883
+ function getExecutionProfile(stage, full) {
884
+ switch (stage) {
885
+ case "dev":
886
+ return { configStage: "dev", appTarget: "dev", runtimeStage: "dev", integrated: full, attachTester: false };
887
+ case "prod":
888
+ return { configStage: "prod", appTarget: "prod", runtimeStage: "prod", integrated: true, attachTester: false };
889
+ case "test":
890
+ return { configStage: "test", appTarget: "test", runtimeStage: "test", integrated: false, attachTester: false };
891
+ case "e2e":
892
+ return { configStage: "e2e", appTarget: "prod", runtimeStage: "e2e", integrated: true, attachTester: true, testerTarget: "test-e2e" };
893
+ }
894
+ }
895
+ function mergeDocument(target, source, context) {
896
+ for (const section of ["services", "volumes", "networks", "configs", "secrets"]) {
897
+ const src = source[section];
898
+ if (!src) continue;
899
+ const dst = target[section] ??= {};
900
+ for (const [key, value] of Object.entries(src)) {
901
+ if (key in dst) throw new ConfigError({ configPath: `${section}.${key}`, referencedObject: context, reason: "Internal Compose namespace collision" });
902
+ dst[key] = value;
903
+ }
904
+ }
905
+ }
906
+ function getTemplateSeed(stage, meshMode) {
907
+ const base = parse(fs.readFileSync(getDockerComposeTemplate("docker-compose.base.yml"), "utf8"));
908
+ const stageName = stage === "e2e" ? "e2e" : stage;
909
+ const overlay = parse(fs.readFileSync(getDockerComposeTemplate(`docker-compose.${stageName}.yml`), "utf8"));
910
+ const merged = { ...base, services: { ...base.services ?? {} } };
911
+ for (const [name, svc] of Object.entries(overlay.services ?? {})) merged.services[name] = { ...merged.services[name] ?? {}, ...svc, build: { ...merged.services[name]?.build ?? {}, ...svc.build ?? {} } };
912
+ if (meshMode) delete merged.services.tester;
913
+ return merged;
914
+ }
915
+ function ownEnv(build, stage) {
916
+ const env = { ...build.app.env };
917
+ const reserved = ["EXEC_MODE", "INFRA_MODE", ...getPrimaryEndpoint(build.app.endpoints) ? ["PORT"] : []];
918
+ for (const key of reserved) if (key in env) throw new ConfigError({ sourceFile: "build.json", configPath: "app.env", stage, composition: "service", value: key, reason: "Application env cannot set a Builder-owned key" });
919
+ return env;
920
+ }
921
+ function resolveEnv(input, registry, source) {
922
+ const out = {};
923
+ for (const [key, value] of Object.entries(input)) {
924
+ collectBuilderReferences(value, "build", `${source}.${key}`);
925
+ out[key] = interpolateBuilderReferences(value, "build", registry).replace(/\$/g, "$$$$");
926
+ }
927
+ return out;
928
+ }
929
+ function addPorts(service, endpointPairs) {
930
+ for (const [ep, hostPort] of endpointPairs) {
931
+ const ports = Array.isArray(service.ports) ? service.ports : [];
932
+ if (ports.some((p) => p && typeof p === "object" && p.published === hostPort)) throw new ConfigError({ configPath: ep.logicalPath, stage: "service", value: hostPort, reason: "Duplicate host port publication" });
933
+ ports.push({ target: ep.networkPort, published: hostPort, host_ip: PUBLIC_HOST, protocol: "tcp" });
934
+ service.ports = ports;
935
+ }
936
+ }
937
+ function compileServiceComposition(stage, projectDir, options = {}) {
938
+ const root = resolveProjectDir(projectDir), buildPath = path.join(root, "build.json"), raw = getBuildJson(root), effective = resolveBuildStage(raw, stage, buildPath), profile = getExecutionProfile(stage, Boolean(options.full));
939
+ resolveApplicationDockerfile(root, raw.dockerfile ?? "Dockerfile", stage);
940
+ const seed = getTemplateSeed(stage, Boolean(options.meshMode));
941
+ const rawName = options.projectNameOverride ?? raw.name ?? path.basename(root);
942
+ const projectName = deriveProjectName(rawName, stage);
943
+ const namespaced = {};
944
+ for (const [key, dep] of Object.entries(effective.dependencies).sort(([a], [b]) => a.localeCompare(b))) {
945
+ const sourcePath = resolveInsideProject(root, dep.compose, { sourceFile: buildPath, configPath: `dependencies.${key}.compose`, stage });
946
+ const document = rebaseComposePaths(loadComposeDocument(sourcePath, { sourceFile: buildPath, configPath: `dependencies.${key}.compose`, stage, composition: "service" }), sourcePath, options.composeOutputDir ?? root);
947
+ validateDependencyCompose(key, dep, document, { composePath: sourcePath, stage });
948
+ if (Object.keys(dep.endpoints).length) {
949
+ const ns = namespaceDependencyCompose({ namespacePrefix: options.namespacePrefix ? `${options.namespacePrefix}${key}` : `dep--${key}`, document });
950
+ namespaced[key] = { doc: ns.document, map: ns.serviceNameMap, source: sourcePath };
951
+ }
952
+ }
953
+ const materialized = {};
954
+ const compose = { ...seed, ...options.meshMode ? {} : { name: projectName }, services: { ...seed.services } };
955
+ let app = compose.services.app ?? (compose.services.app = { build: { context: "." } });
956
+ if (profile.integrated) for (const [key, entry] of Object.entries(namespaced)) {
957
+ if (options.suppressDependencies?.has(key)) continue;
958
+ const dep = effective.dependencies[key];
959
+ const item = structuredClone(entry.doc);
960
+ mergeDocument(compose, item, `dependency ${key}`);
961
+ const endpointOwnerMap = /* @__PURE__ */ new Map();
962
+ for (const [epName, ep] of Object.entries(dep.endpoints)) endpointOwnerMap.set(epName, entry.map.get(ep.service));
963
+ const endpointOwners = new Set(endpointOwnerMap.values());
964
+ materialized[key] = { key, composePath: entry.source, compose: item, serviceNameMap: entry.map, endpointOwnerMap, endpoints: {}, endpointOwners };
965
+ }
966
+ const appEndpoints = buildStandaloneAppEndpoints(effective, stage, options.appServiceName ?? "app");
967
+ const depEndpoints = {};
968
+ for (const [key, dep] of Object.entries(effective.dependencies)) {
969
+ depEndpoints[key] = buildStandaloneDependencyEndpoints(key, effective, namespaced[key]?.map ?? /* @__PURE__ */ new Map(), Boolean(materialized[key]));
970
+ if (options.meshMode) for (const ep of Object.values(depEndpoints[key])) {
971
+ ep.effectivelyPublished = false;
972
+ delete ep.publicHost;
973
+ delete ep.publicPort;
974
+ }
975
+ }
976
+ if (options.meshMode) for (const ep of Object.values(appEndpoints)) {
977
+ ep.effectivelyPublished = false;
978
+ delete ep.publicHost;
979
+ delete ep.publicPort;
980
+ }
981
+ const intents = [];
982
+ if (!options.meshMode) {
983
+ for (const [name, e] of Object.entries(effective.app.endpoints).sort(([a], [b]) => a.localeCompare(b))) if (e.publicPort !== void 0) intents.push({ logicalPath: `app.endpoints.${name}`, requested: e.publicPort });
984
+ for (const [key, dep] of Object.entries(effective.dependencies).sort(([a], [b]) => a.localeCompare(b))) if (materialized[key]) {
985
+ for (const [name, e] of Object.entries(dep.endpoints).sort(([a], [b]) => a.localeCompare(b))) if (e.publicPort !== void 0) intents.push({ logicalPath: `dependencies.${key}.endpoints.${name}`, requested: e.publicPort });
986
+ }
987
+ }
988
+ const allocation = allocateHostPorts(root, stage, intents, Boolean(options.validationMode));
989
+ for (const [name, ep] of Object.entries(appEndpoints)) if (allocation.has(ep.logicalPath)) {
990
+ ep.publicHost = PUBLIC_HOST;
991
+ ep.publicPort = allocation.get(ep.logicalPath);
992
+ ep.effectivelyPublished = true;
993
+ }
994
+ for (const [key, eps] of Object.entries(depEndpoints)) for (const [name, ep] of Object.entries(eps)) if (allocation.has(ep.logicalPath)) {
995
+ ep.publicHost = PUBLIC_HOST;
996
+ ep.publicPort = allocation.get(ep.logicalPath);
997
+ ep.effectivelyPublished = true;
998
+ }
999
+ const registry = (ref) => {
1000
+ if (ref.target === "app") {
1001
+ const ep2 = appEndpoints[ref.endpoint];
1002
+ if (!ep2) throw new ConfigError({ sourceFile: buildPath, configPath: ref.raw, stage, composition: "service", referencedObject: ref.raw, reason: "Unknown app endpoint reference" });
1003
+ return resolveEndpointProperty(ep2, ref.property, { sourceFile: buildPath, configPath: ref.raw, stage });
1004
+ }
1005
+ const ep = depEndpoints[ref.dependency]?.[ref.endpoint];
1006
+ if (!ep) throw new ConfigError({ sourceFile: buildPath, configPath: ref.raw, stage, composition: "service", referencedObject: ref.raw, reason: "Unknown dependency endpoint reference" });
1007
+ return resolveEndpointProperty(ep, ref.property, { sourceFile: buildPath, configPath: ref.raw, stage });
1008
+ };
1009
+ for (const [key, dep] of Object.entries(effective.dependencies)) {
1010
+ const depEnv = options.deferReferenceResolution ? dep.env : resolveEnv(dep.env, registry, `dependencies.${key}.env`);
1011
+ for (const svc of Object.values(materialized[key]?.compose.services ?? {})) mergeComposeEnvironment(svc, depEnv);
1012
+ }
1013
+ const appEnv = options.deferReferenceResolution ? ownEnv(effective, stage) : resolveEnv(ownEnv(effective, stage), registry, "app.env");
1014
+ let buildAppEnvironment = { ...appEnv };
1015
+ const runtimeDotenv = path.join(root, `.env.${profile.runtimeStage}`);
1016
+ if (fs.existsSync(runtimeDotenv)) {
1017
+ const text = fs.readFileSync(runtimeDotenv, "utf8");
1018
+ for (const line of text.split(/\r?\n/)) {
1019
+ const match = line.match(/^\s*(?:export\s+)?(EXEC_MODE|INFRA_MODE|PORT)\s*=/);
1020
+ if (match && (match[1] !== "PORT" || getPrimaryEndpoint(effective.app.endpoints))) throw new ConfigError({ sourceFile: runtimeDotenv, configPath: match[1], stage, composition: "service", reason: "Dotenv file cannot define Builder-owned environment" });
1021
+ }
1022
+ }
1023
+ const internal = { EXEC_MODE: profile.runtimeStage, INFRA_MODE: profile.integrated ? "integrated" : "isolated", ...getPrimaryEndpoint(effective.app.endpoints) ? { PORT: String(getPrimaryEndpoint(effective.app.endpoints)[1].port) } : {} };
1024
+ const appBuild = app.build && typeof app.build === "object" ? app.build : { context: "." };
1025
+ const outputDir = options.composeOutputDir ? path.resolve(options.composeOutputDir) : root;
1026
+ const serviceContext = path.relative(outputDir, root).replace(/\\/g, "/") || ".";
1027
+ appBuild.context = options.meshMode ? serviceContext : ".";
1028
+ if (raw.dockerfile) appBuild.dockerfile = raw.dockerfile;
1029
+ else delete appBuild.dockerfile;
1030
+ appBuild.target = profile.appTarget;
1031
+ app.build = appBuild;
1032
+ app.env_file = [{ path: options.meshMode ? path.posix.join(serviceContext, `.env.${profile.runtimeStage}`) : `.env.${profile.runtimeStage}`, required: false }];
1033
+ app.environment = { ...appEnv, ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
1034
+ if (stage === "dev") app.volumes = [`${options.meshMode && serviceContext !== "." ? `./${serviceContext}` : "."}:/app`, "/app/node_modules"];
1035
+ for (const [name, ep] of Object.entries(appEndpoints)) if (!options.meshMode && ep.effectivelyPublished) addPorts(app, [[ep, ep.publicPort]]);
1036
+ for (const [key, dependency] of Object.entries(materialized)) {
1037
+ for (const [epName, owner] of dependency.endpointOwnerMap.entries()) {
1038
+ const endpoint = depEndpoints[key][epName];
1039
+ if (!options.meshMode && endpoint.effectivelyPublished) addPorts(compose.services[owner], [[endpoint, endpoint.publicPort]]);
1040
+ }
1041
+ for (const owner of dependency.endpointOwners) {
1042
+ const svc = compose.services[owner];
1043
+ if (!options.meshMode && svc.networks !== void 0) {
1044
+ const nets = svc.networks;
1045
+ if (Array.isArray(nets)) {
1046
+ if (!nets.includes("default")) nets.push("default");
1047
+ } else if (nets && typeof nets === "object") nets.default = null;
1048
+ }
1049
+ }
1050
+ for (const [epName, ep] of Object.entries(depEndpoints[key])) dependency.endpoints[epName] = ep;
1051
+ }
1052
+ if (effective.overrideCompose) {
1053
+ const overridePath = resolveInsideProject(root, effective.overrideCompose, { sourceFile: buildPath, configPath: "override-compose", stage });
1054
+ const odoc = rebaseComposePaths(loadComposeDocument(overridePath, { sourceFile: buildPath, configPath: "override-compose", stage, composition: "service" }), overridePath, options.composeOutputDir ?? root);
1055
+ const prepared = validateAndPrepareAppOverride(odoc, { file: overridePath, stage, expectedBuildContext: options.meshMode ? path.relative(options.composeOutputDir ?? root, root).replace(/\\/g, "/") || "." : "." });
1056
+ for (const section of ["volumes", "networks", "configs", "secrets"]) if (prepared.resources[section]) mergeDocument(compose, { services: {}, [section]: prepared.resources[section] }, "app override");
1057
+ const rawOverrideEnv = normalizeComposeEnvironment(prepared.app.environment, "override-compose.services.app.environment");
1058
+ const overrideEnv = options.deferReferenceResolution ? rawOverrideEnv : resolveEnv(rawOverrideEnv, registry, "override-compose.services.app.environment");
1059
+ if (getPrimaryEndpoint(effective.app.endpoints) && "PORT" in overrideEnv) throw new ConfigError({ sourceFile: overridePath, configPath: "services.app.environment.PORT", stage, composition: "service", reason: "Override cannot set Builder-owned PORT" });
1060
+ buildAppEnvironment = { ...appEnv, ...overrideEnv };
1061
+ const merged = { ...app, ...prepared.app };
1062
+ merged.environment = { ...appEnv, ...overrideEnv, ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
1063
+ const overrideBuild = prepared.app.build && typeof prepared.app.build === "object" ? prepared.app.build : {};
1064
+ if (overrideBuild.args !== void 0) appBuild.args = overrideBuild.args;
1065
+ merged.build = appBuild;
1066
+ merged.env_file = app.env_file;
1067
+ merged.depends_on = app.depends_on;
1068
+ merged.networks = { ...!options.meshMode ? { default: null } : {}, ...normalizeNetworks(app.networks), ...normalizeNetworks(prepared.app.networks) };
1069
+ compose.services.app = merged;
1070
+ app = merged;
1071
+ }
1072
+ if (options.meshMode && options.appServiceName && options.appServiceName !== "app") {
1073
+ delete compose.services.app;
1074
+ compose.services[options.appServiceName] = app;
1075
+ }
1076
+ if (profile.integrated) applyDependencyLifecycle(app, materialized, effective);
1077
+ if (profile.attachTester && !options.meshMode) {
1078
+ const testerEnvRaw = effective.tester?.env ?? {};
1079
+ assertTesterReferencesArePublic(testerEnvRaw, "build", "tester.env");
1080
+ const testerEnv = options.deferReferenceResolution ? testerEnvRaw : resolveEnv(testerEnvRaw, registry, "tester.env");
1081
+ compose.services.tester = { build: { context: ".", ...raw.dockerfile ? { dockerfile: raw.dockerfile } : {}, target: "test-e2e" }, network_mode: "host", environment: testerEnv, depends_on: { app: { condition: "service_healthy" } } };
1082
+ }
1083
+ const builderAppEnvironment = { ...buildAppEnvironment, ...options.externalAppEnv ?? {} };
1084
+ return { compose, effectiveBuild: effective, endpoints: { app: appEndpoints, dependencies: depEndpoints }, projectName, ...profile.attachTester && !options.meshMode ? { testerServiceName: "tester" } : {}, builderAppEnvironment, buildAppEnvironment, externalAppEnvironment: { ...options.externalAppEnv ?? {} }, dependencyEnvironments: Object.fromEntries(Object.entries(effective.dependencies).map(([key, dep]) => [key, dep.env])) };
1085
+ }
1086
+
1087
+ // src/core/checkers/checkEffectiveServiceStages.ts
1088
+ function checkAllEffectiveServiceStages(projectDir) {
1089
+ compileServiceComposition("dev", projectDir, { validationMode: true });
1090
+ compileServiceComposition("dev", projectDir, { full: true, validationMode: true });
1091
+ compileServiceComposition("prod", projectDir, { validationMode: true });
1092
+ compileServiceComposition("test", projectDir, { validationMode: true });
1093
+ compileServiceComposition("e2e", projectDir, { validationMode: true });
380
1094
  }
381
1095
 
382
1096
  // src/core/checkers/checkInfra.ts
@@ -386,8 +1100,8 @@ function checkInfra(projectDir = process.cwd()) {
386
1100
  checkDockerfile(buildJson, absProjectDir);
387
1101
  checkDockerfileContract(buildJson, absProjectDir);
388
1102
  checkYamlFiles(buildJson, absProjectDir);
389
- checkComposeContract(buildJson, absProjectDir);
390
- console.log(pc22.green("\n\u2705 All infrastructure and contract checks passed.\n"));
1103
+ checkAllEffectiveServiceStages(absProjectDir);
1104
+ console.log(pc22.green("\n\u2705 All V2 service infrastructure and contract checks passed.\n"));
391
1105
  }
392
1106
  function checkComposeAvailability() {
393
1107
  const composeCheck = spawnSync(
@@ -471,326 +1185,489 @@ Examples:
471
1185
  }
472
1186
  });
473
1187
  };
474
- var meshHealthcheckSchema = z.union([
475
- z.object({
476
- type: z.literal("tcp"),
477
- port: z.union([z.number(), z.string()]).optional()
478
- }).strict(),
479
- z.object({
480
- test: z.union([z.string(), z.array(z.string())]),
481
- interval: z.string().optional(),
482
- timeout: z.string().optional(),
483
- retries: z.number().optional(),
484
- start_period: z.string().optional(),
485
- disable: z.boolean().optional()
486
- }).passthrough()
487
- ]);
488
- var meshServiceSchema = z.object({
489
- path: z.string({ required_error: 'Service "path" is required' }).describe("Relative path to service directory containing build.json"),
490
- port: z.union([z.number(), z.string()]).optional().describe("Public host port mapped to internal port 3000"),
491
- preservePort: z.boolean().optional().describe("If true, use the port declared in build.json"),
492
- provideDependency: z.record(z.string(), z.string()).optional().describe("Map consumer dependency key to fellow mesh service provider"),
493
- replaceMocks: z.record(z.string(), z.string()).optional().describe("Alias for provideDependency"),
494
- envOverrides: z.record(z.string(), z.string()).optional().describe("Environment variable overrides with URL templating"),
495
- healthcheck: meshHealthcheckSchema.optional()
496
- }).strict();
497
- var meshTesterSchema = z.object({
498
- path: z.string({ required_error: 'Tester "path" is required' }).describe("Relative path to E2E tester directory"),
499
- compose: z.string().optional().describe("Tester compose file (defaults to 'docker-compose.yml')"),
500
- dockerfile: z.string().optional().describe("Tester Dockerfile (defaults to 'Dockerfile')"),
501
- envOverrides: z.record(z.string(), z.string()).optional().describe(
502
- "Environment variable overrides for global tester with URL templating"
503
- ),
504
- policy: z.object({
505
- dockerfile: z.string().optional(),
506
- compose: z.string().optional()
507
- }).strict().optional()
508
- }).strict();
509
- var meshServiceNameRegex = /^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/;
510
- var meshSchema = z.object({
511
- $schema: z.string().optional(),
512
- name: z.string().optional(),
513
- services: z.record(
514
- z.string().regex(meshServiceNameRegex, {
515
- message: "Service name must start with a lowercase letter or digit and contain only lowercase letters, digits, '-', '_', or '.'"
516
- }),
517
- meshServiceSchema
518
- ).refine((services) => Object.keys(services).length > 0, {
519
- message: 'At least one service must be defined in "services".'
520
- }),
521
- dependencies: z.record(
522
- z.string(),
523
- z.object({
524
- path: z.string(),
525
- service: z.string().optional()
526
- }).strict()
527
- ).optional(),
528
- tester: meshTesterSchema.optional()
529
- }).strict();
530
-
531
- // src/core/mesh/checkers/checkMeshJson.ts
532
- function checkMeshJson(mesh) {
533
- const result = meshSchema.safeParse(mesh);
534
- if (!result.success) {
535
- const errorDetails = result.error.issues.map(
536
- (issue) => issue.path.length > 0 ? `${issue.path.join(".")}: ${issue.message}` : issue.message
537
- ).join("; ");
538
- throw new ScriptError(`Invalid mesh.json: ${errorDetails}`);
539
- }
540
- const services = result.data.services;
541
- const serviceKeys = new Set(Object.keys(services));
542
- const graph = /* @__PURE__ */ new Map();
543
- for (const sName of serviceKeys) {
544
- graph.set(sName, /* @__PURE__ */ new Set());
545
- }
546
- for (const [serviceName, serviceConfig] of Object.entries(services)) {
547
- const provideMap = {
548
- ...serviceConfig.replaceMocks || {},
549
- ...serviceConfig.provideDependency || {}
550
- };
551
- for (const [depKey, targetSvc] of Object.entries(provideMap)) {
552
- if (!serviceKeys.has(targetSvc)) {
553
- throw new ScriptError(
554
- `Invalid mesh.json: Service "${serviceName}" maps dependency "${depKey}" to nonexistent service "${targetSvc}".`
555
- );
556
- }
557
- graph.get(serviceName).add(targetSvc);
558
- }
559
- }
560
- const visited = /* @__PURE__ */ new Map();
561
- function dfs(node, pathStack) {
562
- visited.set(node, "visiting");
563
- pathStack.push(node);
564
- const neighbors = graph.get(node) || /* @__PURE__ */ new Set();
565
- for (const neighbor of neighbors) {
566
- const state = visited.get(neighbor);
567
- if (state === "visiting") {
568
- const cycleStart = pathStack.indexOf(neighbor);
569
- const cycle = [...pathStack.slice(cycleStart), neighbor];
570
- throw new ScriptError(
571
- `Dependency cycle detected in mesh.json: ${cycle.join(" -> ")}`
572
- );
573
- }
574
- if (!state) {
575
- dfs(neighbor, pathStack);
576
- }
577
- }
578
- pathStack.pop();
579
- visited.set(node, "visited");
580
- }
581
- for (const sName of serviceKeys) {
582
- if (!visited.has(sName)) {
583
- dfs(sName, []);
584
- }
585
- }
586
- }
1188
+ var identifierSchema2 = z.string().regex(BUILDER_IDENTIFIER_PATTERN, "must match ^[a-z][a-z0-9-]*$");
1189
+ var serviceNameSchema = identifierSchema2.refine((name) => !RESERVED_MESH_SERVICE_NAMES.has(name), { message: "is reserved and cannot be used as a mesh service name" });
1190
+ var envSchema2 = z.record(z.string(), z.string());
1191
+ var meshServiceSchema = z.object({ path: z.string().min(1), env: envSchema2.optional(), dependencies: z.record(identifierSchema2, serviceNameSchema).optional(), dependsOn: z.array(serviceNameSchema).optional(), publish: z.array(z.string()).optional() }).strict();
1192
+ var meshServiceStageOverlaySchema = z.object({ path: z.string().min(1).optional(), env: envSchema2.optional(), dependencies: z.record(identifierSchema2, serviceNameSchema).optional(), dependsOn: z.array(serviceNameSchema).optional(), publish: z.array(z.string()).optional() }).strict();
1193
+ var meshStageSchema = z.object({ services: z.record(serviceNameSchema, meshServiceStageOverlaySchema).optional() }).strict();
1194
+ var meshSchema = z.object({ $schema: z.string().optional(), name: z.string().optional(), tester: z.object({ compose: z.string().min(1), service: z.string().min(1), env: envSchema2.optional() }).strict().optional(), services: z.record(serviceNameSchema, meshServiceSchema), dev: meshStageSchema.optional(), prod: meshStageSchema.optional(), test: meshStageSchema.optional(), e2e: meshStageSchema.optional() }).strict();
587
1195
 
588
1196
  // src/core/mesh/getMeshJson.ts
589
1197
  function getMeshJson(projectDir = process.cwd()) {
590
- const absDir = resolveProjectDir(projectDir);
591
- const meshPath = path13.resolve(absDir, "mesh.json");
592
- if (!existsSync(meshPath)) {
593
- throw new NotFoundError(`mesh.json not found in directory: ${absDir}`);
594
- }
1198
+ const absDir = resolveProjectDir(projectDir), meshPath = path.resolve(absDir, "mesh.json");
1199
+ if (!existsSync(meshPath)) throw new NotFoundError(`mesh.json not found in directory: ${absDir}`);
595
1200
  let content;
596
1201
  try {
597
1202
  content = readFileSync(meshPath, "utf-8");
598
1203
  } catch (err) {
599
- throw new ScriptError(
600
- `Failed to read mesh.json at ${meshPath}: ${errorMessage(err)}`
601
- );
1204
+ throw new ScriptError(`Failed to read mesh.json at ${meshPath}: ${errorMessage(err)}`);
602
1205
  }
603
1206
  let parsed;
604
1207
  try {
605
1208
  parsed = JSON.parse(content);
606
1209
  } catch (err) {
607
- throw new ScriptError(
608
- `Failed to parse mesh.json at ${meshPath}: ${errorMessage(err)}`
609
- );
1210
+ throw new ScriptError(`Failed to parse mesh.json at ${meshPath}: ${errorMessage(err)}`);
610
1211
  }
611
- if (!parsed || typeof parsed !== "object") {
612
- throw new ScriptError(`Invalid mesh.json: root must be an object.`);
1212
+ const result = meshSchema.safeParse(parsed);
1213
+ if (!result.success) {
1214
+ const reason = result.error.issues.map((issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`).join("; ");
1215
+ throw new ConfigError({ sourceFile: meshPath, configPath: "<root>", composition: "mesh", reason: `Invalid mesh.json: ${reason}` });
613
1216
  }
614
- const meshConfig = parsed;
615
- checkMeshJson(meshConfig);
616
- return meshConfig;
1217
+ return result.data;
617
1218
  }
618
- function checkMeshServices(mesh, meshDir = process.cwd()) {
619
- const absMeshDir = resolveProjectDir(meshDir);
620
- const serviceNames = Object.keys(mesh.services);
621
- console.log(
622
- pc22.bold(
623
- pc22.cyan(
624
- `
625
- \u{1F50D} Checking Mesh Services (${serviceNames.length} service${serviceNames.length === 1 ? "" : "s"})...`
626
- )
627
- )
628
- );
629
- for (const serviceName of serviceNames) {
630
- const serviceConfig = mesh.services[serviceName];
631
- if (!serviceConfig) {
632
- throw new ScriptError(`Service "${serviceName}" configuration is missing.`);
633
- }
634
- const serviceDir = path13.resolve(absMeshDir, serviceConfig.path);
635
- if (!isPathInside(absMeshDir, serviceDir)) {
636
- throw new ScriptError(
637
- `Security error: Service "${serviceName}" directory escapes the mesh directory: ${serviceDir}`
638
- );
639
- }
640
- if (!existsSync(serviceDir)) {
641
- throw new ScriptError(
642
- `Service "${serviceName}" directory does not exist: ${serviceDir} (declared path: "${serviceConfig.path}")`
643
- );
644
- }
645
- if (!statSync(serviceDir).isDirectory()) {
646
- throw new ScriptError(
647
- `Service "${serviceName}" path is not a directory: ${serviceDir}`
648
- );
649
- }
650
- const buildJsonPath = path13.resolve(serviceDir, "build.json");
651
- if (!existsSync(buildJsonPath)) {
652
- throw new ScriptError(
653
- `Service "${serviceName}" is missing a valid build.json at: ${buildJsonPath}`
654
- );
1219
+
1220
+ // src/core/config/resolveMeshStage.ts
1221
+ function resolveMeshStage(mesh, stage, sourceFile) {
1222
+ const overlays = mesh[stage]?.services ?? {}, names = /* @__PURE__ */ new Set([...Object.keys(mesh.services), ...Object.keys(overlays)]), services = {};
1223
+ for (const name of names) {
1224
+ const base = mesh.services[name], patch = overlays[name];
1225
+ const merged = { path: patch?.path ?? base?.path, env: mergeStringMap(base?.env, patch?.env), dependencies: { ...base?.dependencies ?? {}, ...patch?.dependencies ?? {} }, dependsOn: unionStable(base?.dependsOn, patch?.dependsOn), publish: unionStable(base?.publish, patch?.publish) };
1226
+ if (!merged.path) throw new ConfigError({ sourceFile, configPath: `services.${name}.path`, stage, composition: "mesh", reason: "Effective mesh service requires path" });
1227
+ services[name] = merged;
1228
+ }
1229
+ if (!Object.keys(services).length) throw new ConfigError({ sourceFile, configPath: "services", stage, composition: "mesh", reason: "At least one effective mesh service is required" });
1230
+ const graph = /* @__PURE__ */ new Map();
1231
+ for (const [name, service] of Object.entries(services)) {
1232
+ if (!BUILDER_IDENTIFIER_PATTERN.test(name) || RESERVED_MESH_SERVICE_NAMES.has(name)) throw new ConfigError({ sourceFile, configPath: `services.${name}`, stage, composition: "mesh", value: name, reason: "Invalid or reserved mesh service name" });
1233
+ graph.set(name, /* @__PURE__ */ new Set());
1234
+ for (const target of service.dependsOn) {
1235
+ if (target === name) throw new ConfigError({ sourceFile, configPath: `services.${name}.dependsOn`, stage, composition: "mesh", referencedObject: target, reason: "Mesh service cannot depend on itself" });
1236
+ if (!services[target]) throw new ConfigError({ sourceFile, configPath: `services.${name}.dependsOn`, stage, composition: "mesh", referencedObject: target, reason: "Unknown mesh lifecycle target" });
1237
+ graph.get(name).add(target);
1238
+ }
1239
+ }
1240
+ assertAcyclicGraph(graph, { sourceFile, stage, composition: "mesh" });
1241
+ const result = { ...mesh, services };
1242
+ delete result.dev;
1243
+ delete result.prod;
1244
+ delete result.test;
1245
+ delete result.e2e;
1246
+ return result;
1247
+ }
1248
+ function loadEffectiveMeshServices(meshDir, effectiveMesh, stage) {
1249
+ const out = {};
1250
+ for (const [name, svc] of Object.entries(effectiveMesh.services).sort(([a], [b]) => a.localeCompare(b))) {
1251
+ const abs = resolveInsideProject(meshDir, svc.path, { sourceFile: path.join(meshDir, "mesh.json"), configPath: `services.${name}.path`, stage });
1252
+ if (!fs.existsSync(abs) || !fs.statSync(abs).isDirectory()) throw new ConfigError({ sourceFile: path.join(meshDir, "mesh.json"), configPath: `services.${name}.path`, stage, composition: "mesh", value: svc.path, reason: "Mesh service directory does not exist" });
1253
+ const buildJsonPath = path.join(abs, "build.json"), build = getBuildJson(abs), effectiveBuild = resolveBuildStage(build, stage, buildJsonPath);
1254
+ out[name] = { name, path: svc.path, absolutePath: abs, buildJsonPath, effectiveBuild, meshEnv: { ...svc.env ?? {} }, dependencyBindings: { ...svc.dependencies ?? {} }, dependsOn: [...svc.dependsOn ?? []], publish: [...svc.publish ?? []] };
1255
+ }
1256
+ return out;
1257
+ }
1258
+
1259
+ // src/core/mesh/v2/substitution.ts
1260
+ function buildDependencyBindings(services, stage, meshJsonPath) {
1261
+ const out = [];
1262
+ for (const service of Object.values(services)) {
1263
+ for (const [logicalDependency, providerService] of Object.entries(service.dependencyBindings)) {
1264
+ if (!service.effectiveBuild.dependencies[logicalDependency]) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${service.name}.dependencies.${logicalDependency}`, stage, composition: "mesh", value: providerService, reason: `Unknown logical dependency slot on consumer ${service.name}` });
1265
+ if (!services[providerService]) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${service.name}.dependencies.${logicalDependency}`, stage, composition: "mesh", value: providerService, reason: "Dependency provider is not an effective top-level mesh service" });
1266
+ out.push({ consumerService: service.name, logicalDependency, providerService });
655
1267
  }
656
- console.log(
657
- pc22.bold(pc22.blue(`
658
- --- Validating Infrastructure for [${serviceName}] ---`))
659
- );
660
- checkInfra(serviceDir);
661
1268
  }
1269
+ return out;
662
1270
  }
663
- function checkMeshTester(mesh, meshDir = process.cwd(), options = {}) {
664
- if (!mesh.tester) {
665
- if (options.required) {
666
- throw new ScriptError(
667
- 'E2E tester not configured in mesh.json: Missing "tester" configuration.'
668
- );
1271
+ function bindingKey(consumer, dependency) {
1272
+ return `${consumer}::${dependency}`;
1273
+ }
1274
+ function bindingsMap(bindings) {
1275
+ return new Map(bindings.map((b) => [bindingKey(b.consumerService, b.logicalDependency), b.providerService]));
1276
+ }
1277
+
1278
+ // src/core/mesh/v2/publication.ts
1279
+ var APP = /^app\.endpoints\.([a-z][a-z0-9-]*)$/;
1280
+ var DEP = /^dependencies\.([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)$/;
1281
+ function resolveMeshPublication(services, bindings, stage, meshJsonPath) {
1282
+ const out = [];
1283
+ for (const svc of Object.values(services).sort((a, b) => a.name.localeCompare(b.name))) for (const raw of svc.publish) {
1284
+ let m;
1285
+ if (m = APP.exec(raw)) {
1286
+ const ep = m[1], endpoint = svc.effectiveBuild.app.endpoints[ep];
1287
+ if (!endpoint) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${svc.name}.publish`, stage, composition: "mesh", value: raw, reason: "Published app endpoint does not exist" });
1288
+ if (endpoint.publicPort === void 0) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${svc.name}.publish`, stage, composition: "mesh", value: raw, reason: "Published endpoint requires publicPort in build.json" });
1289
+ out.push({ logicalPath: `${svc.name}.app.endpoints.${ep}`, ownerMeshService: svc.name, target: "app", endpoint: ep });
1290
+ continue;
669
1291
  }
670
- return;
671
- }
672
- const absMeshDir = resolveProjectDir(meshDir);
673
- const testerConfig = mesh.tester;
674
- if (!testerConfig.path || typeof testerConfig.path !== "string") {
675
- throw new ScriptError(
676
- 'Invalid tester configuration in mesh.json: Missing or invalid "path".'
677
- );
1292
+ if (m = DEP.exec(raw)) {
1293
+ const dependency = m[1], endpoint = m[2], dep = svc.effectiveBuild.dependencies[dependency];
1294
+ if (!dep || !dep.endpoints[endpoint]) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${svc.name}.publish`, stage, composition: "mesh", value: raw, reason: "Published dependency endpoint does not exist" });
1295
+ if (!Object.keys(dep.endpoints).length) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${svc.name}.publish`, stage, composition: "mesh", value: raw, reason: "Dependency endpoint is inert" });
1296
+ if (bindings.has(bindingKey(svc.name, dependency))) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${svc.name}.publish`, stage, composition: "mesh", value: raw, referencedObject: `${bindings.get(bindingKey(svc.name, dependency))}.publish -> app.endpoints.${endpoint}`, reason: "A substituted dependency endpoint cannot be published by its consumer; publish the provider app endpoint instead" });
1297
+ if (dep.endpoints[endpoint].publicPort === void 0) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${svc.name}.publish`, stage, composition: "mesh", value: raw, reason: "Published dependency endpoint requires publicPort in build.json" });
1298
+ out.push({ logicalPath: `${svc.name}.dependencies.${dependency}.endpoints.${endpoint}`, ownerMeshService: svc.name, target: "dependency", dependency, endpoint });
1299
+ continue;
1300
+ }
1301
+ throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${svc.name}.publish`, stage, composition: "mesh", value: raw, reason: "Invalid publish target; expected app.endpoints.<name> or dependencies.<name>.endpoints.<name>" });
678
1302
  }
679
- const absTesterDir = path13.resolve(absMeshDir, testerConfig.path);
680
- if (!isPathInside(absMeshDir, absTesterDir)) {
681
- throw new ScriptError(
682
- `Security error: Tester directory path "${testerConfig.path}" escapes the mesh project directory.`
683
- );
1303
+ return out;
1304
+ }
1305
+
1306
+ // src/core/mesh/v2/meshReferences.ts
1307
+ function resolveMesh(ref, ctx, source) {
1308
+ const name = ref.meshService;
1309
+ if (!ctx.services[name]) throw new ConfigError({ sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage, composition: "mesh", referencedObject: ref.raw, reason: `Unknown mesh service reference "${name}"` });
1310
+ const provider = ref.target === "dependency" ? ctx.bindings.get(bindingKey(name, ref.dependency)) : void 0;
1311
+ const ep = ref.target === "app" ? ctx.endpoints.app[name]?.[ref.endpoint] : provider ? ctx.endpoints.app[provider]?.[ref.endpoint] : ctx.endpoints.dependencies[name]?.[ref.dependency]?.[ref.endpoint];
1312
+ if (!ep) throw new ConfigError({ sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage, composition: "mesh", referencedObject: ref.raw, reason: "Referenced endpoint does not exist" });
1313
+ return resolveEndpointProperty(ep, ref.property, { sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage });
1314
+ }
1315
+ function resolveBuild(ref, consumer, ctx, source) {
1316
+ const provider = ref.target === "dependency" ? ctx.bindings.get(bindingKey(consumer, ref.dependency)) : void 0;
1317
+ const ep = ref.target === "app" ? ctx.endpoints.app[consumer]?.[ref.endpoint] : provider ? ctx.endpoints.app[provider]?.[ref.endpoint] : ctx.endpoints.dependencies[consumer]?.[ref.dependency]?.[ref.endpoint];
1318
+ if (!ep) throw new ConfigError({ sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage, composition: "mesh", referencedObject: ref.raw, reason: provider ? `Provider "${provider}" does not expose endpoint "${ref.endpoint}"` : "Referenced endpoint does not exist" });
1319
+ try {
1320
+ return resolveEndpointProperty(ep, ref.property, { sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage });
1321
+ } catch (error) {
1322
+ if (provider && error instanceof ConfigError) throw new ConfigError({ sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage, composition: "mesh", referencedObject: `${consumer}.dependencies.${ref.dependency}.endpoints.${ref.endpoint}.${ref.property} -> ${provider}.app.endpoints.${ref.endpoint}.${ref.property}`, reason: error.message });
1323
+ throw error;
684
1324
  }
685
- if (!existsSync(absTesterDir)) {
686
- throw new ScriptError(
687
- `E2E tester directory does not exist: ${absTesterDir} (declared path: "${testerConfig.path}")`
688
- );
1325
+ }
1326
+ function interpolate(value, scope, resolve, source) {
1327
+ const sentinel = "\0DOLLAR\0";
1328
+ return value.replace(/\$\$/g, sentinel).replace(/\$\{([^}]*)\}/g, (_whole, body) => {
1329
+ const ref = collectBuilderReferences(`\${${body}}`, scope, source)[0];
1330
+ return resolve(ref);
1331
+ }).replaceAll(sentinel, "$").replace(/\$/g, "$$$$");
1332
+ }
1333
+ function resolveMeshEnvMap(env, ctx, sourcePrefix) {
1334
+ return Object.fromEntries(Object.entries(env).map(([key, value]) => [key, interpolate(value, "mesh", (ref) => resolveMesh(ref, ctx, `${sourcePrefix}.${key}`), `${sourcePrefix}.${key}`)]));
1335
+ }
1336
+ function resolveServiceBuildEnvThroughMesh(consumer, env, ctx, sourcePrefix) {
1337
+ return Object.fromEntries(Object.entries(env).map(([key, value]) => [key, interpolate(value, "build", (ref) => resolveBuild(ref, consumer, ctx, `${sourcePrefix}.${key}`), `${sourcePrefix}.${key}`)]));
1338
+ }
1339
+ function assertMeshTesterEnvPublic(env, source) {
1340
+ assertTesterReferencesArePublic(env, "mesh", source);
1341
+ }
1342
+
1343
+ // src/core/mesh/v2/lifecycle.ts
1344
+ function buildMeshLifecycleEdges(services, bindings, stage, meshJsonPath) {
1345
+ const result = [];
1346
+ const seen = /* @__PURE__ */ new Set();
1347
+ for (const svc of Object.values(services)) for (const provider of [...svc.dependsOn, ...Object.entries(svc.dependencyBindings).map(([dep]) => bindings.get(bindingKey(svc.name, dep))).filter(Boolean)]) {
1348
+ if (provider === svc.name) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${svc.name}.dependsOn`, stage, composition: "mesh", referencedObject: provider, reason: "Mesh service cannot depend on itself" });
1349
+ const source = svc.dependsOn.includes(provider) ? "dependsOn" : "dependency-binding";
1350
+ const id = `${svc.name}\0${provider}`;
1351
+ if (!seen.has(id)) {
1352
+ seen.add(id);
1353
+ result.push({ consumer: svc.name, provider, source });
1354
+ }
689
1355
  }
690
- console.log(
691
- pc22.bold(pc22.cyan(`
692
- \u{1F50D} Checking E2E Tester (${testerConfig.path})...`))
693
- );
694
- const composeRel = testerConfig.compose || "docker-compose.yml";
695
- const composePath = path13.resolve(absTesterDir, composeRel);
696
- if (!existsSync(composePath)) {
697
- throw new ScriptError(
698
- `E2E tester docker compose file not found at: ${composePath}`
699
- );
1356
+ const graph = new Map(Object.keys(services).map((name) => [name, /* @__PURE__ */ new Set()]));
1357
+ for (const edge of result) graph.get(edge.consumer).add(edge.provider);
1358
+ assertAcyclicGraph(graph, { sourceFile: meshJsonPath, stage, composition: "mesh" });
1359
+ return result;
1360
+ }
1361
+ function applyMeshLifecycleEdges(services, edges) {
1362
+ for (const edge of edges) {
1363
+ const consumer = services[edge.consumer];
1364
+ const old = consumer.depends_on && typeof consumer.depends_on === "object" && !Array.isArray(consumer.depends_on) ? consumer.depends_on : {};
1365
+ old[edge.provider] = { condition: "service_healthy" };
1366
+ consumer.depends_on = old;
700
1367
  }
701
- try {
702
- const composeContent = readFileSync(composePath, "utf-8");
703
- const docs = parseAllDocuments(composeContent);
704
- const docErrors = docs.flatMap((doc) => doc.errors);
705
- if (docErrors.length > 0) {
706
- throw new Error(docErrors.map((e) => e.message).join("\n"));
1368
+ }
1369
+
1370
+ // src/core/mesh/v2/compileMeshTester.ts
1371
+ function refs(svc) {
1372
+ const out = [];
1373
+ const add = (v) => {
1374
+ if (typeof v === "string") out.push(v);
1375
+ };
1376
+ if (Array.isArray(svc.depends_on)) svc.depends_on.forEach(add);
1377
+ else if (svc.depends_on && typeof svc.depends_on === "object") Object.keys(svc.depends_on).forEach(add);
1378
+ if (Array.isArray(svc.links)) svc.links.forEach((v) => add(typeof v === "string" ? v.split(":")[0] : v));
1379
+ if (Array.isArray(svc.volumes_from)) svc.volumes_from.forEach((v) => add(typeof v === "string" ? v.split(":")[0] : v));
1380
+ if (typeof svc.network_mode === "string" && svc.network_mode.startsWith("service:")) out.push(svc.network_mode.slice(8));
1381
+ return out;
1382
+ }
1383
+ function referencedResources(svc, doc) {
1384
+ const sets = { volumes: /* @__PURE__ */ new Set(), networks: /* @__PURE__ */ new Set(), configs: /* @__PURE__ */ new Set(), secrets: /* @__PURE__ */ new Set() };
1385
+ for (const v of Array.isArray(svc.volumes) ? svc.volumes : []) {
1386
+ if (typeof v === "string") {
1387
+ const source = v.split(":")[0];
1388
+ if (doc.volumes?.[source]) sets.volumes.add(source);
1389
+ } else if (v && typeof v === "object" && v.type === "volume" && doc.volumes?.[v.source]) sets.volumes.add(v.source);
1390
+ }
1391
+ const nets = svc.networks;
1392
+ if (Array.isArray(nets)) nets.forEach((n) => {
1393
+ if (typeof n === "string" && doc.networks?.[n]) sets.networks.add(n);
1394
+ });
1395
+ else if (nets && typeof nets === "object") Object.keys(nets).forEach((n) => {
1396
+ if (doc.networks?.[n]) sets.networks.add(n);
1397
+ });
1398
+ for (const kind of ["configs", "secrets"]) {
1399
+ const v = svc[kind];
1400
+ if (Array.isArray(v)) for (const x of v) {
1401
+ const n = typeof x === "string" ? x : x?.source;
1402
+ if (typeof n === "string" && doc[kind]?.[n]) sets[kind].add(n);
1403
+ }
1404
+ }
1405
+ return sets;
1406
+ }
1407
+ function compileMeshTester(meshDir, tester, endpointRegistry, effectiveTopLevelApps, stage, referenceContext) {
1408
+ const meshPath = `${meshDir}/mesh.json`, file = resolveInsideProject(meshDir, tester.compose, { sourceFile: meshPath, configPath: "tester.compose", stage }), raw = rebaseComposePaths(loadComposeDocument(file, { sourceFile: meshPath, configPath: "tester.compose", stage, composition: "mesh" }), file, meshDir);
1409
+ if (!raw.services || !raw.services[tester.service]) throw new ConfigError({ sourceFile: meshPath, configPath: "tester.service", stage, composition: "mesh", value: tester.service, reason: "Selected tester service does not exist in tester Compose" });
1410
+ const included = /* @__PURE__ */ new Set(), visit = (name) => {
1411
+ if (included.has(name)) return;
1412
+ if (!raw.services[name]) throw new ConfigError({ sourceFile: file, configPath: `services.${name}`, stage, composition: "mesh", reason: "Tester service dependency does not exist" });
1413
+ included.add(name);
1414
+ for (const ref of refs(raw.services[name])) visit(ref);
1415
+ };
1416
+ visit(tester.service);
1417
+ for (const name of included) {
1418
+ const svc = raw.services[name];
1419
+ if (name !== tester.service && svc.network_mode === "host") throw new ConfigError({ sourceFile: file, configPath: `services.${name}.network_mode`, stage, composition: "mesh", reason: "Only the selected tester runner may use host networking" });
1420
+ if (name === tester.service && svc.network_mode !== void 0 && svc.network_mode !== "host") throw new ConfigError({ sourceFile: file, configPath: `services.${name}.network_mode`, stage, composition: "mesh", reason: "Selected tester runner must be compatible with host networking" });
1421
+ if (name === tester.service && svc.networks !== void 0) throw new ConfigError({ sourceFile: file, configPath: `services.${name}.networks`, stage, composition: "mesh", reason: "Selected host-network tester runner cannot declare networks" });
1422
+ }
1423
+ const res = { volumes: /* @__PURE__ */ new Set(), networks: /* @__PURE__ */ new Set(), configs: /* @__PURE__ */ new Set(), secrets: /* @__PURE__ */ new Set() };
1424
+ for (const name of included) {
1425
+ const own = referencedResources(raw.services[name], raw);
1426
+ for (const k of Object.keys(res)) for (const v of own[k]) res[k].add(v);
1427
+ }
1428
+ const selected = { services: Object.fromEntries([...included].map((k) => [k, raw.services[k]])) };
1429
+ for (const k of Object.keys(res)) if (res[k].size) selected[k] = Object.fromEntries([...res[k]].map((n) => [n, raw[k]?.[n]]));
1430
+ const ns = namespaceDependencyCompose({ namespacePrefix: "mesh-tester", document: selected });
1431
+ const runner = ns.serviceNameMap.get(tester.service);
1432
+ const runnerSvc = ns.document.services[runner];
1433
+ if (runnerSvc.ports !== void 0) throw new ConfigError({ sourceFile: file, configPath: `services.${tester.service}.ports`, stage, composition: "mesh", reason: "Selected host-network tester runner cannot define ports" });
1434
+ runnerSvc.network_mode = "host";
1435
+ delete runnerSvc.networks;
1436
+ const meshCtx = referenceContext ?? { services: {}, bindings: /* @__PURE__ */ new Map(), endpoints: endpointRegistry, stage, meshJsonPath: meshPath };
1437
+ const env = tester.env ?? {};
1438
+ assertMeshTesterEnvPublic(env, "tester.env");
1439
+ runnerSvc.environment = { ...normalizeComposeEnvironment(runnerSvc.environment, "tester runner environment"), ...resolveMeshEnvMap(env, meshCtx, "tester.env") };
1440
+ const depends = runnerSvc.depends_on && typeof runnerSvc.depends_on === "object" && !Array.isArray(runnerSvc.depends_on) ? runnerSvc.depends_on : {};
1441
+ for (const app of effectiveTopLevelApps) depends[app] = { condition: "service_healthy" };
1442
+ runnerSvc.depends_on = depends;
1443
+ return { services: ns.document.services, ...ns.document.volumes ? { volumes: ns.document.volumes } : {}, ...ns.document.networks ? { networks: ns.document.networks } : {}, ...ns.document.configs ? { configs: ns.document.configs } : {}, ...ns.document.secrets ? { secrets: ns.document.secrets } : {}, runnerServiceName: runner };
1444
+ }
1445
+ function assertUniqueHostPortMappings(yamlConfig) {
1446
+ const parsed = parse(yamlConfig);
1447
+ const owners = /* @__PURE__ */ new Map();
1448
+ for (const [serviceName, service] of Object.entries(parsed?.services ?? {})) {
1449
+ for (const port of service?.ports ?? []) {
1450
+ let hostPort = null;
1451
+ if (typeof port === "string") {
1452
+ const parts = port.split(":");
1453
+ if (parts.length === 2) hostPort = Number(parts[0]);
1454
+ if (parts.length === 3) hostPort = Number(parts[1]);
1455
+ } else if (port && typeof port === "object" && "published" in port) {
1456
+ hostPort = Number(port.published);
1457
+ }
1458
+ if (!hostPort || !Number.isInteger(hostPort)) continue;
1459
+ const existing = owners.get(hostPort);
1460
+ if (existing) {
1461
+ throw new ScriptError(
1462
+ `Port Collision Detected: Host port ${hostPort} is requested by both "${existing}" and "${serviceName}".`
1463
+ );
1464
+ }
1465
+ owners.set(hostPort, serviceName);
707
1466
  }
708
- } catch (err) {
709
- throw new ScriptError(
710
- `Invalid YAML syntax in tester docker compose (${composeRel}): ${errorMessage(err)}`
711
- );
712
1467
  }
713
- const dockerfileRel = testerConfig.dockerfile || "Dockerfile";
714
- const dockerfilePath = path13.resolve(absTesterDir, dockerfileRel);
715
- if (!existsSync(dockerfilePath)) {
716
- throw new ScriptError(
717
- `E2E tester Dockerfile not found at: ${dockerfilePath}`
718
- );
1468
+ }
1469
+
1470
+ // src/core/mesh/v2/compileMeshComposition.ts
1471
+ function mergeFragment(target, fragment, owner) {
1472
+ for (const key of ["services", "volumes", "networks", "configs", "secrets"]) {
1473
+ const incoming = fragment[key];
1474
+ if (!incoming) continue;
1475
+ const dest = target[key] ??= {};
1476
+ for (const [name, value] of Object.entries(incoming)) {
1477
+ if (name in dest) throw new ConfigError({ configPath: `${key}.${name}`, referencedObject: owner, reason: "Mesh composition name collision" });
1478
+ dest[name] = value;
1479
+ }
1480
+ }
1481
+ }
1482
+ function appendPort(service, target, published) {
1483
+ const ports = Array.isArray(service.ports) ? service.ports : [];
1484
+ ports.push({ target, published, host_ip: PUBLIC_HOST, protocol: "tcp" });
1485
+ service.ports = ports;
1486
+ }
1487
+ function ownerFor(pub, fragment) {
1488
+ return pub.target === "app" ? pub.ownerMeshService : fragment.endpoints.dependencies[pub.dependency]?.[pub.endpoint]?.networkHost ?? "";
1489
+ }
1490
+ function setEnv(service, env) {
1491
+ const current = service.environment && typeof service.environment === "object" && !Array.isArray(service.environment) ? service.environment : {};
1492
+ service.environment = { ...current, ...env };
1493
+ }
1494
+ function compileMeshComposition(stage, meshDir, options = {}) {
1495
+ const meshPath = path.join(meshDir, "mesh.json"), raw = getMeshJson(meshDir), effective = resolveMeshStage(raw, stage, meshPath), services = loadEffectiveMeshServices(meshDir, effective, stage), bindings = buildDependencyBindings(services, stage, meshPath), bindingMap = bindingsMap(bindings);
1496
+ const rawName = raw.name ?? path.basename(meshDir), projectName = deriveProjectName(rawName, stage, meshDir);
1497
+ const fragments = {};
1498
+ const compose = { name: projectName, services: {}, networks: { mesh: { driver: "bridge" } } };
1499
+ for (const [name, svc] of Object.entries(services).sort(([a], [b]) => a.localeCompare(b))) {
1500
+ for (const key of ["EXEC_MODE", "INFRA_MODE", ...Object.keys(svc.effectiveBuild.app.endpoints).some((ep) => svc.effectiveBuild.app.endpoints[ep]?.primary) ? ["PORT"] : []]) if (key in svc.meshEnv) throw new ConfigError({ sourceFile: meshPath, configPath: `services.${name}.env.${key}`, stage, composition: "mesh", reason: "Mesh service env cannot set Builder-owned environment" });
1501
+ const suppress = new Set(Object.keys(svc.dependencyBindings));
1502
+ const fragment = compileServiceComposition(stage, svc.absolutePath, { full: true, meshMode: true, projectNameOverride: projectName, namespacePrefix: `svc--${name}--dep--`, suppressDependencies: suppress, externalAppEnv: svc.meshEnv, deferReferenceResolution: true, appServiceName: name, composeOutputDir: meshDir, validationMode: options.validationMode });
1503
+ fragments[name] = fragment;
1504
+ mergeFragment(compose, fragment.compose, name);
1505
+ const app = compose.services[name];
1506
+ const networks = { mesh: null };
1507
+ const localDeps = Object.keys(fragment.endpoints.dependencies).filter((dep) => !bindingMap.has(bindingKey(name, dep)) && Object.keys(fragment.effectiveBuild.dependencies[dep]?.endpoints ?? {}).length > 0);
1508
+ if (localDeps.length) {
1509
+ const privateName = `mesh--${name}`;
1510
+ networks[privateName] = null;
1511
+ compose.networks[privateName] = { driver: "bridge" };
1512
+ for (const dep of localDeps) {
1513
+ for (const ep of Object.values(fragment.endpoints.dependencies[dep] ?? {})) {
1514
+ const owner = ep.networkHost;
1515
+ const ownerService = compose.services[owner];
1516
+ if (ownerService) {
1517
+ const old = normalizeNetworks(ownerService.networks);
1518
+ old[privateName] = null;
1519
+ ownerService.networks = old;
1520
+ }
1521
+ }
1522
+ for (const generated of Object.keys(fragment.compose.services).filter((k) => k.startsWith(`svc--${name}--dep--${dep}--`))) {
1523
+ const ownerService = compose.services[generated];
1524
+ const old = normalizeNetworks(ownerService.networks);
1525
+ old[privateName] = null;
1526
+ ownerService.networks = old;
1527
+ }
1528
+ }
1529
+ }
1530
+ app.networks = { ...normalizeNetworks(app.networks), ...networks };
1531
+ }
1532
+ const publication = resolveMeshPublication(services, bindingMap, stage, meshPath), intents = [];
1533
+ for (const name of Object.keys(services).sort()) for (const pub of publication.filter((p) => p.ownerMeshService === name && p.target === "app").sort((a, b) => a.endpoint.localeCompare(b.endpoint))) {
1534
+ const ep = services[name].effectiveBuild.app.endpoints[pub.endpoint];
1535
+ intents.push({ logicalPath: pub.logicalPath, requested: ep.publicPort });
1536
+ }
1537
+ for (const name of Object.keys(services).sort()) for (const pub of publication.filter((p) => p.ownerMeshService === name && p.target === "dependency").sort((a, b) => `${a.dependency}.${a.endpoint}`.localeCompare(`${b.dependency}.${b.endpoint}`))) {
1538
+ const ep = services[name].effectiveBuild.dependencies[pub.dependency].endpoints[pub.endpoint];
1539
+ intents.push({ logicalPath: pub.logicalPath, requested: ep.publicPort });
1540
+ }
1541
+ const ports = allocateHostPorts(meshDir, stage, intents, Boolean(options.validationMode));
1542
+ const endpoints = { app: {}, dependencies: {} };
1543
+ for (const [name, svc] of Object.entries(services)) {
1544
+ endpoints.app[name] = {};
1545
+ for (const [epName, ep] of Object.entries(svc.effectiveBuild.app.endpoints)) {
1546
+ const host = name;
1547
+ const record = { logicalPath: `${name}.app.endpoints.${epName}`, networkHost: host, networkPort: ep.port, ...ep.scheme ? { scheme: ep.scheme } : {}, effectivelyPublished: false };
1548
+ endpoints.app[name][epName] = record;
1549
+ }
1550
+ endpoints.dependencies[name] = {};
1551
+ const fragment = fragments[name];
1552
+ for (const [depName, dep] of Object.entries(svc.effectiveBuild.dependencies)) {
1553
+ if (bindingMap.has(bindingKey(name, depName))) continue;
1554
+ endpoints.dependencies[name][depName] = {};
1555
+ for (const [epName, def] of Object.entries(dep.endpoints)) {
1556
+ const local = fragment.endpoints.dependencies[depName]?.[epName];
1557
+ if (!local) continue;
1558
+ endpoints.dependencies[name][depName][epName] = { ...local, logicalPath: `${name}.dependencies.${depName}.endpoints.${epName}`, effectivelyPublished: false };
1559
+ }
1560
+ }
1561
+ }
1562
+ for (const pub of publication) {
1563
+ const ep = pub.target === "app" ? endpoints.app[pub.ownerMeshService]?.[pub.endpoint] : endpoints.dependencies[pub.ownerMeshService]?.[pub.dependency]?.[pub.endpoint];
1564
+ if (!ep) continue;
1565
+ ep.publicHost = PUBLIC_HOST;
1566
+ ep.publicPort = ports.get(pub.logicalPath);
1567
+ ep.effectivelyPublished = true;
1568
+ }
1569
+ for (const pub of publication) {
1570
+ const fragment = fragments[pub.ownerMeshService], endpoint = pub.target === "app" ? endpoints.app[pub.ownerMeshService][pub.endpoint] : endpoints.dependencies[pub.ownerMeshService][pub.dependency][pub.endpoint];
1571
+ const owner = ownerFor(pub, fragment);
1572
+ const service = compose.services[owner];
1573
+ if (service && endpoint) appendPort(service, endpoint.networkPort, endpoint.publicPort);
1574
+ }
1575
+ const refContext = { services, bindings: bindingMap, endpoints, stage, meshJsonPath: meshPath };
1576
+ for (const [name, fragment] of Object.entries(fragments)) {
1577
+ const app = compose.services[name];
1578
+ const buildEnv = resolveServiceBuildEnvThroughMesh(name, fragment.buildAppEnvironment ?? fragment.builderAppEnvironment ?? {}, refContext, `services.${name}.app.env`);
1579
+ const meshEnv = resolveMeshEnvMap(fragment.externalAppEnvironment ?? {}, refContext, `services.${name}.env`);
1580
+ setEnv(app, { ...buildEnv, ...meshEnv });
1581
+ for (const [depName, depEnv] of Object.entries(fragment.dependencyEnvironments ?? {})) {
1582
+ const logicalBinding = bindingMap.get(bindingKey(name, depName));
1583
+ if (logicalBinding) continue;
1584
+ const resolvedDep = resolveServiceBuildEnvThroughMesh(name, depEnv, refContext, `services.${name}.dependencies.${depName}.env`);
1585
+ const prefix = `svc--${name}--dep--${depName}--`;
1586
+ for (const [serviceName, service] of Object.entries(compose.services)) if (serviceName.startsWith(prefix)) setEnv(service, resolvedDep);
1587
+ }
1588
+ }
1589
+ const edges = buildMeshLifecycleEdges(services, bindingMap, stage, meshPath);
1590
+ applyMeshLifecycleEdges(compose.services, edges);
1591
+ for (const [name, svc] of Object.entries(services)) for (const [sourceDep, dep] of Object.entries(svc.effectiveBuild.dependencies)) {
1592
+ if (bindingMap.has(bindingKey(name, sourceDep))) continue;
1593
+ for (const rawTarget of dep.dependsOn) {
1594
+ const targetKey = rawTarget.slice("dependencies.".length);
1595
+ const provider = bindingMap.get(bindingKey(name, targetKey));
1596
+ if (!provider) continue;
1597
+ const localEndpoints = endpoints.dependencies[name]?.[sourceDep] ?? {};
1598
+ for (const ep of Object.values(localEndpoints)) {
1599
+ const localOwner = ep.networkHost, localSvc = compose.services[localOwner];
1600
+ if (!localSvc) continue;
1601
+ const ds = localSvc.depends_on && typeof localSvc.depends_on === "object" && !Array.isArray(localSvc.depends_on) ? localSvc.depends_on : {};
1602
+ ds[provider] = { condition: "service_healthy" };
1603
+ localSvc.depends_on = ds;
1604
+ const net2 = localSvc.networks && typeof localSvc.networks === "object" && !Array.isArray(localSvc.networks) ? localSvc.networks : {};
1605
+ net2.mesh = null;
1606
+ localSvc.networks = net2;
1607
+ }
1608
+ }
1609
+ }
1610
+ const fullGraph = new Map(Object.keys(compose.services).map((name) => [name, /* @__PURE__ */ new Set()]));
1611
+ for (const [serviceName, service] of Object.entries(compose.services)) {
1612
+ const dependencies = service.depends_on;
1613
+ if (dependencies && typeof dependencies === "object" && !Array.isArray(dependencies)) for (const target of Object.keys(dependencies)) {
1614
+ if (fullGraph.has(target)) fullGraph.get(serviceName).add(target);
1615
+ }
1616
+ }
1617
+ assertAcyclicGraph(fullGraph, { sourceFile: meshPath, stage, composition: "mesh" });
1618
+ let testerServiceName;
1619
+ if (stage === "e2e") {
1620
+ if (!raw.tester && !options.allowMissingTester) throw new ConfigError({ sourceFile: meshPath, configPath: "tester", stage, composition: "mesh", reason: "Global mesh E2E requires root mesh.json.tester { compose, service, env? }" });
1621
+ const built = raw.tester ? compileMeshTester(meshDir, raw.tester, endpoints, Object.keys(services).sort(), "e2e", refContext) : void 0;
1622
+ if (built) {
1623
+ const fragment = { services: built.services, ...built.volumes ? { volumes: built.volumes } : {}, ...built.networks ? { networks: built.networks } : {}, ...built.configs ? { configs: built.configs } : {}, ...built.secrets ? { secrets: built.secrets } : {} };
1624
+ mergeFragment(compose, fragment, "mesh tester");
1625
+ testerServiceName = built.runnerServiceName;
1626
+ }
719
1627
  }
720
- const dockerfileContent = readFileSync(dockerfilePath, "utf-8");
721
- console.log(pc22.cyan(`
722
- \u{1F50D} Linting E2E Tester Dockerfile (${dockerfileRel})...`));
723
- runStep(
724
- "docker",
725
- ["run", "--rm", "-i", "--network", "none", HADOLINT_IMAGE, "hadolint", "--failure-threshold", "error", "-"],
726
- absTesterDir,
727
- {
728
- stepName: "E2E Tester Dockerfile Linting",
729
- targetFile: dockerfileRel,
730
- input: dockerfileContent
1628
+ const yaml = stringify(compose);
1629
+ assertUniqueHostPortMappings(yaml);
1630
+ return { compose, effectiveMesh: effective, loadedServices: services, endpoints, projectName, ...testerServiceName ? { testerServiceName } : {} };
1631
+ }
1632
+
1633
+ // src/core/mesh/checkers/checkMeshServices.ts
1634
+ function checkMeshServices(mesh, meshDir) {
1635
+ const root = resolveProjectDir(meshDir), meshPath = path.join(root, "mesh.json");
1636
+ const checked = /* @__PURE__ */ new Set();
1637
+ for (const stage of ["dev", "prod", "test", "e2e"]) {
1638
+ const effective = resolveMeshStage(mesh, stage, meshPath);
1639
+ const services = loadEffectiveMeshServices(root, effective, stage);
1640
+ for (const [name, svc] of Object.entries(services)) {
1641
+ if (!checked.has(svc.absolutePath)) {
1642
+ console.log(pc22.cyan(`
1643
+ \u{1F50D} Checking mesh service ${name}...`));
1644
+ checkInfra(svc.absolutePath);
1645
+ checked.add(svc.absolutePath);
1646
+ }
1647
+ if (stage === "test") {
1648
+ const fragment = compileServiceComposition("test", svc.absolutePath, { validationMode: true, meshMode: true, deferReferenceResolution: true });
1649
+ const endpoints = { app: { [name]: fragment.endpoints.app }, dependencies: { [name]: fragment.endpoints.dependencies } };
1650
+ const ctx = { services: { [name]: svc }, bindings: /* @__PURE__ */ new Map(), endpoints, stage: "test", meshJsonPath: meshPath };
1651
+ for (const key of ["EXEC_MODE", "INFRA_MODE", ...Object.values(svc.effectiveBuild.app.endpoints).some((ep) => ep.primary) ? ["PORT"] : []]) {
1652
+ if (key in svc.meshEnv) throw new ConfigError({ sourceFile: meshPath, configPath: `services.${name}.env.${key}`, stage: "test", composition: "mesh", reason: "Mesh service env cannot set Builder-owned environment" });
1653
+ }
1654
+ resolveServiceBuildEnvThroughMesh(name, fragment.builderAppEnvironment ?? {}, ctx, `services.${name}.app.env`);
1655
+ for (const [depName, depEnv] of Object.entries(fragment.dependencyEnvironments ?? {})) resolveServiceBuildEnvThroughMesh(name, depEnv, ctx, `services.${name}.dependencies.${depName}.env`);
1656
+ resolveMeshEnvMap(svc.meshEnv, ctx, `services.${name}.env`);
1657
+ }
731
1658
  }
732
- );
733
- const dockerfilePolicyRel = testerConfig.policy?.dockerfile || "policy/dockerfile";
734
- const dockerfilePolicyDir = path13.resolve(absTesterDir, dockerfilePolicyRel);
735
- if (existsSync(dockerfilePolicyDir)) {
736
- console.log(
737
- pc22.cyan(
738
- `
739
- \u{1F50D} Validating Tester Dockerfile Contract (${dockerfilePolicyRel})...`
740
- )
741
- );
742
- runStep(
743
- "docker",
744
- [
745
- "run",
746
- "--rm",
747
- "--network",
748
- "none",
749
- "--mount",
750
- `type=bind,src=${absTesterDir},dst=/project,readonly`,
751
- "-w",
752
- "/project",
753
- CONFTEST_IMAGE,
754
- "test",
755
- dockerfileRel,
756
- "-p",
757
- `${dockerfilePolicyRel}/`
758
- ],
759
- absTesterDir,
760
- { stepName: "E2E Tester Dockerfile Contract", targetFile: dockerfileRel }
761
- );
1659
+ if (stage !== "test") compileMeshComposition(stage, root, { validationMode: true, allowMissingTester: true });
762
1660
  }
763
- const composePolicyRel = testerConfig.policy?.compose || "policy/compose";
764
- const composePolicyDir = path13.resolve(absTesterDir, composePolicyRel);
765
- if (existsSync(composePolicyDir)) {
766
- console.log(
767
- pc22.cyan(`
768
- \u{1F50D} Validating Tester Compose Contract (${composePolicyRel})...`)
769
- );
770
- runStep(
771
- "docker",
772
- [
773
- "run",
774
- "--rm",
775
- "--network",
776
- "none",
777
- "--mount",
778
- `type=bind,src=${absTesterDir},dst=/project,readonly`,
779
- "-w",
780
- "/project",
781
- CONFTEST_IMAGE,
782
- "test",
783
- composeRel,
784
- "-p",
785
- `${composePolicyRel}/`,
786
- "--all-namespaces"
787
- ],
788
- absTesterDir,
789
- { stepName: "E2E Tester Compose Contract", targetFile: composeRel }
790
- );
1661
+ }
1662
+ function checkMeshTester(mesh, meshDir, options = {}) {
1663
+ const root = resolveProjectDir(meshDir);
1664
+ if (!mesh.tester) {
1665
+ if (options.required) throw new ConfigError({ sourceFile: path.join(root, "mesh.json"), configPath: "tester", stage: "e2e", composition: "mesh", reason: "Global mesh E2E requires root tester" });
1666
+ return;
791
1667
  }
792
- console.log(pc22.green(`\u2705 E2E tester configuration and contracts verified.
793
- `));
1668
+ const file = resolveInsideProject(root, mesh.tester.compose, { sourceFile: path.join(root, "mesh.json"), configPath: "tester.compose", stage: "e2e" });
1669
+ loadComposeDocument(file, { sourceFile: path.join(root, "mesh.json"), configPath: "tester.compose", stage: "e2e", composition: "mesh" });
1670
+ compileMeshComposition("e2e", root, { validationMode: true });
794
1671
  }
795
1672
 
796
1673
  // src/core/mesh/checkers/checkMesh.ts
@@ -801,7 +1678,7 @@ function checkMesh(meshDir = process.cwd(), options = {}) {
801
1678
  checkMeshTester(mesh, absMeshDir, { required: Boolean(options.requireTester) });
802
1679
  console.log(
803
1680
  pc22.bold(
804
- pc22.green("\n\u{1F389} All mesh infrastructure, services, and contract checks passed!\n")
1681
+ pc22.green("\n\u{1F389} All V2 mesh infrastructure, services, and contract checks passed!\n")
805
1682
  )
806
1683
  );
807
1684
  }
@@ -840,1036 +1717,74 @@ Examples:
840
1717
  }
841
1718
  });
842
1719
  };
843
- function assertUniqueHostPortMappings(yamlConfig) {
844
- const parsed = parse(yamlConfig);
845
- const owners = /* @__PURE__ */ new Map();
846
- for (const [serviceName, service] of Object.entries(parsed?.services ?? {})) {
847
- for (const port of service?.ports ?? []) {
848
- let hostPort = null;
849
- if (typeof port === "string") {
850
- const parts = port.split(":");
851
- if (parts.length === 2) hostPort = Number(parts[0]);
852
- if (parts.length === 3) hostPort = Number(parts[1]);
853
- } else if (port && typeof port === "object" && "published" in port) {
854
- hostPort = Number(port.published);
855
- }
856
- if (!hostPort || !Number.isInteger(hostPort)) continue;
857
- const existing = owners.get(hostPort);
858
- if (existing) {
859
- throw new ScriptError(
860
- `Port Collision Detected: Host port ${hostPort} is requested by both "${existing}" and "${serviceName}".`
861
- );
862
- }
863
- owners.set(hostPort, serviceName);
864
- }
865
- }
866
- }
867
-
868
- // src/utils/dependencyPorts.ts
869
- var EXPLICIT_PORT_MAPPING = /^([1-9]\d{0,4}):([1-9]\d{0,4})$/;
870
- function assertValidPort(port, label) {
871
- if (!Number.isInteger(port) || port < 1 || port > 65535) {
872
- throw new ScriptError(`${label} must be between 1 and 65535.`);
873
- }
874
- }
875
- function parseExplicitPortMapping(value, context = "Dependency port") {
876
- const match = EXPLICIT_PORT_MAPPING.exec(value.trim());
877
- if (!match) {
878
- throw new ScriptError(`${context} "${value}" must use "HOST_PORT:CONTAINER_PORT".`);
879
- }
880
- const hostPort = Number(match[1]);
881
- const containerPort = Number(match[2]);
882
- assertValidPort(hostPort, `${context} host port`);
883
- assertValidPort(containerPort, `${context} container port`);
884
- return { raw: `${hostPort}:${containerPort}`, hostPort, containerPort };
885
- }
886
- function normalizePrimaryDependencyPort(value, context = "Dependency port") {
887
- if (typeof value === "number") {
888
- assertValidPort(value, `${context} host port`);
889
- return { raw: `${value}:3000`, hostPort: value, containerPort: 3e3 };
1720
+ function compileMeshEnvironment(stage, rawMeshDir = process.cwd(), options = {}) {
1721
+ const meshDir = resolveProjectDir(rawMeshDir), compiled = compileMeshComposition(stage, meshDir), yaml = stringify(compiled.compose);
1722
+ if (options.validateWithDocker !== false) {
1723
+ const result = spawnSync("docker", ["compose", "--project-directory", meshDir, "-f", "-", "config", "--quiet"], { cwd: meshDir, encoding: "utf-8", input: yaml });
1724
+ if (result.error || result.status !== 0) throw new ScriptError(`Generated mesh Compose configuration is invalid: ${result.error?.message ?? result.stderr ?? result.stdout}`, { cause: result.error });
890
1725
  }
891
- const trimmed = value.trim();
892
- if (/^[1-9]\d{0,4}$/.test(trimmed)) {
893
- const hostPort = Number(trimmed);
894
- assertValidPort(hostPort, `${context} host port`);
895
- return { raw: `${hostPort}:3000`, hostPort, containerPort: 3e3 };
896
- }
897
- return parseExplicitPortMapping(trimmed, context);
898
- }
899
- function getDependencyPortMappings(dependency, context = "Dependency") {
900
- const mappings = [];
901
- if (dependency.port !== void 0) {
902
- mappings.push(normalizePrimaryDependencyPort(dependency.port, `${context} primary port`));
903
- }
904
- for (const value of dependency.ports ?? []) {
905
- mappings.push(parseExplicitPortMapping(value, `${context} auxiliary port`));
906
- }
907
- return [...new Map(mappings.map((mapping) => [mapping.raw, mapping])).values()];
1726
+ return { yaml, ...compiled.testerServiceName ? { testerServiceName: compiled.testerServiceName } : {} };
908
1727
  }
909
- var buildPolicyConfigSchema = z.object({
910
- dockerfile: z.string().optional().describe("Relative path to policy directory for Dockerfile checks"),
911
- compose: z.string().optional().describe("Relative path to policy directory for Compose contract checks")
912
- }).strict().describe("Policy configurations for infra/contract verification");
913
- var auxiliaryPortMappingSchema = z.string().regex(/^([1-9]\d{0,4}):([1-9]\d{0,4})$/, 'Must use "HOST_PORT:CONTAINER_PORT"').refine((value) => value.split(":").every((part) => Number(part) <= 65535), {
914
- message: "Host and container ports must be between 1 and 65535"
915
- });
916
- var buildDependencySchema = z.object({
917
- path: z.string({ required_error: 'Dependency "path" is required' }).describe("Relative path to mock Docker Compose file"),
918
- service: z.string().optional().describe("Target service name in the mock compose file"),
919
- port: z.union([z.number(), z.string()]).optional().describe("Host port to map to this dependency locally"),
920
- ports: z.array(auxiliaryPortMappingSchema).optional().describe("Additional explicit HOST_PORT:CONTAINER_PORT mappings for local dependency tooling")
921
- }).strict().describe("Service dependency specification");
922
- var buildOverrideSchema = z.object({
923
- path: z.string({ required_error: 'Override "path" is required' }).describe("Relative path to the environment stage override file")
924
- }).strict().describe("Environment override specification");
925
- var buildTesterSchema = z.object({
926
- envOverrides: z.record(z.string(), z.string()).optional().describe(
927
- "Environment variable overrides for the individual E2E tester with URL templating"
928
- )
929
- }).strict().describe("E2E tester configuration");
930
- var buildJsonSchema = z.object({
931
- $schema: z.string().optional().describe("JSON Schema URL or relative path"),
932
- name: z.string().optional().describe("Service project name"),
933
- dockerfile: z.string().optional().describe("Relative path to the Dockerfile (defaults to 'Dockerfile')"),
934
- port: z.union([z.number(), z.string()]).optional().describe(
935
- "Host port exposed by this service when listening publicly"
936
- ),
937
- policy: buildPolicyConfigSchema.optional(),
938
- policies: buildPolicyConfigSchema.optional(),
939
- composeFiles: z.array(z.string()).optional().describe("Additional compose files to merge"),
940
- dependencies: z.record(z.string(), buildDependencySchema).optional().describe("Service dependencies and mocks"),
941
- envOverrides: z.record(z.string(), z.string()).optional().describe("Environment variable overrides for the app service with URL templating"),
942
- overrides: z.record(
943
- z.enum(["dev", "prod", "test", "e2e"]),
944
- buildOverrideSchema
945
- ).optional().describe("Stage overrides (dev, prod, test, e2e)"),
946
- services: z.record(z.string(), z.any()).optional().describe("Additional Docker Compose service overrides"),
947
- tester: buildTesterSchema.optional()
948
- }).strict().describe("Solid Stack service build and deployment configuration");
949
-
950
- // src/utils/extractBuildDeps.ts
951
- var extractBuildDeps = (buildJson, projectDir = process.cwd()) => {
952
- if (!buildJson || typeof buildJson !== "object") {
953
- return [];
954
- }
955
- if (!("dependencies" in buildJson) || !buildJson.dependencies) {
956
- return [];
957
- }
958
- const schema = z.object({
959
- dependencies: z.record(z.string(), buildDependencySchema)
960
- });
961
- const result = schema.safeParse(buildJson);
962
- if (!result.success) {
963
- const errorDetails = result.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ");
964
- throw new ScriptError(
965
- `Invalid build.json structure for dependencies: ${errorDetails}`
966
- );
967
- }
968
- const dependenciesData = result.data.dependencies;
969
- const dependencies = Object.entries(dependenciesData || {}).map(
970
- ([name, service]) => {
971
- return {
972
- path: path13.resolve(projectDir, service.path),
973
- name,
974
- serviceName: service.service,
975
- port: service.port,
976
- ports: service.ports
977
- };
978
- }
979
- );
980
- return dependencies;
981
- };
982
- var VALID_STAGES = ["dev", "prod", "test", "e2e"];
983
- var extractOverrides = (buildJson, projectDir = process.cwd()) => {
984
- if (!buildJson || typeof buildJson !== "object") {
985
- return {};
986
- }
987
- if (!("overrides" in buildJson) || !buildJson.overrides) {
988
- return {};
989
- }
990
- const schema = z.object({
991
- overrides: z.record(
992
- z.enum(VALID_STAGES, {
993
- errorMap: () => ({
994
- message: `Unknown stage override. Supported stages are: ${VALID_STAGES.join(", ")}`
995
- })
996
- }),
997
- z.object({
998
- path: z.string({ required_error: "Override 'path' is required" })
999
- })
1000
- )
1001
- });
1002
- const result = schema.safeParse(buildJson);
1003
- if (!result.success) {
1004
- const errorDetails = result.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ");
1005
- throw new ScriptError(
1006
- `Invalid build.json structure for overrides: ${errorDetails}`
1007
- );
1008
- }
1009
- const resolvedOverrides = {};
1010
- for (const [key, value] of Object.entries(result.data.overrides)) {
1011
- resolvedOverrides[key] = {
1012
- path: path13.resolve(projectDir, value.path)
1013
- };
1014
- }
1015
- return resolvedOverrides;
1728
+ var activeComposeSet = /* @__PURE__ */ new Set();
1729
+ var signalHandlersRegistered = false;
1730
+ var activeChildProcess = null;
1731
+ var isTearingDown = false;
1732
+ var isShuttingDown = false;
1733
+ var isProcessAlive = (c) => {
1734
+ return Boolean(c && c.exitCode === null && c.signalCode === null);
1016
1735
  };
1017
- function normalizeProjectName(name, projectDir) {
1018
- let normalized = name.toLowerCase().replace(/[^a-z0-9_-]/g, "-").replace(/^[-_]+/, "").replace(/[-_]+$/, "");
1019
- if (!normalized || !/^[a-z0-9]/.test(normalized)) {
1020
- return "project";
1736
+ function setActiveChild(child) {
1737
+ activeChildProcess = child;
1738
+ if (!child) {
1739
+ isShuttingDown = false;
1021
1740
  }
1022
- return normalized;
1023
1741
  }
1024
- function deriveProjectName(name, stage, projectDir, options = {}) {
1025
- let base = normalizeProjectName(name);
1026
- if (options.hash && projectDir) ;
1027
- if (!stage) {
1028
- return base;
1029
- }
1030
- const s = stage.toLowerCase();
1031
- if (s === "dev") {
1032
- return base;
1033
- }
1034
- if (s === "prod") {
1035
- return `${base}-prod`;
1036
- }
1037
- if (s === "test" || s === "test-unit") {
1038
- return `${base}-test`;
1039
- }
1040
- if (s === "e2e" || s === "test-e2e") {
1041
- return `${base}-e2e`;
1042
- }
1043
- return `${base}-${s}`;
1742
+ function setTearingDown(tearingDown) {
1743
+ isTearingDown = tearingDown;
1044
1744
  }
1045
-
1046
- // src/core/mesh/compileMeshEnvironment.ts
1047
- function compileMeshEnvironment(mode, rawMeshDir = process.cwd(), options = {}) {
1048
- const meshDir = resolveProjectDir(rawMeshDir);
1049
- const mesh = getMeshJson(meshDir);
1050
- const rawProjectName = mesh.name || path13.basename(meshDir);
1051
- const projectName = deriveProjectName(
1052
- rawProjectName,
1053
- options.includeTester ? "e2e" : mode
1054
- );
1055
- const composeConfig = {
1056
- name: projectName,
1057
- networks: {
1058
- mesh: {}
1059
- },
1060
- services: {}
1745
+ function registerActiveCompose(yamlConfig, projectDir, options = {}) {
1746
+ const entry = {
1747
+ yamlConfig,
1748
+ projectDir,
1749
+ removeVolumes: options.removeVolumes
1061
1750
  };
1062
- function mergeTopLevelResources(parsed) {
1063
- if (!parsed || typeof parsed !== "object") return;
1064
- for (const key of ["volumes", "secrets", "configs"]) {
1065
- if (parsed[key] && typeof parsed[key] === "object") {
1066
- composeConfig[key] = {
1067
- ...composeConfig[key] || {},
1068
- ...parsed[key]
1069
- };
1070
- }
1751
+ activeComposeSet.add(entry);
1752
+ ensureSignalHandlers();
1753
+ return () => {
1754
+ activeComposeSet.delete(entry);
1755
+ };
1756
+ }
1757
+ function ensureSignalHandlers() {
1758
+ if (signalHandlersRegistered) return;
1759
+ signalHandlersRegistered = true;
1760
+ const handleSignal = (signal) => {
1761
+ if (isTearingDown) {
1762
+ return;
1071
1763
  }
1072
- }
1073
- function rewriteServiceVolume(svc, oldKey, newKey) {
1074
- if (!svc || !Array.isArray(svc.volumes)) return;
1075
- svc.volumes = svc.volumes.map((vol) => {
1076
- if (typeof vol === "string") {
1077
- if (vol === oldKey) return newKey;
1078
- if (vol.startsWith(`${oldKey}:`)) {
1079
- return `${newKey}:${vol.slice(oldKey.length + 1)}`;
1764
+ if (activeChildProcess && isProcessAlive(activeChildProcess)) {
1765
+ const child = activeChildProcess;
1766
+ if (signal === "SIGINT") {
1767
+ if (!isShuttingDown) {
1768
+ isShuttingDown = true;
1769
+ setTimeout(() => {
1770
+ if (isProcessAlive(child)) {
1771
+ try {
1772
+ child.kill("SIGKILL");
1773
+ } catch {
1774
+ }
1775
+ }
1776
+ }, 1e4).unref();
1777
+ return;
1778
+ }
1779
+ try {
1780
+ child.kill("SIGINT");
1781
+ } catch {
1080
1782
  }
1081
- return vol;
1783
+ return;
1082
1784
  }
1083
- if (vol && typeof vol === "object" && vol.source === oldKey) {
1084
- return { ...vol, source: newKey };
1085
- }
1086
- return vol;
1087
- });
1088
- }
1089
- function rewriteServiceSecret(svc, oldKey, newKey) {
1090
- if (!svc || !svc.secrets) return;
1091
- if (Array.isArray(svc.secrets)) {
1092
- svc.secrets = svc.secrets.map((sec) => {
1093
- if (sec === oldKey) return newKey;
1094
- if (typeof sec === "object" && sec.source === oldKey) {
1095
- return { ...sec, source: newKey };
1096
- }
1097
- return sec;
1098
- });
1099
- }
1100
- }
1101
- function rewriteServiceConfig(svc, oldKey, newKey) {
1102
- if (!svc || !svc.configs) return;
1103
- if (Array.isArray(svc.configs)) {
1104
- svc.configs = svc.configs.map((cfg) => {
1105
- if (cfg === oldKey) return newKey;
1106
- if (typeof cfg === "object" && cfg.source === oldKey) {
1107
- return { ...cfg, source: newKey };
1108
- }
1109
- return cfg;
1110
- });
1111
- }
1112
- }
1113
- function mergeAndNamespaceMockResources(parsed, namespacePrefix, baseDir, targetMeshDir) {
1114
- if (!parsed || typeof parsed !== "object") return;
1115
- if (parsed.volumes && typeof parsed.volumes === "object") {
1116
- composeConfig.volumes = composeConfig.volumes || {};
1117
- for (const [volKey, volDef] of Object.entries(parsed.volumes)) {
1118
- const namespacedVolKey = `${namespacePrefix}_${volKey}`;
1119
- composeConfig.volumes[namespacedVolKey] = volDef ?? {};
1120
- if (parsed.services && typeof parsed.services === "object") {
1121
- for (const svc of Object.values(parsed.services)) {
1122
- rewriteServiceVolume(svc, volKey, namespacedVolKey);
1123
- }
1124
- }
1125
- }
1126
- }
1127
- if (parsed.secrets && typeof parsed.secrets === "object") {
1128
- composeConfig.secrets = composeConfig.secrets || {};
1129
- for (const [secKey, secDef] of Object.entries(parsed.secrets)) {
1130
- const namespacedSecKey = `${namespacePrefix}_${secKey}`;
1131
- const clonedDef = { ...secDef };
1132
- if (clonedDef.file) {
1133
- clonedDef.file = toComposePath(targetMeshDir, path13.resolve(baseDir, clonedDef.file));
1134
- }
1135
- composeConfig.secrets[namespacedSecKey] = clonedDef;
1136
- if (parsed.services && typeof parsed.services === "object") {
1137
- for (const svc of Object.values(parsed.services)) {
1138
- rewriteServiceSecret(svc, secKey, namespacedSecKey);
1139
- }
1140
- }
1141
- }
1142
- }
1143
- if (parsed.configs && typeof parsed.configs === "object") {
1144
- composeConfig.configs = composeConfig.configs || {};
1145
- for (const [cfgKey, cfgDef] of Object.entries(parsed.configs)) {
1146
- const namespacedCfgKey = `${namespacePrefix}_${cfgKey}`;
1147
- const clonedDef = { ...cfgDef };
1148
- if (clonedDef.file) {
1149
- clonedDef.file = toComposePath(targetMeshDir, path13.resolve(baseDir, clonedDef.file));
1150
- }
1151
- composeConfig.configs[namespacedCfgKey] = clonedDef;
1152
- if (parsed.services && typeof parsed.services === "object") {
1153
- for (const svc of Object.values(parsed.services)) {
1154
- rewriteServiceConfig(svc, cfgKey, namespacedCfgKey);
1155
- }
1156
- }
1157
- }
1158
- }
1159
- }
1160
- function applyInternalMockDependsOnMapping(svc, mapping) {
1161
- if (!svc.depends_on) return;
1162
- if (Array.isArray(svc.depends_on)) {
1163
- svc.depends_on = svc.depends_on.map((d) => mapping.get(d) || d);
1164
- } else if (typeof svc.depends_on === "object") {
1165
- const newDepends = {};
1166
- for (const [k, v] of Object.entries(svc.depends_on)) {
1167
- newDepends[mapping.get(k) || k] = v;
1168
- }
1169
- svc.depends_on = newDepends;
1170
- }
1171
- }
1172
- function registerService(key, serviceDef, origin) {
1173
- if (composeConfig.services[key]) {
1174
- throw new ScriptError(
1175
- `Service name collision in mesh compose configuration: Service "${key}" from ${origin} conflicts with an existing service definition.`
1176
- );
1177
- }
1178
- composeConfig.services[key] = serviceDef;
1179
- }
1180
- for (const serviceName of Object.keys(mesh.services)) {
1181
- composeConfig.networks[`${serviceName}_net`] = {};
1182
- }
1183
- if (mesh.dependencies && typeof mesh.dependencies === "object") {
1184
- for (const [depKey, depDef] of Object.entries(mesh.dependencies)) {
1185
- const depComposePath = path13.resolve(meshDir, depDef.path);
1186
- if (!existsSync(depComposePath)) {
1187
- throw new ScriptError(
1188
- `Root dependency compose file not found: ${depComposePath}`
1189
- );
1190
- }
1191
- const raw = readFileSync(depComposePath, "utf-8");
1192
- const parsed = parse(raw);
1193
- if (!parsed?.services || typeof parsed.services !== "object") {
1194
- throw new ScriptError(
1195
- `Root dependency compose file "${depDef.path}" does not define any services.`
1196
- );
1197
- }
1198
- mergeAndNamespaceMockResources(parsed, `mesh_${depKey}`, meshDir, meshDir);
1199
- const targetServiceName = depDef.service || Object.keys(parsed.services)[0];
1200
- const serviceEntry = targetServiceName ? parsed.services[targetServiceName] : void 0;
1201
- if (!serviceEntry) {
1202
- throw new ScriptError(
1203
- `Service "${targetServiceName}" not found in root dependency compose file: ${depComposePath}`
1204
- );
1205
- }
1206
- const sidecarMapping = /* @__PURE__ */ new Map();
1207
- for (const sName of Object.keys(parsed.services)) {
1208
- if (sName === targetServiceName) {
1209
- sidecarMapping.set(sName, depKey);
1210
- } else {
1211
- const companionKey = `${depKey}-${sName}`;
1212
- sidecarMapping.set(sName, composeConfig.services[sName] ? companionKey : sName);
1213
- }
1214
- }
1215
- const resolvedService = resolveServicePaths(serviceEntry, meshDir, meshDir);
1216
- delete resolvedService.container_name;
1217
- normalizeDependsOn(resolvedService);
1218
- applyInternalMockDependsOnMapping(resolvedService, sidecarMapping);
1219
- resolvedService.networks = {
1220
- mesh: {
1221
- aliases: [depKey, targetServiceName].filter(Boolean)
1222
- }
1223
- };
1224
- registerService(depKey, resolvedService, `root dependency "${depKey}"`);
1225
- for (const [sName, sDef] of Object.entries(parsed.services)) {
1226
- if (sName !== targetServiceName) {
1227
- const finalKey = sidecarMapping.get(sName);
1228
- const companion = resolveServicePaths(sDef, meshDir, meshDir);
1229
- delete companion.container_name;
1230
- normalizeDependsOn(companion);
1231
- applyInternalMockDependsOnMapping(companion, sidecarMapping);
1232
- companion.networks = {
1233
- mesh: {
1234
- aliases: [sName, finalKey]
1235
- }
1236
- };
1237
- registerService(finalKey, companion, `companion of root dependency "${depKey}"`);
1238
- }
1239
- }
1240
- }
1241
- }
1242
- const providerAliases = /* @__PURE__ */ new Map();
1243
- for (const sName of Object.keys(mesh.services)) {
1244
- providerAliases.set(sName, /* @__PURE__ */ new Set());
1245
- }
1246
- const globalDepAliasToProvider = /* @__PURE__ */ new Map();
1247
- const INTERNAL_PORT = 3e3;
1248
- const serviceUrls = /* @__PURE__ */ new Map();
1249
- const allocatedPorts = /* @__PURE__ */ new Map();
1250
- function claimPort(portVal, ownerDesc) {
1251
- if (!portVal) return;
1252
- const portStr = String(portVal);
1253
- const hostPort = portStr.includes(":") ? portStr.split(":")[0] : portStr;
1254
- if (!hostPort) return;
1255
- if (allocatedPorts.has(hostPort)) {
1256
- throw new ScriptError(
1257
- `\u274C Port Collision Detected: Host port ${hostPort} is requested by both [${allocatedPorts.get(hostPort)}] and [${ownerDesc}].`
1258
- );
1259
- }
1260
- allocatedPorts.set(hostPort, ownerDesc);
1261
- }
1262
- for (const [serviceName, serviceConfig] of Object.entries(mesh.services)) {
1263
- const serviceDir = path13.resolve(meshDir, serviceConfig.path);
1264
- const serviceBuildJson = getBuildJson(serviceDir);
1265
- const serviceDeps = extractBuildDeps(serviceBuildJson, serviceDir);
1266
- let publicPort = null;
1267
- if (serviceConfig.port !== void 0 && serviceConfig.port !== null && serviceConfig.port !== "") {
1268
- publicPort = serviceConfig.port;
1269
- claimPort(publicPort, `mesh service "${serviceName}"`);
1270
- } else if (serviceConfig.preservePort && serviceBuildJson.port) {
1271
- publicPort = serviceBuildJson.port;
1272
- claimPort(publicPort, `mesh service "${serviceName}" (via preservePort)`);
1273
- }
1274
- const provideMap = {
1275
- ...serviceConfig.replaceMocks || {},
1276
- ...serviceConfig.provideDependency || {}
1277
- };
1278
- for (const dep of serviceDeps) {
1279
- if (provideMap[dep.name] || mesh.dependencies?.[dep.name]) continue;
1280
- for (const mapping of getDependencyPortMappings(dep, `Local dependency "${dep.name}" of service "${serviceName}"`)) {
1281
- claimPort(mapping.raw, `local dependency "${dep.name}" of service "${serviceName}"`);
1282
- }
1283
- }
1284
- const hostPort = publicPort ? String(publicPort).includes(":") ? String(publicPort).split(":")[0] : String(publicPort) : null;
1285
- serviceUrls.set(serviceName, {
1286
- networkUrl: `http://${serviceName}:${INTERNAL_PORT}`,
1287
- publicUrl: hostPort ? `http://localhost:${hostPort}` : null
1288
- });
1289
- }
1290
- function escapeRegExp(string) {
1291
- return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1292
- }
1293
- function interpolateEnvTemplates(value, context) {
1294
- if (typeof value !== "string") {
1295
- return value;
1296
- }
1297
- if (!options.silenceWarnings && context.includes("Tester") && value.includes(".network_url")) {
1298
- console.warn(
1299
- pc22.yellow(`
1300
- \u26A0\uFE0F WARNING: You are passing a '.network_url' template to the E2E tester ("${value}"). Since the tester runs in 'network_mode: host', it cannot resolve internal Docker DNS. Use '.public_url' instead. (Mute with --silence-warnings)
1301
- `)
1302
- );
1303
- }
1304
- let interpolated = value;
1305
- for (const [sName, urls] of serviceUrls.entries()) {
1306
- interpolated = interpolated.replace(
1307
- new RegExp(`\\$\\{${escapeRegExp(sName)}\\.network_url\\}`, "g"),
1308
- urls.networkUrl
1309
- );
1310
- if (urls.publicUrl) {
1311
- interpolated = interpolated.replace(
1312
- new RegExp(`\\$\\{${escapeRegExp(sName)}\\.public_url\\}`, "g"),
1313
- urls.publicUrl
1314
- );
1315
- }
1316
- }
1317
- const unresolvedMatch = interpolated.match(/\$\{([^}]+?)\.(network_url|public_url)\}/);
1318
- if (unresolvedMatch) {
1319
- const variable = unresolvedMatch[0];
1320
- const targetService = unresolvedMatch[1];
1321
- const type = unresolvedMatch[2];
1322
- if (!serviceUrls.has(targetService)) {
1323
- throw new ScriptError(
1324
- `[${context}] Unresolved template variable: ${variable}. Service "${targetService}" is not defined in mesh.json.`
1325
- );
1326
- } else if (type === "public_url") {
1327
- throw new ScriptError(
1328
- `[${context}] Unresolved template variable: ${variable}. Service "${targetService}" does not expose a public port (missing 'port' or 'preservePort' in mesh.json).`
1329
- );
1330
- } else {
1331
- throw new ScriptError(`[${context}] Unresolved template variable: ${variable}.`);
1332
- }
1333
- }
1334
- return interpolated;
1335
- }
1336
- for (const [serviceName, serviceConfig] of Object.entries(mesh.services)) {
1337
- const serviceDir = path13.resolve(meshDir, serviceConfig.path);
1338
- const serviceBuildJson = getBuildJson(serviceDir);
1339
- const serviceOverrides = extractOverrides(serviceBuildJson, serviceDir);
1340
- const serviceDeps = extractBuildDeps(serviceBuildJson, serviceDir);
1341
- const relServiceDir = toComposePath(meshDir, serviceDir);
1342
- const dockerfile = serviceBuildJson.dockerfile || "Dockerfile";
1343
- const environment = {
1344
- INFRA_MODE: "integrated",
1345
- EXEC_MODE: mode
1346
- };
1347
- let overrideVolumes = [];
1348
- let overrideHealthcheck = void 0;
1349
- let overrideCommand = void 0;
1350
- let overrideApp = void 0;
1351
- const stageOverride = serviceOverrides[mode];
1352
- if (stageOverride && existsSync(stageOverride.path)) {
1353
- try {
1354
- const overrideYaml = parse(readFileSync(stageOverride.path, "utf-8"));
1355
- mergeTopLevelResources(overrideYaml);
1356
- overrideApp = overrideYaml?.services?.app || overrideYaml?.services?.[serviceName];
1357
- if (!overrideApp && overrideYaml?.services && Object.keys(overrideYaml.services).length > 0) {
1358
- throw new ScriptError(
1359
- `Override file "${stageOverride.path}" must define service "app" or "${serviceName}".`
1360
- );
1361
- }
1362
- if (overrideApp) {
1363
- if (Array.isArray(overrideApp.environment)) {
1364
- for (const item of overrideApp.environment) {
1365
- const eqIdx = item.indexOf("=");
1366
- if (eqIdx !== -1) {
1367
- environment[item.slice(0, eqIdx)] = item.slice(eqIdx + 1);
1368
- } else {
1369
- environment[item] = process.env[item] ?? null;
1370
- }
1371
- }
1372
- } else if (overrideApp.environment && typeof overrideApp.environment === "object") {
1373
- Object.assign(environment, overrideApp.environment);
1374
- }
1375
- if (overrideApp.command) {
1376
- overrideCommand = overrideApp.command;
1377
- }
1378
- if (Array.isArray(overrideApp.volumes)) {
1379
- overrideVolumes = overrideApp.volumes.map(
1380
- (vol) => resolveVolumeEntry(vol, serviceDir, meshDir)
1381
- );
1382
- }
1383
- if (overrideApp.healthcheck) {
1384
- overrideHealthcheck = overrideApp.healthcheck;
1385
- }
1386
- }
1387
- } catch (err) {
1388
- if (err instanceof ScriptError) throw err;
1389
- const msg = err instanceof Error ? err.message : String(err);
1390
- throw new ScriptError(
1391
- `Failed to parse override file ${stageOverride.path}: ${msg}`
1392
- );
1393
- }
1394
- }
1395
- environment.PORT = String(INTERNAL_PORT);
1396
- const buildArgs = {};
1397
- if (overrideApp?.build?.args) {
1398
- if (Array.isArray(overrideApp.build.args)) {
1399
- for (const item of overrideApp.build.args) {
1400
- if (typeof item === "string") {
1401
- const eqIdx = item.indexOf("=");
1402
- if (eqIdx !== -1) {
1403
- buildArgs[item.slice(0, eqIdx)] = item.slice(eqIdx + 1);
1404
- } else {
1405
- buildArgs[item] = process.env[item] ?? null;
1406
- }
1407
- }
1408
- }
1409
- } else if (typeof overrideApp.build.args === "object") {
1410
- Object.assign(buildArgs, overrideApp.build.args);
1411
- }
1412
- }
1413
- if (serviceBuildJson.envOverrides) {
1414
- for (const [k, v] of Object.entries(serviceBuildJson.envOverrides)) {
1415
- const interpolated = interpolateEnvTemplates(v, `Service build.json: ${serviceName}`);
1416
- environment[k] = interpolated;
1417
- buildArgs[k] = interpolated;
1418
- }
1419
- }
1420
- if (serviceConfig.envOverrides) {
1421
- for (const [k, v] of Object.entries(serviceConfig.envOverrides)) {
1422
- const interpolated = interpolateEnvTemplates(v, `Service: ${serviceName}`);
1423
- environment[k] = interpolated;
1424
- buildArgs[k] = interpolated;
1425
- }
1426
- }
1427
- const serviceDef = {
1428
- build: {
1429
- context: relServiceDir,
1430
- dockerfile,
1431
- target: mode,
1432
- ...Object.keys(buildArgs).length > 0 ? { args: buildArgs } : {}
1433
- },
1434
- init: true,
1435
- logging: {
1436
- driver: "json-file",
1437
- options: {
1438
- "max-size": "10m",
1439
- "max-file": "3"
1440
- }
1441
- },
1442
- environment,
1443
- depends_on: {}
1444
- };
1445
- const envFilePath = path13.resolve(serviceDir, `.env.${mode}`);
1446
- if (existsSync(envFilePath)) {
1447
- serviceDef.env_file = [toComposePath(meshDir, envFilePath)];
1448
- }
1449
- if (mode === "dev") {
1450
- const volSet = /* @__PURE__ */ new Set();
1451
- volSet.add(`${relServiceDir}:/app`);
1452
- volSet.add("/app/node_modules");
1453
- for (const v of overrideVolumes) {
1454
- if (typeof v === "string") {
1455
- volSet.add(v);
1456
- }
1457
- }
1458
- serviceDef.volumes = Array.from(volSet);
1459
- }
1460
- const urls = serviceUrls.get(serviceName);
1461
- if (urls.publicUrl) {
1462
- const pubPort = urls.publicUrl.split(":").pop();
1463
- serviceDef.ports = [`${pubPort}:${INTERNAL_PORT}`];
1464
- } else {
1465
- delete serviceDef.ports;
1466
- }
1467
- if (overrideCommand) {
1468
- serviceDef.command = overrideCommand;
1469
- }
1470
- if (serviceConfig.healthcheck) {
1471
- if (serviceConfig.healthcheck.type === "tcp") {
1472
- const hcPort = serviceConfig.healthcheck.port || INTERNAL_PORT;
1473
- serviceDef.healthcheck = {
1474
- test: [
1475
- "CMD-SHELL",
1476
- `nc -z 127.0.0.1 ${hcPort} || node -e "require('net').connect(${hcPort},'127.0.0.1').on('connect',()=>process.exit(0)).on('error',()=>process.exit(1))" || exit 1`
1477
- ],
1478
- interval: "2s",
1479
- timeout: "2s",
1480
- start_period: "3s",
1481
- retries: 10
1482
- };
1483
- } else {
1484
- serviceDef.healthcheck = serviceConfig.healthcheck;
1485
- }
1486
- } else if (overrideHealthcheck) {
1487
- serviceDef.healthcheck = overrideHealthcheck;
1488
- } else {
1489
- serviceDef.healthcheck = {
1490
- test: [
1491
- "CMD-SHELL",
1492
- `nc -z 127.0.0.1 ${INTERNAL_PORT} || node -e "require('net').connect(${INTERNAL_PORT},'127.0.0.1').on('connect',()=>process.exit(0)).on('error',()=>process.exit(1))" || exit 1`
1493
- ],
1494
- interval: "2s",
1495
- timeout: "2s",
1496
- start_period: "3s",
1497
- retries: 10
1498
- };
1499
- }
1500
- const namespacedAppKey = `${serviceName}-app`;
1501
- serviceDef.networks = {
1502
- mesh: {
1503
- aliases: [serviceName, namespacedAppKey]
1504
- },
1505
- [`${serviceName}_net`]: {
1506
- aliases: ["app", serviceName, namespacedAppKey]
1507
- }
1508
- };
1509
- const provideMap = {
1510
- ...serviceConfig.replaceMocks || {},
1511
- ...serviceConfig.provideDependency || {}
1512
- };
1513
- const declaredDepNames = new Set(serviceDeps.map((d) => d.name));
1514
- for (const [depKey, targetProvider] of Object.entries(provideMap)) {
1515
- if (!declaredDepNames.has(depKey)) {
1516
- throw new ScriptError(
1517
- `Service "${serviceName}" declares provideDependency/replaceMocks for "${depKey}", but "${depKey}" is not declared in its build.json dependencies.`
1518
- );
1519
- }
1520
- if (!mesh.services[targetProvider]) {
1521
- throw new ScriptError(
1522
- `Service "${serviceName}" maps dependency "${depKey}" to nonexistent service "${targetProvider}".`
1523
- );
1524
- }
1525
- if (globalDepAliasToProvider.has(depKey) && globalDepAliasToProvider.get(depKey) !== targetProvider) {
1526
- throw new ScriptError(
1527
- `Dependency alias collision: Dependency key "${depKey}" is mapped to multiple different provider services ("${globalDepAliasToProvider.get(
1528
- depKey
1529
- )}" and "${targetProvider}").`
1530
- );
1531
- }
1532
- if (mesh.services[depKey] && depKey !== targetProvider) {
1533
- throw new ScriptError(
1534
- `Dependency alias conflict: Dependency key "${depKey}" collides with declared mesh service "${depKey}".`
1535
- );
1536
- }
1537
- globalDepAliasToProvider.set(depKey, targetProvider);
1538
- }
1539
- for (const dep of serviceDeps) {
1540
- const depKey = dep.name;
1541
- if (provideMap[depKey]) {
1542
- const fellowService = provideMap[depKey];
1543
- const fellowAppKey = `${fellowService}-app`;
1544
- serviceDef.depends_on[fellowAppKey] = {
1545
- condition: "service_healthy"
1546
- };
1547
- providerAliases.get(fellowService)?.add(depKey);
1548
- } else if (mesh.dependencies && mesh.dependencies[depKey]) {
1549
- serviceDef.depends_on[depKey] = {
1550
- condition: "service_healthy"
1551
- };
1552
- } else {
1553
- const namespacedDepKey = `${serviceName}-${depKey}`;
1554
- serviceDef.depends_on[namespacedDepKey] = {
1555
- condition: "service_healthy"
1556
- };
1557
- const depComposePath = dep.path;
1558
- if (!existsSync(depComposePath)) {
1559
- throw new ScriptError(
1560
- `Mock compose file for dependency "${depKey}" not found: ${depComposePath}`
1561
- );
1562
- }
1563
- const raw = readFileSync(depComposePath, "utf-8");
1564
- const parsed = parse(raw);
1565
- if (!parsed?.services || typeof parsed.services !== "object") {
1566
- throw new ScriptError(
1567
- `Invalid compose file for dependency "${depKey}": missing "services"`
1568
- );
1569
- }
1570
- mergeAndNamespaceMockResources(parsed, `${serviceName}_${depKey}`, serviceDir, meshDir);
1571
- if (dep.serviceName && !parsed.services[dep.serviceName]) {
1572
- throw new ScriptError(
1573
- `Service "${dep.serviceName}" declared in build.json not found in mock compose ${depComposePath}`
1574
- );
1575
- }
1576
- const targetMockService = dep.serviceName ? parsed.services[dep.serviceName] : Object.values(parsed.services)[0];
1577
- if (!targetMockService) {
1578
- throw new ScriptError(
1579
- `No services found in mock compose ${depComposePath}`
1580
- );
1581
- }
1582
- const sidecarMapping = /* @__PURE__ */ new Map();
1583
- for (const mName of Object.keys(parsed.services)) {
1584
- if (parsed.services[mName] === targetMockService) {
1585
- sidecarMapping.set(mName, namespacedDepKey);
1586
- } else {
1587
- sidecarMapping.set(mName, `${serviceName}-${mName}`);
1588
- }
1589
- }
1590
- const resolvedMock = resolveServicePaths(
1591
- targetMockService,
1592
- serviceDir,
1593
- meshDir
1594
- );
1595
- delete resolvedMock.ports;
1596
- delete resolvedMock.container_name;
1597
- normalizeDependsOn(resolvedMock);
1598
- applyInternalMockDependsOnMapping(resolvedMock, sidecarMapping);
1599
- const portMappings = getDependencyPortMappings(dep, `Local dependency "${depKey}" of service "${serviceName}"`);
1600
- if (portMappings.length > 0) {
1601
- resolvedMock.ports = portMappings.map((mapping) => mapping.raw);
1602
- }
1603
- resolvedMock.networks = {
1604
- [`${serviceName}_net`]: {
1605
- aliases: [depKey, namespacedDepKey]
1606
- }
1607
- };
1608
- registerService(namespacedDepKey, resolvedMock, `mock dependency for "${serviceName}"`);
1609
- for (const [mName, mDef] of Object.entries(parsed.services)) {
1610
- if (mDef !== targetMockService) {
1611
- const sidecarKey = sidecarMapping.get(mName);
1612
- if (!composeConfig.services[sidecarKey]) {
1613
- const resolvedSidecar = resolveServicePaths(mDef, serviceDir, meshDir);
1614
- delete resolvedSidecar.ports;
1615
- delete resolvedSidecar.container_name;
1616
- normalizeDependsOn(resolvedSidecar);
1617
- applyInternalMockDependsOnMapping(resolvedSidecar, sidecarMapping);
1618
- resolvedSidecar.networks = {
1619
- [`${serviceName}_net`]: {
1620
- aliases: [mName, sidecarKey]
1621
- }
1622
- };
1623
- registerService(sidecarKey, resolvedSidecar, `sidecar of mock "${depKey}"`);
1624
- }
1625
- }
1626
- }
1627
- }
1628
- }
1629
- if (Object.keys(serviceDef.depends_on).length === 0) {
1630
- delete serviceDef.depends_on;
1631
- }
1632
- registerService(namespacedAppKey, serviceDef, `mesh service "${serviceName}"`);
1633
- }
1634
- for (const [providerName, aliases] of providerAliases.entries()) {
1635
- const appKey = `${providerName}-app`;
1636
- const serviceDef = composeConfig.services[appKey];
1637
- if (serviceDef && serviceDef.networks?.mesh) {
1638
- const existingAliases = new Set(serviceDef.networks.mesh.aliases || []);
1639
- for (const alias of aliases) {
1640
- existingAliases.add(alias);
1641
- }
1642
- serviceDef.networks.mesh.aliases = Array.from(existingAliases);
1643
- }
1644
- }
1645
- let testerServiceName;
1646
- if (options.includeTester && mesh.tester) {
1647
- const testerDir = path13.resolve(meshDir, mesh.tester.path);
1648
- const composeRel = mesh.tester.compose || "docker-compose.yml";
1649
- const testerComposePath = path13.resolve(testerDir, composeRel);
1650
- if (existsSync(testerComposePath)) {
1651
- const raw = readFileSync(testerComposePath, "utf-8");
1652
- const parsed = parse(raw);
1653
- mergeTopLevelResources(parsed);
1654
- if (parsed?.services && typeof parsed.services === "object") {
1655
- const firstKey = Object.keys(parsed.services)[0];
1656
- if (firstKey && parsed.services[firstKey]) {
1657
- testerServiceName = firstKey;
1658
- for (const [tKey, tDef] of Object.entries(parsed.services)) {
1659
- const resolvedTester = resolveServicePaths(
1660
- tDef,
1661
- testerDir,
1662
- meshDir
1663
- );
1664
- delete resolvedTester.container_name;
1665
- normalizeDependsOn(resolvedTester);
1666
- resolvedTester.network_mode = "host";
1667
- delete resolvedTester.networks;
1668
- if (tKey === firstKey) {
1669
- resolvedTester.depends_on = resolvedTester.depends_on || {};
1670
- for (const sName of Object.keys(mesh.services)) {
1671
- resolvedTester.depends_on[`${sName}-app`] = {
1672
- condition: "service_healthy"
1673
- };
1674
- }
1675
- if (mesh.tester.envOverrides) {
1676
- if (Array.isArray(resolvedTester.environment)) {
1677
- const envObj = {};
1678
- for (const item of resolvedTester.environment) {
1679
- if (typeof item === "string") {
1680
- const eqIdx = item.indexOf("=");
1681
- if (eqIdx !== -1) {
1682
- envObj[item.slice(0, eqIdx)] = item.slice(eqIdx + 1);
1683
- } else {
1684
- envObj[item] = process.env[item] ?? null;
1685
- }
1686
- }
1687
- }
1688
- resolvedTester.environment = envObj;
1689
- } else if (!resolvedTester.environment || typeof resolvedTester.environment !== "object") {
1690
- resolvedTester.environment = {};
1691
- }
1692
- for (const [k, v] of Object.entries(mesh.tester.envOverrides)) {
1693
- resolvedTester.environment[k] = interpolateEnvTemplates(v, `Tester: ${tKey}`);
1694
- }
1695
- }
1696
- }
1697
- registerService(tKey, resolvedTester, `tester service "${tKey}"`);
1698
- }
1699
- }
1700
- }
1701
- }
1702
- }
1703
- for (const svc of Object.values(composeConfig.services)) {
1704
- if (svc.depends_on && typeof svc.depends_on === "object") {
1705
- for (const [depTarget, depOpts] of Object.entries(svc.depends_on)) {
1706
- const targetSvc = composeConfig.services[depTarget];
1707
- if (targetSvc && (!targetSvc.healthcheck || targetSvc.healthcheck.disable) && depOpts && depOpts.condition === "service_healthy") {
1708
- depOpts.condition = "service_started";
1709
- }
1710
- }
1711
- }
1712
- }
1713
- const generatedYaml = stringify(composeConfig);
1714
- assertUniqueHostPortMappings(generatedYaml);
1715
- if (options.validateWithDocker === false) {
1716
- return { yaml: generatedYaml, testerServiceName };
1717
- }
1718
- const result = spawnSync(
1719
- "docker",
1720
- [
1721
- "compose",
1722
- "-p",
1723
- projectName,
1724
- "--project-directory",
1725
- meshDir,
1726
- "-f",
1727
- "-",
1728
- "config"
1729
- ],
1730
- {
1731
- cwd: meshDir,
1732
- input: generatedYaml,
1733
- encoding: "utf-8"
1734
- }
1735
- );
1736
- if (result.error) {
1737
- throw new ScriptError(
1738
- `Failed to run docker compose config: ${result.error.message}`,
1739
- { cause: result.error }
1740
- );
1741
- }
1742
- if (result.status !== 0) {
1743
- throw new ScriptError(
1744
- `\u274C Failed to validate mesh compose configuration:
1745
- ${result.stderr || result.stdout}`
1746
- );
1747
- }
1748
- return {
1749
- yaml: result.stdout || generatedYaml,
1750
- testerServiceName
1751
- };
1752
- }
1753
- function resolveVolumeEntry(vol, baseDir, meshDir) {
1754
- if (typeof vol === "string") {
1755
- if (!vol.includes(":")) {
1756
- return vol;
1757
- }
1758
- const parts = vol.split(":");
1759
- const host = parts[0];
1760
- if (isBindMount(host)) {
1761
- const absHost = path13.resolve(baseDir, host);
1762
- const formattedRel = toComposePath(meshDir, absHost);
1763
- return `${formattedRel}:${parts.slice(1).join(":")}`;
1764
- }
1765
- return vol;
1766
- }
1767
- if (vol && typeof vol === "object") {
1768
- const cloned = { ...vol };
1769
- if (cloned.type === "bind" && cloned.source && typeof cloned.source === "string") {
1770
- const absSource = path13.resolve(baseDir, cloned.source);
1771
- cloned.source = toComposePath(meshDir, absSource);
1772
- }
1773
- return cloned;
1774
- }
1775
- return vol;
1776
- }
1777
- function resolveServicePaths(service, baseDir, meshDir) {
1778
- const cloned = JSON.parse(JSON.stringify(service));
1779
- if (cloned.build) {
1780
- if (typeof cloned.build === "string") {
1781
- cloned.build = toComposePath(meshDir, path13.resolve(baseDir, cloned.build));
1782
- } else if (cloned.build.context) {
1783
- cloned.build.context = toComposePath(
1784
- meshDir,
1785
- path13.resolve(baseDir, cloned.build.context)
1786
- );
1787
- }
1788
- }
1789
- if (Array.isArray(cloned.volumes)) {
1790
- cloned.volumes = cloned.volumes.map(
1791
- (vol) => resolveVolumeEntry(vol, baseDir, meshDir)
1792
- );
1793
- }
1794
- if (Array.isArray(cloned.env_file)) {
1795
- cloned.env_file = cloned.env_file.map((ef) => {
1796
- if (typeof ef === "string") {
1797
- return toComposePath(meshDir, path13.resolve(baseDir, ef));
1798
- }
1799
- if (ef && typeof ef === "object" && ef.path) {
1800
- return {
1801
- ...ef,
1802
- path: toComposePath(meshDir, path13.resolve(baseDir, ef.path))
1803
- };
1804
- }
1805
- return ef;
1806
- });
1807
- } else if (typeof cloned.env_file === "string") {
1808
- cloned.env_file = toComposePath(meshDir, path13.resolve(baseDir, cloned.env_file));
1809
- }
1810
- normalizeDependsOn(cloned);
1811
- return cloned;
1812
- }
1813
- var activeComposeSet = /* @__PURE__ */ new Set();
1814
- var signalHandlersRegistered = false;
1815
- var activeChildProcess = null;
1816
- var isTearingDown = false;
1817
- var isShuttingDown = false;
1818
- var isProcessAlive = (c) => {
1819
- return Boolean(c && c.exitCode === null && c.signalCode === null);
1820
- };
1821
- function setActiveChild(child) {
1822
- activeChildProcess = child;
1823
- if (!child) {
1824
- isShuttingDown = false;
1825
- }
1826
- }
1827
- function setTearingDown(tearingDown) {
1828
- isTearingDown = tearingDown;
1829
- }
1830
- function registerActiveCompose(yamlConfig, projectDir, options = {}) {
1831
- const entry = {
1832
- yamlConfig,
1833
- projectDir,
1834
- removeVolumes: options.removeVolumes
1835
- };
1836
- activeComposeSet.add(entry);
1837
- ensureSignalHandlers();
1838
- return () => {
1839
- activeComposeSet.delete(entry);
1840
- };
1841
- }
1842
- function ensureSignalHandlers() {
1843
- if (signalHandlersRegistered) return;
1844
- signalHandlersRegistered = true;
1845
- const handleSignal = (signal) => {
1846
- if (isTearingDown) {
1847
- return;
1848
- }
1849
- if (activeChildProcess && isProcessAlive(activeChildProcess)) {
1850
- const child = activeChildProcess;
1851
- if (signal === "SIGINT") {
1852
- if (!isShuttingDown) {
1853
- isShuttingDown = true;
1854
- setTimeout(() => {
1855
- if (isProcessAlive(child)) {
1856
- try {
1857
- child.kill("SIGKILL");
1858
- } catch {
1859
- }
1860
- }
1861
- }, 1e4).unref();
1862
- return;
1863
- }
1864
- try {
1865
- child.kill("SIGINT");
1866
- } catch {
1867
- }
1868
- return;
1869
- }
1870
- try {
1871
- child.kill(signal);
1872
- } catch {
1785
+ try {
1786
+ child.kill(signal);
1787
+ } catch {
1873
1788
  }
1874
1789
  setTimeout(() => {
1875
1790
  if (isProcessAlive(child)) {
@@ -1963,8 +1878,8 @@ async function teardownCompose(yamlConfig, projectDir, options = {}) {
1963
1878
  }
1964
1879
  const inputData = options.projectName ? void 0 : yamlConfig;
1965
1880
  if (!removeVolumes) {
1966
- const rmArgs = [...baseArgs, "rm", "-f", "-v", "app"];
1967
- await runSpawn("docker", rmArgs, absProjectDir, inputData, true, 15e3);
1881
+ const services = yamlConfig.trim() ? anonymousVolumeServices(parse(yamlConfig)?.services ?? {}) : options.anonymousVolumeServices ?? [];
1882
+ if (services.length) await runSpawn("docker", [...baseArgs, "rm", "-s", "-f", "-v", ...services], absProjectDir, inputData, true, 15e3);
1968
1883
  }
1969
1884
  const downArgs = [...baseArgs, "down"];
1970
1885
  if (removeVolumes) {
@@ -2021,12 +1936,12 @@ function redactYamlSecrets(yamlContent) {
2021
1936
  return redacted;
2022
1937
  }
2023
1938
  function getRunStatePath(projectDir) {
2024
- return path13.resolve(resolveProjectDir(projectDir), ".builder", "run.state");
1939
+ return path.resolve(resolveProjectDir(projectDir), ".builder", "run.state");
2025
1940
  }
2026
1941
  function writeRunState(projectDir, state) {
2027
1942
  try {
2028
1943
  const absDir = resolveProjectDir(projectDir);
2029
- const builderDir = path13.resolve(absDir, ".builder");
1944
+ const builderDir = path.resolve(absDir, ".builder");
2030
1945
  if (!existsSync(builderDir)) {
2031
1946
  mkdirSync(builderDir, { recursive: true });
2032
1947
  }
@@ -2035,7 +1950,7 @@ function writeRunState(projectDir, state) {
2035
1950
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
2036
1951
  };
2037
1952
  writeFileSync(
2038
- path13.resolve(builderDir, "run.state"),
1953
+ path.resolve(builderDir, "run.state"),
2039
1954
  JSON.stringify(fullState, null, 2),
2040
1955
  "utf-8"
2041
1956
  );
@@ -2066,9 +1981,9 @@ function projectNamesForServiceStage(projectDir, stage) {
2066
1981
  let rawName;
2067
1982
  try {
2068
1983
  const buildJson = getBuildJson(absDir);
2069
- rawName = buildJson.name || path13.basename(absDir);
1984
+ rawName = buildJson.name || path.basename(absDir);
2070
1985
  } catch {
2071
- rawName = path13.basename(absDir);
1986
+ rawName = path.basename(absDir);
2072
1987
  }
2073
1988
  const s = stage.toLowerCase();
2074
1989
  if (s === "dev") {
@@ -2094,13 +2009,13 @@ function projectNamesForServiceStage(projectDir, stage) {
2094
2009
  function projectNamesForMeshStage(meshDir, stage) {
2095
2010
  const absDir = resolveProjectDir(meshDir);
2096
2011
  let rawMeshName;
2097
- let services = {};
2012
+ let serviceNames = [];
2098
2013
  try {
2099
2014
  const mesh = getMeshJson(absDir);
2100
- rawMeshName = mesh.name || path13.basename(absDir);
2101
- services = mesh.services || {};
2015
+ rawMeshName = mesh.name || path.basename(absDir);
2016
+ serviceNames = Object.keys(resolveMeshStage(mesh, "test", path.join(absDir, "mesh.json")).services);
2102
2017
  } catch {
2103
- rawMeshName = path13.basename(absDir);
2018
+ rawMeshName = path.basename(absDir);
2104
2019
  }
2105
2020
  const s = stage.toLowerCase();
2106
2021
  if (s === "dev") {
@@ -2113,19 +2028,10 @@ function projectNamesForMeshStage(meshDir, stage) {
2113
2028
  return [deriveProjectName(rawMeshName, "e2e")];
2114
2029
  }
2115
2030
  if (s === "test-unit") {
2116
- return Object.values(services).map((svc) => {
2117
- const svcDir = path13.resolve(absDir, svc.path);
2118
- return projectNamesForServiceStage(svcDir, "test-unit")[0];
2119
- });
2031
+ return serviceNames.map((name) => `${deriveProjectName(rawMeshName, "dev")}-${name}-test`);
2120
2032
  }
2121
2033
  if (s === "test") {
2122
- const list = [];
2123
- for (const svc of Object.values(services)) {
2124
- const svcDir = path13.resolve(absDir, svc.path);
2125
- list.push(...projectNamesForServiceStage(svcDir, "test"));
2126
- }
2127
- list.push(deriveProjectName(rawMeshName, "e2e"));
2128
- return Array.from(new Set(list));
2034
+ return [...serviceNames.map((name) => `${deriveProjectName(rawMeshName, "dev")}-${name}-test`), deriveProjectName(rawMeshName, "e2e")];
2129
2035
  }
2130
2036
  return [deriveProjectName(rawMeshName, s)];
2131
2037
  }
@@ -2146,9 +2052,8 @@ async function handleMeshDown(rawStage = "dev", options = {}) {
2146
2052
  );
2147
2053
  if (options.debug) {
2148
2054
  try {
2149
- const mode = stage === "dev" ? "dev" : "prod";
2150
- const includeTester = stage === "test" || stage === "test-e2e";
2151
- const { yaml } = compileMeshEnvironment(mode, meshDir, { includeTester });
2055
+ const mode = stage === "dev" ? "dev" : stage === "test-e2e" ? "e2e" : "prod";
2056
+ const { yaml } = compileMeshEnvironment(mode, meshDir, { validateWithDocker: false });
2152
2057
  console.log(
2153
2058
  pc22.yellow("\nFinal merged Mesh YAML configuration:\n"),
2154
2059
  redactYamlSecrets(yaml)
@@ -2165,6 +2070,7 @@ async function handleMeshDown(rawStage = "dev", options = {}) {
2165
2070
  for (const proj of uniqueProjects) {
2166
2071
  await teardownCompose("", meshDir, {
2167
2072
  projectName: proj,
2073
+ ...runState?.projectName === proj && runState.anonymousVolumeServices ? { anonymousVolumeServices: runState.anonymousVolumeServices } : {},
2168
2074
  removeVolumes: Boolean(options.volumes)
2169
2075
  });
2170
2076
  }
@@ -2252,13 +2158,7 @@ async function checkHostPortCollisions(ports) {
2252
2158
  if (port > 0 && port < 65536) {
2253
2159
  const inUse = await isPortInUse(port);
2254
2160
  if (inUse) {
2255
- console.warn(
2256
- pc22.yellow(
2257
- `
2258
- \u26A0\uFE0F Host Port Conflict Warning: Port ${port} is already in use on the host (e.g. by another running stage or process). Docker Compose may fail to bind to this port.
2259
- `
2260
- )
2261
- );
2161
+ throw new ScriptError(`Host port ${port} is already in use. Builder does not remap fixed public ports.`);
2262
2162
  }
2263
2163
  }
2264
2164
  }
@@ -2321,12 +2221,7 @@ async function runMeshDev(options = {}) {
2321
2221
  const meshDir = resolveProjectDir(options.projectDir);
2322
2222
  console.log(pc22.cyan(`
2323
2223
  \u{1F680} Starting Global DEV Mesh Environment...`));
2324
- if (!options.skipChecks) {
2325
- checkMesh(meshDir, { requireTester: false });
2326
- }
2327
- const { yaml } = compileMeshEnvironment("dev", meshDir, {
2328
- silenceWarnings: options.silenceWarnings
2329
- });
2224
+ const { yaml } = compileMeshEnvironment("dev", meshDir);
2330
2225
  const parsed = parse(yaml);
2331
2226
  const projectName = parsed?.name || "mesh-dev";
2332
2227
  if (options.debug) {
@@ -2343,6 +2238,7 @@ async function runMeshDev(options = {}) {
2343
2238
  await checkHostPortCollisions(hostPorts);
2344
2239
  writeRunState(meshDir, {
2345
2240
  projectName,
2241
+ anonymousVolumeServices: anonymousVolumeServices(parsed?.services ?? {}),
2346
2242
  stage: "dev",
2347
2243
  projectDir: meshDir
2348
2244
  });
@@ -2365,1007 +2261,115 @@ async function runMeshDev(options = {}) {
2365
2261
  }
2366
2262
  async function runMeshProd(options = {}) {
2367
2263
  const meshDir = resolveProjectDir(options.projectDir);
2368
- console.log(pc22.cyan(`
2369
- \u{1F3ED} Starting Global PROD Mesh Environment...`));
2370
- if (!options.skipChecks) {
2371
- checkMesh(meshDir, { requireTester: false });
2372
- }
2373
- const { yaml } = compileMeshEnvironment("prod", meshDir, {
2374
- silenceWarnings: options.silenceWarnings
2375
- });
2376
- const parsed = parse(yaml);
2377
- const projectName = parsed?.name || "mesh-prod";
2378
- if (options.debug) {
2379
- console.log(
2380
- pc22.yellow("\nFinal merged Mesh Prod YAML configuration:\n"),
2381
- redactYamlSecrets(yaml)
2382
- );
2383
- }
2384
- if (options.dryRun) {
2385
- console.log(pc22.green("Dry run complete. Compose was not started."));
2386
- return 0;
2387
- }
2388
- const hostPorts = extractHostPorts(yaml);
2389
- await checkHostPortCollisions(hostPorts);
2390
- writeRunState(meshDir, {
2391
- projectName,
2392
- stage: "prod",
2393
- projectDir: meshDir
2394
- });
2395
- const upArgs = ["up", "--build"];
2396
- if (options.detach) {
2397
- upArgs.push("-d");
2398
- }
2399
- let status = 0;
2400
- try {
2401
- status = await runCompose(upArgs, yaml, meshDir, {
2402
- removeVolumes: false
2403
- });
2404
- } finally {
2405
- if (!options.detach) {
2406
- await teardownCompose(yaml, meshDir, { removeVolumes: false });
2407
- clearRunState(meshDir);
2408
- }
2409
- }
2410
- return status;
2411
- }
2412
-
2413
- // src/utils/ymlMods/addDependenciesToAppService.ts
2414
- var addDependenciesToAppService = (yml, dependencies) => {
2415
- if (!yml || !yml.services || !yml.services.app) {
2416
- throw new ScriptError("Invalid YAML structure. Missing 'services.app' field.");
2417
- }
2418
- if (!dependencies || dependencies.length === 0) {
2419
- return;
2420
- }
2421
- normalizeDependsOn(yml.services.app);
2422
- yml.services.app.depends_on = yml.services.app.depends_on || {};
2423
- dependencies.forEach((dep) => {
2424
- const targetSvc = yml.services[dep.name];
2425
- const hasHealthcheck = Boolean(targetSvc?.healthcheck);
2426
- yml.services.app.depends_on[dep.name] = {
2427
- condition: hasHealthcheck ? "service_healthy" : "service_started"
2428
- };
2429
- });
2430
- };
2431
-
2432
- // src/utils/ymlMods/attachName.ts
2433
- var attachName = (yml, nameOrBuildJson) => {
2434
- if (!yml) {
2435
- throw new ScriptError("Invalid YAML structure. Missing 'yml' field.");
2436
- }
2437
- const name = typeof nameOrBuildJson === "string" ? nameOrBuildJson : nameOrBuildJson?.name;
2438
- if (name) {
2439
- yml.name = name;
2440
- }
2441
- };
2442
-
2443
- // src/utils/ymlMods/makeE2eDependOnApp.ts
2444
- var makeE2eDependOnApp = (yml) => {
2445
- if (!yml || !yml.services) {
2446
- throw new ScriptError("Invalid YAML structure. Missing 'services' field.");
2447
- }
2448
- if (!yml.services.tester) {
2449
- throw new ScriptError("Tester service not found");
2450
- }
2451
- if (!yml.services.app) {
2452
- throw new ScriptError("App service not found");
2453
- }
2454
- normalizeDependsOn(yml.services.tester);
2455
- const appHasHealthcheck = Boolean(yml.services.app?.healthcheck);
2456
- yml.services.tester.depends_on = {
2457
- ...yml.services.tester.depends_on || {},
2458
- app: {
2459
- condition: appHasHealthcheck ? "service_healthy" : "service_started"
2460
- }
2461
- };
2462
- };
2463
-
2464
- // src/utils/ymlMods/renameServicesWithDependencies.ts
2465
- var renameServicesWithDependencies = (yml, dependencies) => {
2466
- if (!yml || !yml.services || typeof yml.services !== "object") {
2467
- throw new ScriptError("Invalid YAML structure. Missing 'services' field.");
2468
- }
2469
- if (!dependencies || dependencies.length === 0) {
2470
- return;
2471
- }
2472
- const renameMap = /* @__PURE__ */ new Map();
2473
- for (const dep of dependencies) {
2474
- if (dep.serviceName && dep.name && dep.serviceName !== dep.name) {
2475
- renameMap.set(dep.serviceName, dep.name);
2476
- }
2477
- }
2478
- if (renameMap.size === 0) {
2479
- return;
2480
- }
2481
- const currentKeys = new Set(Object.keys(yml.services));
2482
- for (const [oldName, newName] of renameMap.entries()) {
2483
- if (currentKeys.has(newName) && !renameMap.has(newName)) {
2484
- throw new ScriptError(
2485
- `Service collision: cannot rename "${oldName}" to "${newName}" because a service named "${newName}" already exists in the stack.`
2486
- );
2487
- }
2488
- }
2489
- const newServices = {};
2490
- for (const [name, service] of Object.entries(yml.services)) {
2491
- const targetName = renameMap.get(name) || name;
2492
- newServices[targetName] = service;
2493
- }
2494
- yml.services = newServices;
2495
- for (const service of Object.values(yml.services)) {
2496
- if (!service || typeof service !== "object") continue;
2497
- if (service.depends_on) {
2498
- if (Array.isArray(service.depends_on)) {
2499
- service.depends_on = service.depends_on.map(
2500
- (dep) => renameMap.get(dep) || dep
2501
- );
2502
- } else if (typeof service.depends_on === "object") {
2503
- const updatedDependsOn = {};
2504
- for (const [depName, depConfig] of Object.entries(service.depends_on)) {
2505
- const targetDepName = renameMap.get(depName) || depName;
2506
- updatedDependsOn[targetDepName] = depConfig;
2507
- }
2508
- service.depends_on = updatedDependsOn;
2509
- }
2510
- }
2511
- if (Array.isArray(service.links)) {
2512
- service.links = service.links.map((link) => {
2513
- const [targetSvc, alias] = link.split(":");
2514
- if (targetSvc && renameMap.has(targetSvc)) {
2515
- const newTarget = renameMap.get(targetSvc);
2516
- return alias ? `${newTarget}:${alias}` : newTarget;
2517
- }
2518
- return link;
2519
- });
2520
- }
2521
- if (typeof service.network_mode === "string" && service.network_mode.startsWith("service:")) {
2522
- const targetSvc = service.network_mode.slice("service:".length);
2523
- if (renameMap.has(targetSvc)) {
2524
- service.network_mode = `service:${renameMap.get(targetSvc)}`;
2525
- }
2526
- }
2527
- if (Array.isArray(service.volumes_from)) {
2528
- service.volumes_from = service.volumes_from.map((vf) => {
2529
- const [vfSvc, mode] = vf.split(":");
2530
- if (vfSvc && renameMap.has(vfSvc)) {
2531
- const newTarget = renameMap.get(vfSvc);
2532
- return mode ? `${newTarget}:${mode}` : newTarget;
2533
- }
2534
- return vf;
2535
- });
2536
- }
2537
- if (service.extends && typeof service.extends === "object") {
2538
- if (service.extends.service && renameMap.has(service.extends.service)) {
2539
- service.extends.service = renameMap.get(service.extends.service);
2540
- }
2541
- }
2542
- }
2543
- };
2544
- function findServiceDefinersInDeclaredFiles(buildJson, projectDir, serviceName) {
2545
- const declaredFiles = getDeclaredYamlFiles(buildJson, projectDir);
2546
- const hits = [];
2547
- for (const file of declaredFiles) {
2548
- if (!existsSync(file.absolutePath)) continue;
2549
- try {
2550
- const content = readFileSync(file.absolutePath, "utf-8");
2551
- const parsed = parse(content);
2552
- if (parsed && typeof parsed === "object" && parsed.services && typeof parsed.services === "object") {
2553
- const svc = parsed.services[serviceName];
2554
- if (svc) {
2555
- const hasImageOrBuild = Boolean(svc.image || svc.build);
2556
- hits.push(
2557
- ` - ${file.relativePath} (${file.source})${hasImageOrBuild ? " [defines image/build]" : " [no image/build]"}`
2558
- );
2559
- }
2560
- }
2561
- } catch {
2562
- }
2563
- }
2564
- return hits;
2565
- }
2566
- function explainComposeMergeFailure(buildJson, projectDir, envName, filesUsed, rawOutput) {
2567
- const lines = [];
2568
- const serviceMatch = rawOutput.match(
2569
- /service "([^"]+)" has neither an image nor a build context specified/
2570
- );
2571
- const envMissingMatch = /env file .* not found|no such file or directory.*\.env/i.test(rawOutput);
2572
- const actualComposeFiles = filesUsed.filter(
2573
- (f) => !f.startsWith("-") && (f.endsWith(".yml") || f.endsWith(".yaml"))
2574
- );
2575
- lines.push(`Environment : ${envName}`);
2576
- lines.push(`Compose files merged :`);
2577
- if (actualComposeFiles.length > 0) {
2578
- actualComposeFiles.forEach((f) => lines.push(` - ${f}`));
2579
- } else {
2580
- filesUsed.filter((f) => f !== "-f").forEach((f) => lines.push(` - ${f}`));
2581
- }
2582
- lines.push("");
2583
- if (serviceMatch && serviceMatch[1]) {
2584
- const serviceName = serviceMatch[1];
2585
- lines.push(
2586
- `ROOT CAUSE: Service "${serviceName}" is referenced in the merged stack, but none of the files provide an "image:" or "build:".`
2587
- );
2588
- lines.push("");
2589
- lines.push(
2590
- `Files declared in build.json that define a "${serviceName}:" service block:`
2591
- );
2592
- const definers = findServiceDefinersInDeclaredFiles(
2593
- buildJson,
2594
- projectDir,
2595
- serviceName
2596
- );
2597
- if (definers.length > 0) {
2598
- definers.forEach((d) => lines.push(d));
2599
- } else {
2600
- lines.push(
2601
- ` (none found \u2014 check spelling/indentation of "${serviceName}:" in files declared in build.json)`
2602
- );
2603
- }
2604
- lines.push("");
2605
- lines.push("HOW TO FIX:");
2606
- lines.push(
2607
- ` - Ensure the file declaring service "${serviceName}" with an "image:" or "build:" is referenced in build.json under dependencies or overrides.`
2608
- );
2609
- } else if (/env_file.*must be a string/i.test(rawOutput)) {
2610
- lines.push(
2611
- `ROOT CAUSE: Docker Compose schema error for env_file. Your Docker Compose version is likely older than 2.24.0, which does not support the object syntax { path, required: false }.`
2612
- );
2613
- lines.push("");
2614
- lines.push("HOW TO FIX:");
2615
- lines.push(
2616
- ` - Upgrade Docker Compose to version 2.24.0 or newer to support modern compose templates.`
2617
- );
2618
- } else if (/required variable "?([^"\s]+)"? is missing a value/i.test(rawOutput)) {
2619
- const varMatch = rawOutput.match(/required variable "?([^"\s]+)"? is missing a value/i);
2620
- const varName = varMatch ? varMatch[1] : "VARIABLE";
2621
- lines.push(
2622
- `ROOT CAUSE: Required environment variable "${varName}" is missing a value.`
2623
- );
2624
- lines.push("");
2625
- lines.push("HOW TO FIX:");
2626
- lines.push(
2627
- ` - Define "${varName}" in your shell environment or inside your .env file.`
2628
- );
2629
- } else if (/port is already allocated|address already in use/i.test(rawOutput)) {
2630
- lines.push(
2631
- `ROOT CAUSE: Host port collision. A requested host port is already allocated or in use by another running process or container.`
2632
- );
2633
- lines.push("");
2634
- lines.push("HOW TO FIX:");
2635
- lines.push(
2636
- ` - Stop the conflicting process or container, or change the exposed host port in build.json / compose overrides.`
2637
- );
2638
- } else if (envMissingMatch) {
2639
- lines.push(`ROOT CAUSE: A referenced .env file could not be found.`);
2640
- lines.push("");
2641
- lines.push("HOW TO FIX:");
2642
- lines.push(
2643
- ` - Create the missing env file at the project root (e.g. .env.dev, .env.prod, .env.test)`
2644
- );
2645
- } else {
2646
- lines.push(
2647
- "Docker Compose failed to resolve this merged stack. Common causes:"
2648
- );
2649
- lines.push(
2650
- ` - A "\${VAR}" substitution with no default and no value set in the shell or an env_file.`
2651
- );
2652
- lines.push(` - A YAML syntax error in one of the files listed in build.json.`);
2653
- lines.push(` - A duplicate or conflicting key across merged compose files.`);
2654
- }
2655
- lines.push("");
2656
- lines.push("Raw Docker Compose output:");
2657
- lines.push("-".repeat(60));
2658
- lines.push(rawOutput.trim());
2659
- lines.push("-".repeat(60));
2660
- return lines.join("\n");
2661
- }
2662
- var cachedTemplatesDir = null;
2663
- var lastEnvTemplatesDir = void 0;
2664
- function getTemplatesDir() {
2665
- const envVal = process.env.BUILDER_TEMPLATES_DIR;
2666
- if (envVal !== lastEnvTemplatesDir) {
2667
- cachedTemplatesDir = null;
2668
- lastEnvTemplatesDir = envVal;
2669
- }
2670
- if (envVal) {
2671
- const envDir = path13.resolve(envVal);
2672
- if (!fs.existsSync(envDir) || !fs.existsSync(path13.join(envDir, "docker"))) {
2673
- throw new ScriptError(
2674
- `BUILDER_TEMPLATES_DIR is set to "${envVal}" but directory does not exist or lacks a "docker/" subdirectory (resolved: "${envDir}").`
2675
- );
2676
- }
2677
- return envDir;
2678
- }
2679
- if (cachedTemplatesDir && fs.existsSync(cachedTemplatesDir)) {
2680
- return cachedTemplatesDir;
2681
- }
2682
- const currentDir = typeof __dirname !== "undefined" ? __dirname : path13.dirname(fileURLToPath(import.meta.url));
2683
- const candidates = [
2684
- // When executing compiled output in dist/ (e.g. dist/templates)
2685
- path13.resolve(currentDir, "templates"),
2686
- path13.resolve(currentDir, "../templates"),
2687
- // When executing from src/ (e.g. src/core/templates.ts -> ../../templates)
2688
- path13.resolve(currentDir, "../../templates"),
2689
- // Fallback relative to cwd
2690
- path13.resolve(process.cwd(), "templates")
2691
- ];
2692
- for (const cand of candidates) {
2693
- if (fs.existsSync(cand) && fs.existsSync(path13.join(cand, "docker"))) {
2694
- cachedTemplatesDir = cand;
2695
- return cand;
2696
- }
2697
- }
2698
- throw new ScriptError(
2699
- `Templates directory not found. Searched candidates:
2700
- ${candidates.join("\n")}`
2701
- );
2702
- }
2703
- function getDockerComposeTemplate(filename) {
2704
- const templatesDir = getTemplatesDir();
2705
- const filePath = path13.join(templatesDir, "docker", filename);
2706
- if (!fs.existsSync(filePath)) {
2707
- throw new ScriptError(`Docker compose template not found: ${filePath}`);
2708
- }
2709
- return filePath;
2710
- }
2711
-
2712
- // src/core/compileEnvironment.ts
2713
- var compileEnvironment = (environment, projectDir = process.cwd(), options = {}) => {
2714
- const absProjectDir = resolveProjectDir(projectDir);
2715
- const buildJson = getBuildJson(absProjectDir);
2716
- const overrides = extractOverrides(buildJson, absProjectDir);
2717
- const dependencies = extractBuildDeps(buildJson, absProjectDir);
2718
- const rawProjectName = buildJson.name || path13.basename(absProjectDir);
2719
- const projectName = deriveProjectName(rawProjectName, environment);
2720
- const baseComposePath = getDockerComposeTemplate("docker-compose.base.yml");
2721
- const composeFlags = [
2722
- "compose",
2723
- "-p",
2724
- projectName,
2725
- "--project-directory",
2726
- absProjectDir,
2727
- "-f",
2728
- baseComposePath
2729
- ];
2730
- const filesUsed = [baseComposePath];
2731
- const defaultEnv = path13.resolve(absProjectDir, ".env");
2732
- if (existsSync(defaultEnv)) {
2733
- composeFlags.push("--env-file", defaultEnv);
2734
- }
2735
- if (environment === "e2e") {
2736
- const prodEnv = path13.resolve(absProjectDir, ".env.prod");
2737
- if (existsSync(prodEnv)) {
2738
- composeFlags.push("--env-file", prodEnv);
2739
- }
2740
- const e2eEnv = path13.resolve(absProjectDir, ".env.e2e");
2741
- if (existsSync(e2eEnv)) {
2742
- composeFlags.push("--env-file", e2eEnv);
2743
- }
2744
- } else {
2745
- const stageEnv = path13.resolve(absProjectDir, `.env.${environment}`);
2746
- if (existsSync(stageEnv)) {
2747
- composeFlags.push("--env-file", stageEnv);
2748
- }
2749
- }
2750
- switch (environment) {
2751
- case "dev": {
2752
- const devPath = getDockerComposeTemplate("docker-compose.dev.yml");
2753
- const standalonePath = getDockerComposeTemplate("docker-compose.standalone.yml");
2754
- composeFlags.push("-f", devPath);
2755
- filesUsed.push(devPath);
2756
- if (overrides.dev) {
2757
- composeFlags.push("-f", overrides.dev.path);
2758
- filesUsed.push(overrides.dev.path);
2759
- }
2760
- if (options.full && dependencies.length > 0) {
2761
- for (const dep of dependencies) {
2762
- composeFlags.push("-f", dep.path);
2763
- filesUsed.push(dep.path);
2764
- }
2765
- }
2766
- composeFlags.push("-f", standalonePath);
2767
- filesUsed.push(standalonePath);
2768
- break;
2769
- }
2770
- case "test": {
2771
- const testPath = getDockerComposeTemplate("docker-compose.test.yml");
2772
- composeFlags.push("-f", testPath);
2773
- filesUsed.push(testPath);
2774
- if (overrides.test) {
2775
- composeFlags.push("-f", overrides.test.path);
2776
- filesUsed.push(overrides.test.path);
2777
- }
2778
- break;
2779
- }
2780
- case "prod": {
2781
- const prodPath = getDockerComposeTemplate("docker-compose.prod.yml");
2782
- const standalonePath = getDockerComposeTemplate("docker-compose.standalone.yml");
2783
- composeFlags.push("-f", prodPath);
2784
- filesUsed.push(prodPath);
2785
- if (overrides.prod) {
2786
- composeFlags.push("-f", overrides.prod.path);
2787
- filesUsed.push(overrides.prod.path);
2788
- }
2789
- if (dependencies.length > 0) {
2790
- for (const dep of dependencies) {
2791
- composeFlags.push("-f", dep.path);
2792
- filesUsed.push(dep.path);
2793
- }
2794
- }
2795
- composeFlags.push("-f", standalonePath);
2796
- filesUsed.push(standalonePath);
2797
- break;
2798
- }
2799
- case "e2e": {
2800
- const prodPath = getDockerComposeTemplate("docker-compose.prod.yml");
2801
- const e2ePath = getDockerComposeTemplate("docker-compose.e2e.yml");
2802
- const standalonePath = getDockerComposeTemplate("docker-compose.standalone.yml");
2803
- composeFlags.push("-f", prodPath);
2804
- filesUsed.push(prodPath);
2805
- if (overrides.prod) {
2806
- composeFlags.push("-f", overrides.prod.path);
2807
- filesUsed.push(overrides.prod.path);
2808
- }
2809
- if (dependencies.length > 0) {
2810
- for (const dep of dependencies) {
2811
- composeFlags.push("-f", dep.path);
2812
- filesUsed.push(dep.path);
2813
- }
2814
- }
2815
- composeFlags.push("-f", standalonePath);
2816
- filesUsed.push(standalonePath);
2817
- composeFlags.push("-f", e2ePath);
2818
- filesUsed.push(e2ePath);
2819
- if (overrides.e2e) {
2820
- composeFlags.push("-f", overrides.e2e.path);
2821
- filesUsed.push(overrides.e2e.path);
2822
- }
2823
- break;
2824
- }
2825
- }
2826
- composeFlags.push("config");
2827
- const envVars = { ...process.env };
2828
- if (buildJson.port) {
2829
- envVars.PUBLIC_PORT = String(buildJson.port);
2830
- }
2831
- envVars.PORT = "3000";
2832
- const result = spawnSync("docker", composeFlags, {
2833
- cwd: absProjectDir,
2834
- encoding: "utf-8",
2835
- env: envVars
2836
- });
2837
- if (result.error) {
2838
- throw new ScriptError(
2839
- `Failed to run docker compose: ${result.error.message}`,
2840
- { cause: result.error }
2841
- );
2842
- }
2843
- if (result.status !== 0) {
2844
- const rawOutput = result.stderr || result.stdout;
2845
- const explanation = explainComposeMergeFailure(
2846
- buildJson,
2847
- absProjectDir,
2848
- environment,
2849
- filesUsed,
2850
- rawOutput
2851
- );
2852
- throw new ScriptError(`\u274C Failed to merge compose files:
2853
- ${explanation}`);
2854
- }
2855
- const mergedYamlConfig = result.stdout;
2856
- const yml = parse(mergedYamlConfig);
2857
- if (environment === "prod" || environment === "e2e" || environment === "dev" && options.full) {
2858
- renameServicesWithDependencies(yml, dependencies);
2859
- addDependenciesToAppService(yml, dependencies);
2860
- }
2861
- if (environment === "e2e") {
2862
- makeE2eDependOnApp(yml);
2863
- }
2864
- const INTERNAL_PORT = 3e3;
2865
- const urlRegistry = /* @__PURE__ */ new Map();
2866
- const appPublicPort = buildJson.port ? Number(buildJson.port) : null;
2867
- urlRegistry.set("app", {
2868
- networkUrl: `http://app:${INTERNAL_PORT}`,
2869
- publicUrl: appPublicPort ? `http://localhost:${appPublicPort}` : null
2870
- });
2871
- if (buildJson.name && buildJson.name !== "app") {
2872
- urlRegistry.set(buildJson.name, urlRegistry.get("app"));
2873
- }
2874
- for (const dep of dependencies) {
2875
- const depPortStr = dep.port ? String(dep.port) : null;
2876
- const depHostPort = depPortStr ? depPortStr.includes(":") ? depPortStr.split(":")[0] : depPortStr : null;
2877
- urlRegistry.set(dep.name, {
2878
- networkUrl: `http://${dep.name}:${INTERNAL_PORT}`,
2879
- publicUrl: depHostPort ? `http://localhost:${depHostPort}` : null
2880
- });
2881
- }
2882
- const interpolateEnv = (val, context) => {
2883
- if (!options.silenceWarnings && context.includes("Tester") && val.includes(".network_url")) {
2884
- console.warn(
2885
- pc22.yellow(`
2886
- \u26A0\uFE0F WARNING: You are passing a '.network_url' template to the E2E tester ("${val}"). Since the tester runs in 'network_mode: host', it cannot resolve internal Docker DNS. Use '.public_url' instead. (Mute with --silence-warnings)
2887
- `)
2888
- );
2889
- }
2890
- let output = val;
2891
- for (const [sName, urls] of urlRegistry.entries()) {
2892
- const escaped = sName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2893
- output = output.replace(
2894
- new RegExp(`\\$\\{${escaped}\\.network_url\\}`, "g"),
2895
- urls.networkUrl
2896
- );
2897
- if (urls.publicUrl) {
2898
- output = output.replace(
2899
- new RegExp(`\\$\\{${escaped}\\.public_url\\}`, "g"),
2900
- urls.publicUrl
2901
- );
2902
- }
2903
- }
2904
- const unresolvedMatch = output.match(/\$\{([^}]+?)\.(network_url|public_url)\}/);
2905
- if (unresolvedMatch) {
2906
- const variable = unresolvedMatch[0];
2907
- const targetService = unresolvedMatch[1];
2908
- const type = unresolvedMatch[2];
2909
- if (!urlRegistry.has(targetService)) {
2910
- throw new ScriptError(
2911
- `[${context}] Unresolved template variable: ${variable}. Check build.json dependencies.`
2912
- );
2913
- } else if (type === "public_url") {
2914
- throw new ScriptError(
2915
- `[${context}] Unresolved template variable: ${variable}. Service "${targetService}" does not expose a public port (missing 'port' explicitly defined in build.json).`
2916
- );
2917
- } else {
2918
- throw new ScriptError(`[${context}] Unresolved template variable: ${variable}.`);
2919
- }
2920
- }
2921
- return output;
2922
- };
2923
- const normalizeEnvironment = (serviceConfig) => {
2924
- if (Array.isArray(serviceConfig.environment)) {
2925
- const envObj = {};
2926
- for (const item of serviceConfig.environment) {
2927
- if (typeof item === "string") {
2928
- const eqIdx = item.indexOf("=");
2929
- if (eqIdx !== -1) {
2930
- envObj[item.slice(0, eqIdx)] = item.slice(eqIdx + 1);
2931
- } else {
2932
- envObj[item] = process.env[item] ?? null;
2933
- }
2934
- }
2935
- }
2936
- serviceConfig.environment = envObj;
2937
- } else if (!serviceConfig.environment || typeof serviceConfig.environment !== "object") {
2938
- serviceConfig.environment = {};
2939
- }
2940
- };
2941
- const normalizeBuildArgs = (serviceConfig) => {
2942
- if (typeof serviceConfig.build === "string") {
2943
- serviceConfig.build = {
2944
- context: serviceConfig.build
2945
- };
2946
- }
2947
- if (serviceConfig.build && typeof serviceConfig.build === "object") {
2948
- if (Array.isArray(serviceConfig.build.args)) {
2949
- const argsObj = {};
2950
- for (const item of serviceConfig.build.args) {
2951
- if (typeof item === "string") {
2952
- const eqIdx = item.indexOf("=");
2953
- if (eqIdx !== -1) {
2954
- argsObj[item.slice(0, eqIdx)] = item.slice(eqIdx + 1);
2955
- } else {
2956
- argsObj[item] = process.env[item] ?? null;
2957
- }
2958
- }
2959
- }
2960
- serviceConfig.build.args = argsObj;
2961
- } else if (!serviceConfig.build.args || typeof serviceConfig.build.args !== "object") {
2962
- serviceConfig.build.args = {};
2963
- }
2964
- }
2965
- };
2966
- if (buildJson.envOverrides && yml.services && yml.services.app) {
2967
- normalizeEnvironment(yml.services.app);
2968
- normalizeBuildArgs(yml.services.app);
2969
- for (const [k, v] of Object.entries(buildJson.envOverrides)) {
2970
- const val = interpolateEnv(v, "App EnvOverrides");
2971
- yml.services.app.environment[k] = val;
2972
- if (yml.services.app.build?.args) {
2973
- yml.services.app.build.args[k] = val;
2974
- }
2975
- }
2976
- }
2977
- if (buildJson.tester?.envOverrides && yml.services && yml.services.tester) {
2978
- normalizeEnvironment(yml.services.tester);
2979
- normalizeBuildArgs(yml.services.tester);
2980
- for (const [k, v] of Object.entries(buildJson.tester.envOverrides)) {
2981
- const val = interpolateEnv(v, "Tester EnvOverrides");
2982
- yml.services.tester.environment[k] = val;
2983
- if (yml.services.tester.build?.args) {
2984
- yml.services.tester.build.args[k] = val;
2985
- }
2986
- }
2987
- }
2988
- if (yml.services && (environment === "prod" || environment === "e2e" || environment === "dev" && options.full)) {
2989
- for (const dep of dependencies) {
2990
- const mappings = getDependencyPortMappings(dep, `Dependency "${dep.name}"`);
2991
- let targetSvc = dep.serviceName && yml.services[dep.serviceName] ? dep.serviceName : dep.name;
2992
- if (!yml.services[targetSvc]) {
2993
- targetSvc = Object.keys(yml.services).find((key) => key !== "app" && key !== "tester") ?? targetSvc;
2994
- }
2995
- const service = yml.services[targetSvc];
2996
- if (!service) {
2997
- throw new ScriptError(`Dependency "${dep.name}" target service could not be resolved for port injection.`);
2998
- }
2999
- delete service.ports;
3000
- if (mappings.length > 0) service.ports = mappings.map((mapping) => mapping.raw);
3001
- }
3002
- }
3003
- if (environment === "dev" && options.full && yml.services?.app) {
3004
- normalizeEnvironment(yml.services.app);
3005
- yml.services.app.environment.INFRA_MODE = "integrated";
3006
- }
3007
- attachName(yml, projectName);
3008
- const finalYamlConfig = stringify(yml);
3009
- assertUniqueHostPortMappings(finalYamlConfig);
3010
- return finalYamlConfig;
3011
- };
3012
-
3013
- // src/core/runners/runTestUnit.ts
3014
- var runTestUnit = async (options) => {
3015
- if (!options.skipBanner) {
3016
- console.log(pc22.bold(pc22.blue(`
3017
- ========================================`)));
3018
- console.log(pc22.bold(pc22.blue(`\u{1F9EA} STAGE: UNIT & ISOLATED TESTS`)));
3019
- console.log(pc22.bold(pc22.blue(`========================================
3020
- `)));
3021
- }
3022
- const finalYamlConfig = compileEnvironment("test", options.projectDir, {
3023
- silenceWarnings: options.silenceWarnings
3024
- });
3025
- const parsed = parse(finalYamlConfig);
3026
- const projectName = parsed?.name || "test";
3027
- if (options.debug) {
3028
- console.log(
3029
- pc22.yellow("Final merged YAML configuration:\n"),
3030
- redactYamlSecrets(finalYamlConfig)
3031
- );
3032
- }
3033
- if (options.dryRun) {
3034
- console.log(pc22.green("[DRY-RUN] Unit tests simulated. Compose was not started."));
3035
- return 0;
3036
- }
3037
- await teardownCompose(finalYamlConfig, options.projectDir, {
3038
- removeVolumes: true,
3039
- silent: true
3040
- });
3041
- writeRunState(options.projectDir, {
3042
- projectName,
3043
- stage: "test-unit",
3044
- projectDir: options.projectDir
3045
- });
3046
- let status = 0;
3047
- try {
3048
- status = await runCompose(
3049
- ["up", "--build", "--abort-on-container-exit", "--exit-code-from", "app"],
3050
- finalYamlConfig,
3051
- options.projectDir,
3052
- { removeVolumes: true }
3053
- );
3054
- } finally {
3055
- await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
3056
- clearRunState(options.projectDir);
3057
- }
3058
- if (status === 0) {
3059
- console.log(pc22.bold(pc22.green(`
3060
- \u2705 Unit tests passed successfully.
3061
- `)));
3062
- } else {
3063
- console.error(pc22.red(`
3064
- \u274C Unit tests failed with exit code ${status}.
3065
- `));
3066
- }
3067
- return status;
3068
- };
3069
- var runTestE2e = async (options) => {
3070
- if (!options.skipBanner) {
3071
- console.log(pc22.bold(pc22.blue(`
3072
- ========================================`)));
3073
- console.log(pc22.bold(pc22.blue(`\u{1F6A6} STAGE: INTEGRATED E2E TESTS`)));
3074
- console.log(pc22.bold(pc22.blue(`========================================
3075
- `)));
3076
- }
3077
- const finalYamlConfig = compileEnvironment("e2e", options.projectDir, {
3078
- silenceWarnings: options.silenceWarnings
3079
- });
3080
- const parsed = parse(finalYamlConfig);
3081
- const projectName = parsed?.name || "e2e";
3082
- if (options.debug) {
3083
- console.log(
3084
- pc22.yellow("Final merged YAML configuration:\n"),
3085
- redactYamlSecrets(finalYamlConfig)
3086
- );
3087
- }
3088
- if (options.dryRun) {
3089
- console.log(pc22.green("[DRY-RUN] E2E tests simulated. Compose was not started."));
3090
- return 0;
3091
- }
3092
- await teardownCompose(finalYamlConfig, options.projectDir, {
3093
- removeVolumes: true,
3094
- silent: true
3095
- });
3096
- writeRunState(options.projectDir, {
3097
- projectName,
3098
- stage: "test-e2e",
3099
- projectDir: options.projectDir
3100
- });
3101
- let status = 0;
3102
- try {
3103
- status = await runCompose(
3104
- [
3105
- "up",
3106
- "--build",
3107
- "--abort-on-container-exit",
3108
- "--exit-code-from",
3109
- "tester"
3110
- ],
3111
- finalYamlConfig,
3112
- options.projectDir,
3113
- { removeVolumes: true }
3114
- );
3115
- } finally {
3116
- await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
3117
- clearRunState(options.projectDir);
3118
- }
3119
- if (status === 0) {
3120
- console.log(pc22.bold(pc22.green(`
3121
- \u2705 E2E tests passed successfully.
3122
- `)));
3123
- } else {
3124
- console.error(pc22.red(`
3125
- \u274C E2E tests failed with exit code ${status}.
3126
- `));
3127
- }
3128
- return status;
3129
- };
3130
-
3131
- // src/core/runners/runTest.ts
3132
- var runTest = async (options) => {
3133
- console.log(pc22.bold(pc22.blue(`
3134
- ========================================`)));
3135
- console.log(pc22.bold(pc22.blue(`\u{1F9EA} [1/2] STAGE: UNIT & ISOLATED TESTS`)));
3136
- console.log(pc22.bold(pc22.blue(`========================================
3137
- `)));
3138
- const unitStatus = await runTestUnit({ ...options, skipBanner: true });
3139
- if (unitStatus !== 0) {
3140
- console.error(
3141
- pc22.red(
3142
- `
3143
- \u274C [1/2] Unit tests failed with exit code ${unitStatus}. Aborting E2E tests.
3144
- `
3145
- )
3146
- );
3147
- return unitStatus;
3148
- }
3149
- console.log(
3150
- pc22.bold(pc22.green(`
3151
- \u2705 [1/2] Unit tests passed successfully.
3152
- `))
3153
- );
3154
- console.log(pc22.bold(pc22.blue(`========================================`)));
3155
- console.log(pc22.bold(pc22.blue(`\u{1F6A6} [2/2] STAGE: INTEGRATED E2E TESTS`)));
3156
- console.log(pc22.bold(pc22.blue(`========================================
3157
- `)));
3158
- const e2eStatus = await runTestE2e({ ...options, skipBanner: true });
3159
- if (e2eStatus !== 0) {
3160
- console.error(
3161
- pc22.red(`
3162
- \u274C [2/2] E2E tests failed with exit code ${e2eStatus}.
3163
- `)
3164
- );
3165
- return e2eStatus;
3166
- }
3167
- console.log(pc22.bold(pc22.green(`
3168
- \u2705 [2/2] E2E tests passed successfully.
3169
- `)));
3170
- console.log(
3171
- pc22.bold(
3172
- pc22.green(`\u{1F389} All test stages (unit + e2e) completed successfully!
3173
- `)
3174
- )
3175
- );
3176
- return 0;
3177
- };
3178
- async function runMeshTestE2e(options = {}) {
3179
- const meshDir = resolveProjectDir(options.projectDir);
3180
- console.log(pc22.bold(pc22.blue(`
3181
- ========================================`)));
3182
- console.log(pc22.bold(pc22.blue(`\u{1F6A6} [MESH] STAGE: GLOBAL INTEGRATED E2E TESTS`)));
3183
- console.log(pc22.bold(pc22.blue(`========================================
3184
- `)));
3185
- if (!options.skipChecks) {
3186
- checkMesh(meshDir, { requireTester: true });
3187
- }
3188
- const { yaml, testerServiceName } = compileMeshEnvironment("prod", meshDir, {
3189
- includeTester: true,
3190
- silenceWarnings: options.silenceWarnings
3191
- });
3192
- if (!testerServiceName) {
3193
- throw new ScriptError(
3194
- "No tester service could be identified in the tester docker compose configuration."
3195
- );
3196
- }
3197
- if (options.debug) {
3198
- console.log(
3199
- pc22.yellow("\nFinal merged Mesh E2E YAML configuration:\n"),
3200
- redactYamlSecrets(yaml)
3201
- );
3202
- }
3203
- if (options.dryRun) {
3204
- console.log(pc22.green("[DRY-RUN] Global E2E test simulated. Compose was not started."));
3205
- return 0;
3206
- }
3207
- const parsed = parse(yaml);
3208
- const projectName = parsed?.name || "mesh-e2e";
3209
- await teardownCompose(yaml, meshDir, { removeVolumes: true, silent: true });
3210
- writeRunState(meshDir, {
3211
- projectName,
3212
- stage: "test-e2e",
3213
- projectDir: meshDir
3214
- });
3215
- let status = 0;
3216
- try {
3217
- status = await runCompose(
3218
- [
3219
- "up",
3220
- "--build",
3221
- "--abort-on-container-exit",
3222
- "--exit-code-from",
3223
- testerServiceName
3224
- ],
3225
- yaml,
3226
- meshDir,
3227
- { removeVolumes: true }
3228
- );
3229
- } finally {
3230
- console.log(pc22.cyan("\n\u{1F9F9} Cleaning up global mesh containers and volumes..."));
3231
- await teardownCompose(yaml, meshDir, { removeVolumes: true });
3232
- clearRunState(meshDir);
3233
- }
3234
- if (status === 0) {
3235
- console.log(pc22.bold(pc22.green(`
3236
- \u2705 Global E2E tests passed successfully.
3237
- `)));
3238
- } else {
3239
- console.error(pc22.red(`
3240
- \u274C Global E2E tests failed with exit code ${status}.
3241
- `));
3242
- }
3243
- return status;
3244
- }
3245
-
3246
- // src/core/mesh/runners/runMeshTest.ts
3247
- async function runMeshTest(options = {}) {
3248
- const meshDir = resolveProjectDir(options.projectDir);
3249
- console.log(pc22.bold(pc22.blue(`
3250
- ========================================`)));
3251
- console.log(pc22.bold(pc22.blue(`\u{1F9EA} GLOBAL MESH TEST PIPELINE`)));
3252
- console.log(pc22.bold(pc22.blue(`========================================
3253
- `)));
3254
- if (!options.skipChecks) {
3255
- checkMesh(meshDir, { requireTester: true });
3256
- }
3257
- const mesh = getMeshJson(meshDir);
3258
- console.log(pc22.bold(pc22.blue(`
3259
- ========================================`)));
3260
- console.log(
3261
- pc22.bold(
3262
- pc22.blue(`\u{1F9EA} [1/2] STAGE: LOCAL SUBMODULE TEST SUITES (Unit & Isolated E2E)`)
3263
- )
3264
- );
3265
- console.log(pc22.bold(pc22.blue(`========================================
3266
- `)));
3267
- for (const [serviceName, serviceConfig] of Object.entries(mesh.services)) {
3268
- const serviceDir = path13.resolve(meshDir, serviceConfig.path);
3269
- console.log(
3270
- pc22.bold(pc22.cyan(`
3271
- -> Running full test suite for [${serviceName}] in isolation...`))
3272
- );
3273
- if (options.dryRun) {
3274
- console.log(
3275
- pc22.green(`[DRY-RUN] Full isolated tests for ${serviceName} simulated.`)
3276
- );
3277
- continue;
3278
- }
3279
- const serviceStatus = await runTest({
3280
- projectDir: serviceDir,
3281
- debug: Boolean(options.debug),
3282
- detach: Boolean(options.detach),
3283
- silenceWarnings: options.silenceWarnings
3284
- });
3285
- if (serviceStatus !== 0) {
3286
- console.error(
3287
- pc22.red(
3288
- `
3289
- \u274C Isolated tests failed for service [${serviceName}] with exit code ${serviceStatus}. Aborting global E2E tests.
3290
- `
3291
- )
3292
- );
3293
- return serviceStatus;
3294
- }
2264
+ console.log(pc22.cyan(`
2265
+ \u{1F3ED} Starting Global PROD Mesh Environment...`));
2266
+ const { yaml } = compileMeshEnvironment("prod", meshDir);
2267
+ const parsed = parse(yaml);
2268
+ const projectName = parsed?.name || "mesh-prod";
2269
+ if (options.debug) {
3295
2270
  console.log(
3296
- pc22.bold(pc22.green(`
3297
- \u2705 Isolated tests passed for service: [${serviceName}]
3298
- `))
2271
+ pc22.yellow("\nFinal merged Mesh Prod YAML configuration:\n"),
2272
+ redactYamlSecrets(yaml)
3299
2273
  );
3300
2274
  }
3301
- console.log(pc22.bold(pc22.blue(`
3302
- ========================================`)));
3303
- console.log(
3304
- pc22.bold(
3305
- pc22.blue(`\u{1F6A6} [2/2] STAGE: INTEGRATED PRODUCTION MESH & GLOBAL E2E ASSERTIONS`)
3306
- )
3307
- );
3308
- console.log(pc22.bold(pc22.blue(`========================================
3309
- `)));
3310
- const e2eStatus = await runMeshTestE2e({ ...options, skipChecks: true });
3311
- if (e2eStatus !== 0) {
3312
- return e2eStatus;
2275
+ if (options.dryRun) {
2276
+ console.log(pc22.green("Dry run complete. Compose was not started."));
2277
+ return 0;
3313
2278
  }
3314
- console.log(
3315
- pc22.bold(
3316
- pc22.green(`\u{1F389} Entire global mesh test pipeline (unit, local e2e, and global e2e) completed successfully!
3317
- `)
3318
- )
3319
- );
3320
- return 0;
2279
+ const hostPorts = extractHostPorts(yaml);
2280
+ await checkHostPortCollisions(hostPorts);
2281
+ writeRunState(meshDir, {
2282
+ projectName,
2283
+ anonymousVolumeServices: anonymousVolumeServices(parsed?.services ?? {}),
2284
+ stage: "prod",
2285
+ projectDir: meshDir
2286
+ });
2287
+ const upArgs = ["up", "--build"];
2288
+ if (options.detach) {
2289
+ upArgs.push("-d");
2290
+ }
2291
+ let status = 0;
2292
+ try {
2293
+ status = await runCompose(upArgs, yaml, meshDir, {
2294
+ removeVolumes: false
2295
+ });
2296
+ } finally {
2297
+ if (!options.detach) {
2298
+ await teardownCompose(yaml, meshDir, { removeVolumes: false });
2299
+ clearRunState(meshDir);
2300
+ }
2301
+ }
2302
+ return status;
3321
2303
  }
3322
2304
  async function runMeshTestUnit(options = {}) {
3323
- const meshDir = resolveProjectDir(options.projectDir);
3324
- console.log(pc22.bold(pc22.blue(`
3325
- ========================================`)));
3326
- console.log(pc22.bold(pc22.blue(`\u{1F9EA} [MESH] STAGE: ISOLATED UNIT TESTS`)));
3327
- console.log(pc22.bold(pc22.blue(`========================================
3328
- `)));
3329
- if (!options.skipChecks) {
3330
- checkMesh(meshDir, { requireTester: false });
3331
- }
3332
- const mesh = getMeshJson(meshDir);
3333
- for (const [serviceName, serviceConfig] of Object.entries(mesh.services)) {
3334
- const serviceDir = path13.resolve(meshDir, serviceConfig.path);
3335
- console.log(
3336
- pc22.cyan(`
3337
- -> Running isolated unit tests for service: [${serviceName}]...`)
3338
- );
2305
+ const meshDir = resolveProjectDir(options.projectDir), meshPath = path.join(meshDir, "mesh.json"), raw = getMeshJson(meshDir), effective = resolveMeshStage(raw, "test", meshPath), services = loadEffectiveMeshServices(meshDir, effective, "test");
2306
+ console.log(pc22.bold(pc22.blue("\n[1/2] MESH SERVICE UNIT/ISOLATED TESTS\n")));
2307
+ for (const [name, svc] of Object.entries(services).sort(([a], [b]) => a.localeCompare(b))) {
2308
+ console.log(pc22.cyan(`-> Running isolated unit tests for [${name}]`));
2309
+ const compiled = compileServiceComposition("test", svc.absolutePath, { meshMode: true, full: false, externalAppEnv: {}, deferReferenceResolution: true, appServiceName: "app" });
2310
+ const endpoints = { app: { [name]: compiled.endpoints.app }, dependencies: { [name]: compiled.endpoints.dependencies } };
2311
+ const refCtx = { services: { [name]: svc }, bindings: /* @__PURE__ */ new Map(), endpoints, stage: "test", meshJsonPath: meshPath };
2312
+ const env = svc.meshEnv;
2313
+ for (const key of ["EXEC_MODE", "INFRA_MODE", ...Object.keys(svc.effectiveBuild.app.endpoints).some((k) => svc.effectiveBuild.app.endpoints[k]?.primary) ? ["PORT"] : []]) if (key in env) throw new ConfigError({ sourceFile: meshPath, configPath: `services.${name}.env.${key}`, stage: "test", composition: "mesh", reason: "Mesh service env cannot set Builder-owned environment" });
2314
+ const resolvedBuild = resolveServiceBuildEnvThroughMesh(name, compiled.builderAppEnvironment ?? {}, refCtx, `services.${name}.app.env`);
2315
+ for (const [depName, depEnv] of Object.entries(compiled.dependencyEnvironments ?? {})) resolveServiceBuildEnvThroughMesh(name, depEnv, refCtx, `services.${name}.dependencies.${depName}.env`);
2316
+ const resolved = resolveMeshEnvMap(env, refCtx, `services.${name}.env`);
2317
+ const app = compiled.compose.services.app;
2318
+ app.environment = { ...app.environment, ...resolvedBuild, ...resolved };
2319
+ const projectName = `${deriveProjectName(raw.name ?? path.basename(meshDir), "dev")}-${name}-test`;
2320
+ compiled.compose.name = projectName;
2321
+ const yaml = stringify(compiled.compose);
2322
+ if (options.debug) console.log(yaml);
3339
2323
  if (options.dryRun) {
3340
- console.log(pc22.green(`[DRY-RUN] Unit tests for ${serviceName} simulated.`));
2324
+ console.log(pc22.green(`[DRY-RUN] Unit tests for ${name} compiled.`));
3341
2325
  continue;
3342
2326
  }
3343
- const unitStatus = await runTestUnit({
3344
- projectDir: serviceDir,
3345
- debug: Boolean(options.debug),
3346
- detach: Boolean(options.detach),
3347
- skipBanner: true
3348
- });
3349
- if (unitStatus !== 0) {
3350
- console.error(
3351
- pc22.red(`
3352
- \u274C Unit tests failed for service [${serviceName}] with exit code ${unitStatus}.
3353
- `)
3354
- );
3355
- return unitStatus;
2327
+ await teardownCompose(yaml, svc.absolutePath, { removeVolumes: true, silent: true });
2328
+ writeRunState(svc.absolutePath, { projectName, stage: "test-unit", projectDir: svc.absolutePath });
2329
+ let status;
2330
+ try {
2331
+ status = await runCompose(["up", "--build", "--abort-on-container-exit", "--exit-code-from", "app"], yaml, svc.absolutePath, { removeVolumes: true });
2332
+ } finally {
2333
+ await teardownCompose(yaml, svc.absolutePath, { removeVolumes: true });
2334
+ clearRunState(svc.absolutePath);
3356
2335
  }
3357
- console.log(
3358
- pc22.bold(pc22.green(`
3359
- \u2705 Isolated unit tests passed for service: [${serviceName}]
3360
- `))
3361
- );
2336
+ if (status !== 0) return status;
3362
2337
  }
3363
- console.log(
3364
- pc22.bold(pc22.green(`\u{1F389} All mesh service unit tests completed successfully!
3365
- `))
3366
- );
3367
2338
  return 0;
3368
2339
  }
2340
+ async function runMeshTestE2e(options = {}) {
2341
+ const meshDir = resolveProjectDir(options.projectDir), mesh = getMeshJson(meshDir);
2342
+ if (!mesh.tester) throw new ScriptError("Global mesh E2E requires root mesh.json.tester { compose, service, env? }");
2343
+ const { yaml, testerServiceName } = compileMeshEnvironment("e2e", meshDir);
2344
+ if (!testerServiceName) throw new ScriptError("Global mesh E2E tester runner could not be compiled.");
2345
+ if (options.debug) console.log(pc22.yellow("\nFinal global mesh E2E YAML configuration:\n"), redactYamlSecrets(yaml));
2346
+ if (options.dryRun) {
2347
+ console.log(pc22.green("[DRY-RUN] Global mesh E2E compiled; Compose was not started."));
2348
+ return 0;
2349
+ }
2350
+ await checkHostPortCollisions(extractHostPorts(yaml));
2351
+ const projectName = parse(yaml)?.name || "mesh-e2e";
2352
+ await teardownCompose(yaml, meshDir, { removeVolumes: true, silent: true });
2353
+ writeRunState(meshDir, { projectName, stage: "test-e2e", projectDir: meshDir });
2354
+ let status = 0;
2355
+ try {
2356
+ status = await runCompose(["up", "--build", "--abort-on-container-exit", "--exit-code-from", testerServiceName], yaml, meshDir, { removeVolumes: true });
2357
+ } finally {
2358
+ await teardownCompose(yaml, meshDir, { removeVolumes: true });
2359
+ clearRunState(meshDir);
2360
+ }
2361
+ return status;
2362
+ }
2363
+
2364
+ // src/core/mesh/runners/runMeshTest.ts
2365
+ async function runMeshTest(options = {}) {
2366
+ console.log(pc22.bold(pc22.blue("\n========================================\nMESH TEST PIPELINE\n========================================\n")));
2367
+ console.log(pc22.bold(pc22.blue("[1/2] MESH SERVICE UNIT/ISOLATED TESTS")));
2368
+ const unitStatus = await runMeshTestUnit(options);
2369
+ if (unitStatus !== 0) return unitStatus;
2370
+ console.log(pc22.bold(pc22.blue("[2/2] GLOBAL MESH E2E")));
2371
+ return runMeshTestE2e(options);
2372
+ }
3369
2373
 
3370
2374
  // src/commands/mesh/commands/up/handler.ts
3371
2375
  async function handleMeshUp(rawStage = "dev", options = {}) {
@@ -3375,6 +2379,9 @@ async function handleMeshUp(rawStage = "dev", options = {}) {
3375
2379
  ...options,
3376
2380
  projectDir
3377
2381
  };
2382
+ if (["dev", "prod", "test-unit", "test-e2e", "test"].includes(stage) && !options.skipChecks) {
2383
+ checkMesh(projectDir, { requireTester: stage === "test-e2e" || stage === "test" });
2384
+ }
3378
2385
  switch (stage) {
3379
2386
  case "dev":
3380
2387
  return await runMeshDev(runOptions);
@@ -3417,7 +2424,10 @@ Examples:
3417
2424
  $ builder mesh up prod
3418
2425
  $ builder mesh up test
3419
2426
  $ builder mesh up test-unit
3420
- $ builder mesh up test-e2e`
2427
+ $ builder mesh up test-e2e
2428
+
2429
+ JSON overlays: test-unit uses mesh/build test; test-e2e uses mesh/build e2e.
2430
+ The test command runs per-service unit tests before global E2E.`
3421
2431
  ).action(
3422
2432
  async (stage = "dev", options = {}) => {
3423
2433
  const exitCode = await handleMeshUp(stage, {
@@ -3425,8 +2435,7 @@ Examples:
3425
2435
  debug: options.debug,
3426
2436
  detach: options.detach,
3427
2437
  dryRun: options.dryRun,
3428
- skipChecks: options.skipChecks,
3429
- silenceWarnings: options.silenceWarnings
2438
+ skipChecks: options.skipChecks
3430
2439
  });
3431
2440
  if (exitCode !== 0) {
3432
2441
  process.exit(exitCode);
@@ -3487,6 +2496,9 @@ var registerPruneCommand = (cmd) => {
3487
2496
  }
3488
2497
  });
3489
2498
  };
2499
+ var compileEnvironment = (stage, projectDir = process.cwd(), options = {}) => stringify(compileServiceComposition(stage, projectDir, { full: Boolean(options.full), silenceWarnings: options.silenceWarnings }).compose);
2500
+
2501
+ // src/commands/service/commands/down/handler.ts
3490
2502
  async function handleServiceDown(rawStage = "dev", options = {}) {
3491
2503
  const projectDir = resolveProjectDir(options.projectDir);
3492
2504
  const stage = (rawStage || "dev").toLowerCase();
@@ -3523,6 +2535,7 @@ async function handleServiceDown(rawStage = "dev", options = {}) {
3523
2535
  for (const proj of uniqueProjects) {
3524
2536
  await teardownCompose("", projectDir, {
3525
2537
  projectName: proj,
2538
+ ...runState?.projectName === proj && runState.anonymousVolumeServices ? { anonymousVolumeServices: runState.anonymousVolumeServices } : {},
3526
2539
  removeVolumes: Boolean(options.volumes)
3527
2540
  });
3528
2541
  }
@@ -3591,6 +2604,7 @@ var runDev = async (options) => {
3591
2604
  await checkHostPortCollisions(hostPorts);
3592
2605
  writeRunState(options.projectDir, {
3593
2606
  projectName,
2607
+ anonymousVolumeServices: anonymousVolumeServices(parsed?.services ?? {}),
3594
2608
  stage: "dev",
3595
2609
  projectDir: options.projectDir
3596
2610
  });
@@ -3634,6 +2648,7 @@ var runProd = async (options) => {
3634
2648
  await checkHostPortCollisions(hostPorts);
3635
2649
  writeRunState(options.projectDir, {
3636
2650
  projectName,
2651
+ anonymousVolumeServices: anonymousVolumeServices(parsed?.services ?? {}),
3637
2652
  stage: "prod",
3638
2653
  projectDir: options.projectDir
3639
2654
  });
@@ -3656,12 +2671,178 @@ var runProd = async (options) => {
3656
2671
  }
3657
2672
  return status;
3658
2673
  };
2674
+ var runTestUnit = async (options) => {
2675
+ if (!options.skipBanner) {
2676
+ console.log(pc22.bold(pc22.blue(`
2677
+ ========================================`)));
2678
+ console.log(pc22.bold(pc22.blue(`\u{1F9EA} STAGE: UNIT & ISOLATED TESTS`)));
2679
+ console.log(pc22.bold(pc22.blue(`========================================
2680
+ `)));
2681
+ }
2682
+ const finalYamlConfig = compileEnvironment("test", options.projectDir, {
2683
+ silenceWarnings: options.silenceWarnings
2684
+ });
2685
+ const parsed = parse(finalYamlConfig);
2686
+ const projectName = parsed?.name || "test";
2687
+ if (options.debug) {
2688
+ console.log(
2689
+ pc22.yellow("Final merged YAML configuration:\n"),
2690
+ redactYamlSecrets(finalYamlConfig)
2691
+ );
2692
+ }
2693
+ if (options.dryRun) {
2694
+ console.log(pc22.green("[DRY-RUN] Unit tests simulated. Compose was not started."));
2695
+ return 0;
2696
+ }
2697
+ await checkHostPortCollisions(extractHostPorts(finalYamlConfig));
2698
+ await teardownCompose(finalYamlConfig, options.projectDir, {
2699
+ removeVolumes: true,
2700
+ silent: true
2701
+ });
2702
+ writeRunState(options.projectDir, {
2703
+ projectName,
2704
+ stage: "test-unit",
2705
+ projectDir: options.projectDir
2706
+ });
2707
+ let status = 0;
2708
+ try {
2709
+ status = await runCompose(
2710
+ ["up", "--build", "--abort-on-container-exit", "--exit-code-from", "app"],
2711
+ finalYamlConfig,
2712
+ options.projectDir,
2713
+ { removeVolumes: true }
2714
+ );
2715
+ } finally {
2716
+ await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
2717
+ clearRunState(options.projectDir);
2718
+ }
2719
+ if (status === 0) {
2720
+ console.log(pc22.bold(pc22.green(`
2721
+ \u2705 Unit tests passed successfully.
2722
+ `)));
2723
+ } else {
2724
+ console.error(pc22.red(`
2725
+ \u274C Unit tests failed with exit code ${status}.
2726
+ `));
2727
+ }
2728
+ return status;
2729
+ };
2730
+ var runTestE2e = async (options) => {
2731
+ if (!options.skipBanner) {
2732
+ console.log(pc22.bold(pc22.blue(`
2733
+ ========================================`)));
2734
+ console.log(pc22.bold(pc22.blue(`\u{1F6A6} STAGE: INTEGRATED E2E TESTS`)));
2735
+ console.log(pc22.bold(pc22.blue(`========================================
2736
+ `)));
2737
+ }
2738
+ const finalYamlConfig = compileEnvironment("e2e", options.projectDir, {
2739
+ silenceWarnings: options.silenceWarnings
2740
+ });
2741
+ const parsed = parse(finalYamlConfig);
2742
+ const projectName = parsed?.name || "e2e";
2743
+ if (options.debug) {
2744
+ console.log(
2745
+ pc22.yellow("Final merged YAML configuration:\n"),
2746
+ redactYamlSecrets(finalYamlConfig)
2747
+ );
2748
+ }
2749
+ if (options.dryRun) {
2750
+ console.log(pc22.green("[DRY-RUN] E2E tests simulated. Compose was not started."));
2751
+ return 0;
2752
+ }
2753
+ await checkHostPortCollisions(extractHostPorts(finalYamlConfig));
2754
+ await teardownCompose(finalYamlConfig, options.projectDir, {
2755
+ removeVolumes: true,
2756
+ silent: true
2757
+ });
2758
+ writeRunState(options.projectDir, {
2759
+ projectName,
2760
+ stage: "test-e2e",
2761
+ projectDir: options.projectDir
2762
+ });
2763
+ let status = 0;
2764
+ try {
2765
+ status = await runCompose(
2766
+ [
2767
+ "up",
2768
+ "--build",
2769
+ "--abort-on-container-exit",
2770
+ "--exit-code-from",
2771
+ "tester"
2772
+ ],
2773
+ finalYamlConfig,
2774
+ options.projectDir,
2775
+ { removeVolumes: true }
2776
+ );
2777
+ } finally {
2778
+ await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
2779
+ clearRunState(options.projectDir);
2780
+ }
2781
+ if (status === 0) {
2782
+ console.log(pc22.bold(pc22.green(`
2783
+ \u2705 E2E tests passed successfully.
2784
+ `)));
2785
+ } else {
2786
+ console.error(pc22.red(`
2787
+ \u274C E2E tests failed with exit code ${status}.
2788
+ `));
2789
+ }
2790
+ return status;
2791
+ };
2792
+
2793
+ // src/core/runners/runTest.ts
2794
+ var runTest = async (options) => {
2795
+ console.log(pc22.bold(pc22.blue(`
2796
+ ========================================`)));
2797
+ console.log(pc22.bold(pc22.blue(`\u{1F9EA} [1/2] STAGE: UNIT & ISOLATED TESTS`)));
2798
+ console.log(pc22.bold(pc22.blue(`========================================
2799
+ `)));
2800
+ const unitStatus = await runTestUnit({ ...options, skipBanner: true });
2801
+ if (unitStatus !== 0) {
2802
+ console.error(
2803
+ pc22.red(
2804
+ `
2805
+ \u274C [1/2] Unit tests failed with exit code ${unitStatus}. Aborting E2E tests.
2806
+ `
2807
+ )
2808
+ );
2809
+ return unitStatus;
2810
+ }
2811
+ console.log(
2812
+ pc22.bold(pc22.green(`
2813
+ \u2705 [1/2] Unit tests passed successfully.
2814
+ `))
2815
+ );
2816
+ console.log(pc22.bold(pc22.blue(`========================================`)));
2817
+ console.log(pc22.bold(pc22.blue(`\u{1F6A6} [2/2] STAGE: INTEGRATED E2E TESTS`)));
2818
+ console.log(pc22.bold(pc22.blue(`========================================
2819
+ `)));
2820
+ const e2eStatus = await runTestE2e({ ...options, skipBanner: true });
2821
+ if (e2eStatus !== 0) {
2822
+ console.error(
2823
+ pc22.red(`
2824
+ \u274C [2/2] E2E tests failed with exit code ${e2eStatus}.
2825
+ `)
2826
+ );
2827
+ return e2eStatus;
2828
+ }
2829
+ console.log(pc22.bold(pc22.green(`
2830
+ \u2705 [2/2] E2E tests passed successfully.
2831
+ `)));
2832
+ console.log(
2833
+ pc22.bold(
2834
+ pc22.green(`\u{1F389} All test stages (unit + e2e) completed successfully!
2835
+ `)
2836
+ )
2837
+ );
2838
+ return 0;
2839
+ };
3659
2840
 
3660
2841
  // src/commands/service/commands/up/handler.ts
3661
2842
  async function handleServiceUp(rawStage, options = {}) {
3662
2843
  const projectDir = resolveProjectDir(options.projectDir);
3663
2844
  const stage = (rawStage || "dev").toLowerCase();
3664
- const isFull = Boolean(options.full || options.integrated);
2845
+ const isFull = Boolean(options.full);
3665
2846
  const runOptions = {
3666
2847
  projectDir,
3667
2848
  debug: Boolean(options.debug),
@@ -3705,10 +2886,7 @@ var registerUpCommand = (cmd) => {
3705
2886
  "Silence non-critical warnings like URL templating hints"
3706
2887
  ).option(
3707
2888
  "--full",
3708
- "Run dev environment with mock dependencies and integrated infra mode"
3709
- ).option(
3710
- "--integrated",
3711
- "Alias for --full"
2889
+ "Run dev with all declared local dependencies integrated"
3712
2890
  ).option(
3713
2891
  "-C, --project-dir <dir>",
3714
2892
  "Service project directory (defaults to cwd)"
@@ -3721,7 +2899,10 @@ Examples:
3721
2899
  $ builder service up prod
3722
2900
  $ builder service up test
3723
2901
  $ builder service up test-unit
3724
- $ builder service up test-e2e`
2902
+ $ builder service up test-e2e
2903
+
2904
+ JSON overlays: test-unit uses build.json test; test-e2e uses build.json e2e.
2905
+ The test command runs unit tests before E2E.`
3725
2906
  ).action(
3726
2907
  async (stage = "dev", options = {}) => {
3727
2908
  const exitCode = await handleServiceUp(stage, {
@@ -3731,7 +2912,7 @@ Examples:
3731
2912
  dryRun: options.dryRun,
3732
2913
  skipChecks: options.skipChecks,
3733
2914
  silenceWarnings: options.silenceWarnings,
3734
- full: Boolean(options.full || options.integrated)
2915
+ full: Boolean(options.full)
3735
2916
  });
3736
2917
  if (exitCode !== 0) {
3737
2918
  process.exit(exitCode);
@@ -3804,7 +2985,7 @@ async function handleExportEnv(rawStage, options = {}) {
3804
2985
  const files = [];
3805
2986
  try {
3806
2987
  for (const snapshot of snapshots) {
3807
- let filename = path13.join(projectDir, `.env.${snapshot.stage}`);
2988
+ let filename = path.join(projectDir, `.env.${snapshot.stage}`);
3808
2989
  while (true) {
3809
2990
  let overwrite = false;
3810
2991
  if (existsSync(filename)) {
@@ -3813,11 +2994,11 @@ async function handleExportEnv(rawStage, options = {}) {
3813
2994
  if (!overwrite) {
3814
2995
  const name = (await ask(`New filename for ${snapshot.stage} (relative to the service directory): `)).trim();
3815
2996
  if (!name) continue;
3816
- filename = path13.resolve(projectDir, name);
2997
+ filename = path.resolve(projectDir, name);
3817
2998
  continue;
3818
2999
  }
3819
3000
  }
3820
- mkdirSync(path13.dirname(filename), { recursive: true });
3001
+ mkdirSync(path.dirname(filename), { recursive: true });
3821
3002
  try {
3822
3003
  writeFileSync(filename, snapshot.content, { encoding: "utf-8", flag: overwrite ? "w" : "wx", mode: 384 });
3823
3004
  } catch (error) {
@@ -3838,7 +3019,7 @@ async function handleExportEnv(rawStage, options = {}) {
3838
3019
  // src/commands/service/commands/export/command.ts
3839
3020
  function registerExportCommand(service) {
3840
3021
  const command = service.command("export").description("Export service configuration");
3841
- command.command("env").description("Export the application's resolved environment for one or all stages").addArgument(new Argument("[stage]", "Stage to export (defaults to all four)").choices(["dev", "prod", "test", "e2e"])).option("-C, --project-dir <dir>", "Service project directory (defaults to cwd)").option("--full", "Export dev with mock dependencies and integrated infra mode").option("--integrated", "Alias for --full").option("--silence-warnings", "Silence non-critical URL templating warnings").addHelpText("after", `
3022
+ command.command("env").description("Export the application's resolved environment for one or all stages").addArgument(new Argument("[stage]", "Stage to export (defaults to all four)").choices(["dev", "prod", "test", "e2e"])).option("-C, --project-dir <dir>", "Service project directory (defaults to cwd)").option("--full", "Export dev with mock dependencies and integrated infra mode").option("--silence-warnings", "Silence non-critical URL templating warnings").addHelpText("after", `
3842
3023
  Examples:
3843
3024
  $ builder service export env
3844
3025
  $ builder service export env dev
@@ -3846,7 +3027,7 @@ Examples:
3846
3027
  $ builder service export env dev --full`).action(async (stage, options) => {
3847
3028
  await handleExportEnv(stage, {
3848
3029
  projectDir: options.projectDir,
3849
- full: Boolean(options.full || options.integrated),
3030
+ full: Boolean(options.full),
3850
3031
  silenceWarnings: options.silenceWarnings
3851
3032
  });
3852
3033
  });
@@ -3950,6 +3131,6 @@ ${formatted}
3950
3131
  }
3951
3132
  }
3952
3133
 
3953
- export { NotFoundError, SERVICE_STAGES, ScriptError, buildJsonSchema, compileApplicationEnv, compileEnvironment, compileMeshEnvironment, createCli, meshSchema, runCli, runCompose, serializeApplicationEnv, teardownCompose, version };
3134
+ export { ConfigError, NotFoundError, PortConflictError, SERVICE_STAGES, ScriptError, buildJsonSchema, compileApplicationEnv, compileEnvironment, compileMeshEnvironment, createCli, meshSchema, runCli, runCompose, serializeApplicationEnv, teardownCompose, version };
3954
3135
  //# sourceMappingURL=index.js.map
3955
3136
  //# sourceMappingURL=index.js.map