@solid-stack/builder 1.2.0 → 2.0.0

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