@solid-stack/builder 2.1.0 → 3.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 (174) hide show
  1. package/README.md +40 -593
  2. package/dist/bin.js +1799 -1999
  3. package/dist/bin.js.map +1 -1
  4. package/dist/commands/mesh/command.d.ts.map +1 -1
  5. package/dist/commands/mesh/commands/down/handler.d.ts.map +1 -1
  6. package/dist/commands/mesh/commands/up/command.d.ts.map +1 -1
  7. package/dist/commands/mesh/commands/up/handler.d.ts.map +1 -1
  8. package/dist/commands/prune/command.d.ts.map +1 -1
  9. package/dist/commands/prune/handler.d.ts +3 -1
  10. package/dist/commands/prune/handler.d.ts.map +1 -1
  11. package/dist/commands/service/command.d.ts.map +1 -1
  12. package/dist/commands/service/commands/down/handler.d.ts.map +1 -1
  13. package/dist/commands/service/commands/up/command.d.ts.map +1 -1
  14. package/dist/commands/service/commands/up/handler.d.ts.map +1 -1
  15. package/dist/core/buildSchema.d.ts +217 -952
  16. package/dist/core/buildSchema.d.ts.map +1 -1
  17. package/dist/core/checkers/checkDockerfileContract.d.ts +1 -0
  18. package/dist/core/checkers/checkDockerfileContract.d.ts.map +1 -1
  19. package/dist/core/checkers/checkInfra.d.ts +7 -1
  20. package/dist/core/checkers/checkInfra.d.ts.map +1 -1
  21. package/dist/core/checkers/getDeclaredYamlFiles.d.ts +1 -1
  22. package/dist/core/checkers/getDeclaredYamlFiles.d.ts.map +1 -1
  23. package/dist/core/compileApplicationEnv.d.ts +7 -2
  24. package/dist/core/compileApplicationEnv.d.ts.map +1 -1
  25. package/dist/core/compileEnvironment.d.ts +1 -0
  26. package/dist/core/compileEnvironment.d.ts.map +1 -1
  27. package/dist/core/composeCleanup.d.ts.map +1 -1
  28. package/dist/core/composition/compileGraphComposition.d.ts +16 -0
  29. package/dist/core/composition/compileGraphComposition.d.ts.map +1 -0
  30. package/dist/core/composition/compileServiceComposition.d.ts +2 -13
  31. package/dist/core/composition/compileServiceComposition.d.ts.map +1 -1
  32. package/dist/core/composition/compileTester.d.ts +24 -0
  33. package/dist/core/composition/compileTester.d.ts.map +1 -0
  34. package/dist/core/composition/composeDependsOn.d.ts +8 -2
  35. package/dist/core/composition/composeDependsOn.d.ts.map +1 -1
  36. package/dist/core/composition/composeHealthcheck.d.ts.map +1 -1
  37. package/dist/core/composition/composePaths.d.ts +1 -0
  38. package/dist/core/composition/composePaths.d.ts.map +1 -1
  39. package/dist/core/composition/dotenv.d.ts +3 -0
  40. package/dist/core/composition/dotenv.d.ts.map +1 -0
  41. package/dist/core/composition/generatedNames.d.ts.map +1 -1
  42. package/dist/core/composition/inspectRequiredHealth.d.ts +11 -0
  43. package/dist/core/composition/inspectRequiredHealth.d.ts.map +1 -0
  44. package/dist/core/composition/mergeMainOverride.d.ts +3 -0
  45. package/dist/core/composition/mergeMainOverride.d.ts.map +1 -0
  46. package/dist/core/composition/types.d.ts +21 -39
  47. package/dist/core/composition/types.d.ts.map +1 -1
  48. package/dist/core/composition/validateMaterializedComposeBuildInputs.d.ts +4 -0
  49. package/dist/core/composition/validateMaterializedComposeBuildInputs.d.ts.map +1 -0
  50. package/dist/core/composition/validateMaterializedComposeFiles.d.ts +8 -0
  51. package/dist/core/composition/validateMaterializedComposeFiles.d.ts.map +1 -0
  52. package/dist/core/composition/validateOverrideCompose.d.ts +4 -4
  53. package/dist/core/composition/validateOverrideCompose.d.ts.map +1 -1
  54. package/dist/core/composition/validateServiceCompose.d.ts +12 -0
  55. package/dist/core/composition/validateServiceCompose.d.ts.map +1 -0
  56. package/dist/core/config/constants.d.ts +2 -4
  57. package/dist/core/config/constants.d.ts.map +1 -1
  58. package/dist/core/config/endpointProperties.d.ts +2 -2
  59. package/dist/core/config/endpointProperties.d.ts.map +1 -1
  60. package/dist/core/config/executionProfile.d.ts +11 -0
  61. package/dist/core/config/executionProfile.d.ts.map +1 -0
  62. package/dist/core/config/hostPorts.d.ts +7 -1
  63. package/dist/core/config/hostPorts.d.ts.map +1 -1
  64. package/dist/core/config/meshStageContract.d.ts +6 -0
  65. package/dist/core/config/meshStageContract.d.ts.map +1 -0
  66. package/dist/core/config/publication.d.ts +11 -0
  67. package/dist/core/config/publication.d.ts.map +1 -0
  68. package/dist/core/config/references.d.ts +15 -15
  69. package/dist/core/config/references.d.ts.map +1 -1
  70. package/dist/core/config/resolveBuildStage.d.ts.map +1 -1
  71. package/dist/core/config/resolveMeshStage.d.ts +1 -1
  72. package/dist/core/config/resolveMeshStage.d.ts.map +1 -1
  73. package/dist/core/config/serviceGraph.d.ts +10 -0
  74. package/dist/core/config/serviceGraph.d.ts.map +1 -0
  75. package/dist/core/config/stageMerge.d.ts +2 -3
  76. package/dist/core/config/stageMerge.d.ts.map +1 -1
  77. package/dist/core/config/types.d.ts +104 -27
  78. package/dist/core/config/types.d.ts.map +1 -1
  79. package/dist/core/mesh/applyMeshExtends.d.ts +3 -0
  80. package/dist/core/mesh/applyMeshExtends.d.ts.map +1 -0
  81. package/dist/core/mesh/checkers/checkMesh.d.ts +2 -1
  82. package/dist/core/mesh/checkers/checkMesh.d.ts.map +1 -1
  83. package/dist/core/mesh/checkers/checkMeshServices.d.ts +3 -5
  84. package/dist/core/mesh/checkers/checkMeshServices.d.ts.map +1 -1
  85. package/dist/core/mesh/checkers/checkMeshTester.d.ts +1 -3
  86. package/dist/core/mesh/checkers/checkMeshTester.d.ts.map +1 -1
  87. package/dist/core/mesh/compileMeshComposition.d.ts +6 -0
  88. package/dist/core/mesh/compileMeshComposition.d.ts.map +1 -0
  89. package/dist/core/mesh/compileMeshEnvironment.d.ts +3 -2
  90. package/dist/core/mesh/compileMeshEnvironment.d.ts.map +1 -1
  91. package/dist/core/mesh/getMeshJson.d.ts.map +1 -1
  92. package/dist/core/mesh/loadMeshSources.d.ts +4 -0
  93. package/dist/core/mesh/loadMeshSources.d.ts.map +1 -0
  94. package/dist/core/mesh/meshSchema.d.ts +41 -280
  95. package/dist/core/mesh/meshSchema.d.ts.map +1 -1
  96. package/dist/core/mesh/runners/runMeshDev.d.ts +1 -1
  97. package/dist/core/mesh/runners/runMeshDev.d.ts.map +1 -1
  98. package/dist/core/mesh/runners/runMeshProd.d.ts +1 -1
  99. package/dist/core/mesh/runners/runMeshProd.d.ts.map +1 -1
  100. package/dist/core/mesh/runners/runMeshServiceTests.d.ts +2 -1
  101. package/dist/core/mesh/runners/runMeshServiceTests.d.ts.map +1 -1
  102. package/dist/core/mesh/runners/runMeshTest.d.ts +7 -1
  103. package/dist/core/mesh/runners/runMeshTest.d.ts.map +1 -1
  104. package/dist/core/mesh/runners/runMeshTestE2e.d.ts +2 -1
  105. package/dist/core/mesh/runners/runMeshTestE2e.d.ts.map +1 -1
  106. package/dist/core/mesh/types.d.ts +21 -27
  107. package/dist/core/mesh/types.d.ts.map +1 -1
  108. package/dist/core/runCompose.d.ts +4 -0
  109. package/dist/core/runCompose.d.ts.map +1 -1
  110. package/dist/core/runners/runDev.d.ts.map +1 -1
  111. package/dist/core/runners/runFiniteTester.d.ts +13 -0
  112. package/dist/core/runners/runFiniteTester.d.ts.map +1 -0
  113. package/dist/core/runners/runLongLived.d.ts +15 -0
  114. package/dist/core/runners/runLongLived.d.ts.map +1 -0
  115. package/dist/core/runners/runProd.d.ts.map +1 -1
  116. package/dist/core/runners/runTest.d.ts +7 -1
  117. package/dist/core/runners/runTest.d.ts.map +1 -1
  118. package/dist/core/runners/runTestE2e.d.ts +9 -1
  119. package/dist/core/runners/runTestE2e.d.ts.map +1 -1
  120. package/dist/core/runners/runTestUnit.d.ts +9 -1
  121. package/dist/core/runners/runTestUnit.d.ts.map +1 -1
  122. package/dist/index.js +1802 -2000
  123. package/dist/index.js.map +1 -1
  124. package/dist/templates/docker/docker-compose.base.yml +1 -1
  125. package/dist/templates/docker/docker-compose.dev.yml +1 -4
  126. package/dist/templates/docker/docker-compose.e2e.yml +1 -6
  127. package/dist/templates/docker/docker-compose.prod.yml +1 -1
  128. package/dist/templates/docker/docker-compose.test.yml +1 -1
  129. package/dist/templates/policy/dockerfile/dockerfile.rego +3 -6
  130. package/dist/types/index.d.ts +51 -32
  131. package/dist/types/index.d.ts.map +1 -1
  132. package/dist/utils/runState.d.ts +9 -1
  133. package/dist/utils/runState.d.ts.map +1 -1
  134. package/package.json +11 -6
  135. package/schemas/build-schema.json +868 -507
  136. package/schemas/mesh-schema.json +934 -477
  137. package/templates/docker/docker-compose.base.yml +1 -1
  138. package/templates/docker/docker-compose.dev.yml +1 -4
  139. package/templates/docker/docker-compose.e2e.yml +1 -6
  140. package/templates/docker/docker-compose.prod.yml +1 -1
  141. package/templates/docker/docker-compose.test.yml +1 -1
  142. package/templates/policy/dockerfile/dockerfile.rego +3 -6
  143. package/dist/core/composition/dependencyLifecycle.d.ts +0 -4
  144. package/dist/core/composition/dependencyLifecycle.d.ts.map +0 -1
  145. package/dist/core/composition/mergeAppOverride.d.ts +0 -3
  146. package/dist/core/composition/mergeAppOverride.d.ts.map +0 -1
  147. package/dist/core/composition/selectAppEnvironmentEntries.d.ts +0 -3
  148. package/dist/core/composition/selectAppEnvironmentEntries.d.ts.map +0 -1
  149. package/dist/core/composition/serviceEndpoints.d.ts +0 -5
  150. package/dist/core/composition/serviceEndpoints.d.ts.map +0 -1
  151. package/dist/core/composition/validateDependencyCompose.d.ts +0 -8
  152. package/dist/core/composition/validateDependencyCompose.d.ts.map +0 -1
  153. package/dist/core/mesh/runners/runMeshTestUnit.d.ts +0 -3
  154. package/dist/core/mesh/runners/runMeshTestUnit.d.ts.map +0 -1
  155. package/dist/core/mesh/v2/compileMeshComposition.d.ts +0 -6
  156. package/dist/core/mesh/v2/compileMeshComposition.d.ts.map +0 -1
  157. package/dist/core/mesh/v2/compileMeshTester.d.ts +0 -15
  158. package/dist/core/mesh/v2/compileMeshTester.d.ts.map +0 -1
  159. package/dist/core/mesh/v2/lifecycle.d.ts +0 -10
  160. package/dist/core/mesh/v2/lifecycle.d.ts.map +0 -1
  161. package/dist/core/mesh/v2/loadMeshServices.d.ts +0 -5
  162. package/dist/core/mesh/v2/loadMeshServices.d.ts.map +0 -1
  163. package/dist/core/mesh/v2/meshReferences.d.ts +0 -17
  164. package/dist/core/mesh/v2/meshReferences.d.ts.map +0 -1
  165. package/dist/core/mesh/v2/publication.d.ts +0 -3
  166. package/dist/core/mesh/v2/publication.d.ts.map +0 -1
  167. package/dist/core/mesh/v2/resolveMeshAppEnvironment.d.ts +0 -4
  168. package/dist/core/mesh/v2/resolveMeshAppEnvironment.d.ts.map +0 -1
  169. package/dist/core/mesh/v2/substitution.d.ts +0 -5
  170. package/dist/core/mesh/v2/substitution.d.ts.map +0 -1
  171. package/dist/core/mesh/v2/types.d.ts +0 -40
  172. package/dist/core/mesh/v2/types.d.ts.map +0 -1
  173. package/dist/core/mesh/v2/validateMeshTestStage.d.ts +0 -22
  174. package/dist/core/mesh/v2/validateMeshTestStage.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,19 +1,21 @@
1
1
  import { Command, Argument } from 'commander';
2
- import pc14 from 'picocolors';
3
- import fs, { existsSync, readFileSync, mkdirSync, writeFileSync, renameSync, statSync, realpathSync, lstatSync, readlinkSync, unlinkSync } from 'fs';
2
+ import pc9 from 'picocolors';
3
+ import fs, { existsSync, readFileSync, statSync, mkdirSync, writeFileSync, unlinkSync, realpathSync, lstatSync, readlinkSync, renameSync } from 'fs';
4
4
  import path from 'path';
5
5
  import { z } from 'zod';
6
6
  import { spawnSync, spawn } from 'child_process';
7
7
  import { fileURLToPath } from 'url';
8
8
  import { stringify, parse, parseAllDocuments } from 'yaml';
9
9
  import crypto, { createHash } from 'crypto';
10
- import net, { isIP } from 'net';
11
10
  import os from 'os';
11
+ import net, { isIP } from 'net';
12
12
  import { createInterface } from 'readline/promises';
13
13
  import { createRequire } from 'module';
14
14
 
15
15
  // src/types/index.ts
16
16
  var SERVICE_STAGES = ["dev", "prod", "test", "test-unit", "test-e2e"];
17
+ var isMainEntry = (name) => name === "main";
18
+ var isTesterEntry = (name) => name === "tester";
17
19
 
18
20
  // src/errors/ScriptError.ts
19
21
  var ScriptError = class extends Error {
@@ -47,28 +49,45 @@ var ConfigError = class extends ScriptError {
47
49
  // src/core/config/constants.ts
48
50
  var BUILDER_IDENTIFIER_PATTERN = /^[a-z][a-z0-9-]*$/;
49
51
  var ENDPOINT_SCHEME_PATTERN = /^[A-Za-z][A-Za-z0-9+.-]*$/;
50
- var DEPENDENCY_REFERENCE_PATTERN = /^dependencies\.([a-z][a-z0-9-]*)$/;
51
52
  var ENDPOINT_PROPERTIES = ["network_host", "network_port", "network_address", "network_url", "public_host", "public_port", "public_address", "public_url"];
52
- var PUBLIC_ENDPOINT_PROPERTIES = /* @__PURE__ */ new Set(["public_host", "public_port", "public_address", "public_url"]);
53
- var RESERVED_MESH_SERVICE_NAMES = /* @__PURE__ */ new Set(["app", "dependencies", "tester", "services", "dev", "prod", "test", "e2e"]);
54
53
  var PUBLIC_HOST = "127.0.0.1";
55
- var AUTO_PORT_CACHE_VERSION = 1;
56
- var AUTO_PORT_CACHE_RELATIVE_PATH = ".builder/ports-v2.json";
54
+ var AUTO_PORT_CACHE_VERSION = 3;
55
+ var AUTO_PORT_CACHE_RELATIVE_PATH = ".builder/ports-v3.json";
57
56
  var AUTO_PORT_SCAN_START = 2e4;
58
57
 
59
58
  // src/core/buildSchema.ts
60
- var identifierSchema = z.string().regex(BUILDER_IDENTIFIER_PATTERN, "must match ^[a-z][a-z0-9-]*$");
61
- var envSchema = z.record(z.string(), z.string());
62
- var portSchema = z.number().int().min(1).max(65535);
63
- var publicPortSchema = z.union([portSchema, z.literal("AUTO")]);
64
- var appEndpointSchema = z.object({ port: portSchema, publicPort: publicPortSchema.optional(), primary: z.boolean().optional(), scheme: z.string().regex(ENDPOINT_SCHEME_PATTERN).optional() }).strict();
65
- var dependencyEndpointSchema = appEndpointSchema.extend({ service: z.string().min(1) }).strict();
66
- var dependencySchema = z.object({ compose: z.string().min(1), env: envSchema.optional(), endpoints: z.record(identifierSchema, dependencyEndpointSchema).optional(), dependsOn: z.array(z.string()).optional() }).strict();
67
- var appStageEndpointSchema = appEndpointSchema.partial().strict();
68
- var dependencyStageEndpointSchema = dependencyEndpointSchema.partial().strict();
69
- var dependencyStageSchema = z.object({ compose: z.string().min(1).optional(), env: envSchema.optional(), endpoints: z.record(identifierSchema, dependencyStageEndpointSchema).optional(), dependsOn: z.array(z.string()).optional() }).strict();
70
- var buildStageSchema = z.object({ "override-compose": z.string().min(1).optional(), app: z.object({ env: envSchema.optional(), endpoints: z.record(identifierSchema, appStageEndpointSchema).optional() }).strict().optional(), dependencies: z.record(identifierSchema, dependencyStageSchema).optional() }).strict();
71
- var buildJsonSchema = z.object({ $schema: z.string().optional(), name: z.string().optional(), dockerfile: z.string().min(1).optional(), app: z.object({ env: envSchema.optional(), endpoints: z.record(identifierSchema, appEndpointSchema).optional() }).strict(), dependencies: z.record(identifierSchema, dependencySchema).optional(), tester: z.object({ env: envSchema.optional() }).strict().optional(), dev: buildStageSchema.optional(), prod: buildStageSchema.optional(), test: buildStageSchema.optional(), e2e: buildStageSchema.optional() }).strict();
59
+ var identifier = z.string().regex(BUILDER_IDENTIFIER_PATTERN);
60
+ var nonblank = z.string().min(1).refine((value) => value.trim().length > 0, "must not be blank");
61
+ var env = z.record(z.string(), z.string());
62
+ var port = z.number().int().min(1).max(65535);
63
+ var publicPort = z.union([port, z.literal("AUTO")]);
64
+ var requisite = z.enum(["requirement", "dependency", "prerequisite"]);
65
+ var requisites = z.record(identifier, requisite);
66
+ var requisiteOverlay = z.record(identifier, z.union([requisite, z.literal(false)]));
67
+ var mainEndpointSchema = z.object({ port, publicPort: publicPort.optional(), primary: z.boolean().optional(), scheme: z.string().regex(ENDPOINT_SCHEME_PATTERN).optional() }).strict();
68
+ var serviceEndpointSchema = mainEndpointSchema.extend({ service: nonblank }).strict();
69
+ var mainServiceSchema = z.object({ env: env.optional(), endpoints: z.record(identifier, mainEndpointSchema).optional(), requisites: requisites.optional(), "override-compose": nonblank.optional() }).strict();
70
+ var testerServiceSchema = z.object({ compose: nonblank, service: nonblank, env: env.optional() }).strict();
71
+ var ordinaryServiceSchema = z.object({ compose: nonblank, service: nonblank.optional(), env: env.optional(), endpoints: z.record(identifier, serviceEndpointSchema).optional(), requisites: requisites.optional() }).strict().refine((value) => Boolean(value.service) || Boolean(value.endpoints && Object.keys(value.endpoints).length), "endpoint-less service requires service");
72
+ var mainOverlaySchema = z.object({ env: env.optional(), endpoints: z.record(identifier, mainEndpointSchema.partial().strict()).optional(), requisites: requisiteOverlay.optional(), "override-compose": nonblank.optional() }).strict();
73
+ var testerOverlaySchema = testerServiceSchema.partial().strict();
74
+ var ordinaryOverlaySchema = z.object({ compose: nonblank.optional(), service: nonblank.optional(), env: env.optional(), endpoints: z.record(identifier, serviceEndpointSchema.partial().strict()).optional(), requisites: requisiteOverlay.optional() }).strict();
75
+ var buildServicesSchema = z.record(identifier, z.unknown()).superRefine((value, context) => {
76
+ for (const required of ["main", "tester"]) if (!(required in value)) context.addIssue({ code: "custom", path: [required], message: `${required} is required` });
77
+ for (const [key, entry] of Object.entries(value)) {
78
+ const schema = key === "main" ? mainServiceSchema : key === "tester" ? testerServiceSchema : ordinaryServiceSchema;
79
+ const parsed = schema.safeParse(entry);
80
+ if (!parsed.success) for (const issue of parsed.error.issues) context.addIssue({ ...issue, path: [key, ...issue.path] });
81
+ }
82
+ });
83
+ var buildStageSchema = z.object({ services: z.record(identifier, z.unknown()).superRefine((value, context) => {
84
+ for (const [key, entry] of Object.entries(value)) {
85
+ const schema = key === "main" ? mainOverlaySchema : key === "tester" ? testerOverlaySchema : ordinaryOverlaySchema;
86
+ const parsed = schema.safeParse(entry);
87
+ if (!parsed.success) for (const issue of parsed.error.issues) context.addIssue({ ...issue, path: [key, ...issue.path] });
88
+ }
89
+ }).optional() }).strict();
90
+ var buildJsonSchema = z.object({ $schema: z.string().optional(), name: nonblank, services: buildServicesSchema, dev: buildStageSchema.optional(), prod: buildStageSchema.optional(), test: buildStageSchema.optional(), e2e: buildStageSchema.optional() }).strict();
72
91
 
73
92
  // src/utils/errorMessage.ts
74
93
  function errorMessage(err) {
@@ -149,8 +168,8 @@ function resolveInsideProject(projectDir, relativePath, context) {
149
168
  if (!isPathInside(projectDir, relativePath)) throw new ConfigError({ ...context, value: relativePath, reason: "Path escapes the project directory" });
150
169
  return resolved;
151
170
  }
152
- function resolveApplicationDockerfile(projectDir, relativePath = "Dockerfile", stage) {
153
- const context = { sourceFile: path.join(projectDir, "build.json"), configPath: "dockerfile", ...stage ? { stage } : {} };
171
+ function resolveApplicationDockerfile(projectDir, relativePath = "Dockerfile", stage2) {
172
+ const context = { sourceFile: path.join(projectDir, "build.json"), configPath: "dockerfile", ...stage2 ? { stage: stage2 } : {} };
154
173
  const resolved = resolveInsideProject(projectDir, relativePath, context);
155
174
  if (!existsSync(resolved) || !statSync(resolved).isFile()) throw new ConfigError({ ...context, value: relativePath, reason: `Application Dockerfile not found or not a regular file: ${resolved}` });
156
175
  return resolved;
@@ -174,7 +193,7 @@ function runStep(executable, args, projectDir, ctx) {
174
193
  if (stderr) process.stderr.write(stderr);
175
194
  if (result.error || result.status !== 0) {
176
195
  console.error("\n" + "=".repeat(60));
177
- console.error(pc14.red(`\u{1F6A8} INFRASTRUCTURE CHECK FAILED \u{1F6A8}`));
196
+ console.error(pc9.red(`\u{1F6A8} INFRASTRUCTURE CHECK FAILED \u{1F6A8}`));
178
197
  console.error("=".repeat(60));
179
198
  console.error(`Failed Step : ${ctx.stepName}`);
180
199
  if (ctx.targetFile) {
@@ -198,10 +217,10 @@ ${ctx.detail}`);
198
217
 
199
218
  // src/core/checkers/checkDockerfile.ts
200
219
  function checkDockerfile(buildJson, projectDir) {
201
- const dockerfileRel = buildJson.dockerfile || "Dockerfile";
220
+ const dockerfileRel = "Dockerfile";
202
221
  const dockerfilePath = resolveApplicationDockerfile(projectDir, dockerfileRel);
203
222
  const content = readFileSync(dockerfilePath, "utf-8");
204
- console.log(pc14.cyan(`
223
+ console.log(pc9.cyan(`
205
224
  \u{1F50D} Linting Dockerfile (${dockerfileRel})...`));
206
225
  runStep(
207
226
  "docker",
@@ -264,128 +283,67 @@ function getDockerfilePolicyDir() {
264
283
  if (!fs.existsSync(path.join(policyDir, "dockerfile.rego"))) throw new ScriptError(`Builder Dockerfile policy not found: ${policyDir}`);
265
284
  return policyDir;
266
285
  }
267
-
268
- // src/core/checkers/checkDockerfileContract.ts
286
+ function assertMainDockerfileContract(projectDir, activeStage) {
287
+ const file = resolveApplicationDockerfile(projectDir, "Dockerfile", activeStage);
288
+ const lines = readFileSync(file, "utf8").replace(/\\\r?\n\s*/g, " ").split(/\r?\n/);
289
+ const stages = /* @__PURE__ */ new Map();
290
+ let current;
291
+ for (const raw of lines) {
292
+ const line = raw.trim();
293
+ if (!line || line.startsWith("#")) continue;
294
+ const from = /^FROM\s+(?:--\S+\s+)*(\S+)(?:\s+AS\s+(\S+))?/i.exec(line);
295
+ if (from) {
296
+ current = { name: (from[2] ?? `__${stages.size}`).toLowerCase(), parent: from[1].toLowerCase() };
297
+ stages.set(current.name, current);
298
+ continue;
299
+ }
300
+ if (!current) continue;
301
+ const instruction = /^(CMD|ENTRYPOINT|HEALTHCHECK)\s+(.+)$/i.exec(line);
302
+ if (instruction) {
303
+ const key = instruction[1].toLowerCase();
304
+ if (key === "cmd") current.command = instruction[2];
305
+ else if (key === "entrypoint") current.entrypoint = instruction[2];
306
+ else current.health = instruction[2];
307
+ }
308
+ }
309
+ const fail4 = (reason) => {
310
+ throw new ConfigError({ sourceFile: file, configPath: `Dockerfile.${activeStage}`, stage: activeStage, composition: "service", reason });
311
+ };
312
+ for (const name of ["dev", "test", "prod"]) if (!stages.has(name)) fail4(`Missing required Dockerfile target ${name}`);
313
+ const visited = /* @__PURE__ */ new Set();
314
+ let cursor = stages.get(activeStage), runtime = false, health;
315
+ let effectiveCmd, effectiveEntrypoint;
316
+ while (cursor) {
317
+ if (visited.has(cursor.name)) fail4(`Dockerfile stage inheritance cycle at ${cursor.name}`);
318
+ visited.add(cursor.name);
319
+ runtime ||= Boolean(cursor.command || cursor.entrypoint);
320
+ if (effectiveCmd === void 0 && cursor.command !== void 0) effectiveCmd = cursor.command;
321
+ if (effectiveEntrypoint === void 0 && cursor.entrypoint !== void 0) effectiveEntrypoint = cursor.entrypoint;
322
+ if (health === void 0 && cursor.health !== void 0) health = cursor.health;
323
+ cursor = stages.get(cursor.parent);
324
+ }
325
+ if (!runtime) fail4(`${activeStage} requires an effective CMD or ENTRYPOINT`);
326
+ if (activeStage !== "test" && (!health || /^NONE$/i.test(health.trim()))) fail4(`${activeStage} requires a valid healthcheck`);
327
+ if (activeStage === "dev" && [effectiveEntrypoint, effectiveCmd].some((instruction) => instruction !== void 0 && /(?:nohup|&\s*(?:["']?\s*\]|\s*$)|--daemon)/i.test(instruction))) fail4("dev runtime must remain in foreground");
328
+ }
269
329
  function checkDockerfileContract(build, projectDir) {
270
330
  const root = resolveProjectDir(projectDir);
271
- const relative = build.dockerfile ?? "Dockerfile";
331
+ const relative = "Dockerfile";
272
332
  resolveApplicationDockerfile(root, relative);
273
333
  const policyDir = getDockerfilePolicyDir();
274
- console.log(pc14.cyan(`
334
+ console.log(pc9.cyan(`
275
335
  \u{1F50D} Validating Builder Dockerfile contract (${relative})...`));
276
336
  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 });
277
337
  }
278
- function loadComposeDocument(absolutePath, context) {
279
- const fail = (reason, value) => {
280
- throw new ConfigError({ ...context, sourceFile: absolutePath, ...{} , reason });
281
- };
282
- if (!existsSync(absolutePath) || !statSync(absolutePath).isFile()) fail("Compose file does not exist or is not a regular file");
283
- let text = "";
284
- try {
285
- text = readFileSync(absolutePath, "utf8");
286
- } catch (e) {
287
- fail(`Failed to read Compose file: ${String(e)}`);
288
- }
289
- let docs = [];
290
- try {
291
- docs = parseAllDocuments(text, { prettyErrors: true });
292
- } catch (e) {
293
- fail(`Invalid Compose YAML: ${String(e)}`);
294
- }
295
- if (docs.length !== 1) fail("Compose file must contain exactly one YAML document");
296
- const errors = docs[0].errors;
297
- if (errors.length) fail(`Invalid Compose YAML: ${errors.map((e) => e.message).join("; ")}`);
298
- let parsed;
299
- try {
300
- parsed = parse(text);
301
- } catch (e) {
302
- fail(`Invalid Compose YAML: ${String(e)}`);
303
- }
304
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) fail("Compose root must be an object");
305
- return parsed;
306
- }
307
- function getDeclaredYamlFiles(build, projectDir) {
308
- const files = [];
309
- const seen = /* @__PURE__ */ new Set();
310
- const add = (relativePath, source, kind, stage) => {
311
- const absolutePath = path.resolve(projectDir, relativePath);
312
- if (seen.has(absolutePath)) return;
313
- seen.add(absolutePath);
314
- files.push({ relativePath, absolutePath, source, kind, ...stage ? { stage } : {} });
315
- };
316
- for (const [name, dep] of Object.entries(build.dependencies ?? {})) add(dep.compose, `dependencies.${name}.compose`, "dependency-compose");
317
- for (const stage of ["dev", "prod", "test", "e2e"]) {
318
- const overlay = build[stage];
319
- if (overlay?.["override-compose"]) add(overlay["override-compose"], `${stage}.override-compose`, "override-compose", stage);
320
- for (const [name, dep] of Object.entries(overlay?.dependencies ?? {})) if (dep.compose) add(dep.compose, `${stage}.dependencies.${name}.compose`, "dependency-compose", stage);
321
- }
322
- return files;
323
- }
324
-
325
- // src/core/checkers/checkYamlFiles.ts
326
- function checkYamlFiles(build, projectDir) {
327
- const root = resolveProjectDir(projectDir);
328
- const files = getDeclaredYamlFiles(build, root);
329
- if (files.length) console.log(pc14.cyan(`
330
- \u{1F50D} Validating ${files.length} declared V2 Compose file(s)...`));
331
- for (const file of files) {
332
- const absolutePath = resolveInsideProject(root, file.relativePath, { sourceFile: `${root}/build.json`, configPath: file.source, ...file.stage ? { stage: file.stage } : {} });
333
- loadComposeDocument(absolutePath, { sourceFile: `${root}/build.json`, configPath: file.source, stage: file.stage ?? "base", composition: "service" });
334
- }
335
- }
336
- var GeneratedComposeNameAllocator = class {
337
- occupied;
338
- allocated = /* @__PURE__ */ new Map();
339
- constructor(initialNames = []) {
340
- this.occupied = new Set(initialNames);
341
- }
342
- allocate(identity, hint) {
343
- const existing = this.allocated.get(identity);
344
- if (existing) return existing;
345
- const hash = createHash("sha256").update(identity).digest("hex");
346
- const safeHint = hint.replace(/[^a-zA-Z0-9_-]/g, "-") || "item";
347
- for (const candidate of [
348
- safeHint,
349
- ...[12, 16, 24, 32, 64].map((length) => `${safeHint}-${hash.slice(0, length)}`)
350
- ]) {
351
- if (this.occupied.has(candidate)) continue;
352
- this.occupied.add(candidate);
353
- this.allocated.set(identity, candidate);
354
- return candidate;
355
- }
356
- throw new Error(`Unable to allocate unique Compose name for ${identity}`);
357
- }
358
- assertUnique() {
359
- if (new Set(this.allocated.values()).size !== this.allocated.size) {
360
- throw new Error("Internal generated Compose name collision");
361
- }
362
- }
363
- };
364
-
365
- // src/core/composition/composeNetworks.ts
366
- function normalizeNetworks(value) {
367
- if (Array.isArray(value)) return Object.fromEntries(value.filter((name) => typeof name === "string").map((name) => [name, null]));
368
- return value && typeof value === "object" ? { ...value } : {};
369
- }
370
-
371
- // src/core/composition/selectAppEnvironmentEntries.ts
372
- function selectAppEnvironmentEntries(layers, laterKeys = /* @__PURE__ */ new Set()) {
373
- const winners = /* @__PURE__ */ new Map();
374
- for (const layer of layers) {
375
- for (const key of Object.keys(layer.values)) winners.set(key, layer);
376
- }
377
- for (const key of laterKeys) winners.delete(key);
378
- return winners;
379
- }
380
338
 
381
339
  // src/core/config/endpointProperties.ts
382
340
  function resolveEndpointProperty(endpoint, property, context) {
383
341
  const reference = context.referencedObject ?? endpoint.logicalPath;
384
342
  const published = () => {
385
- if (!endpoint.effectivelyPublished || endpoint.publicHost === void 0 || endpoint.publicPort === void 0) throw new ConfigError({ ...context, referencedObject: reference, reason: `Endpoint property ${property} requires effective publication` });
343
+ if (!endpoint.effectivelyPublished || endpoint.publicHost === void 0 || endpoint.publicPort === void 0) throw new ConfigError({ ...context, referencedObject: reference, reason: `endpoint is not published; ${property} requires publicPort capability and, in a mesh, a publish selector` });
386
344
  };
387
345
  const scheme = () => {
388
- if (!endpoint.scheme) throw new ConfigError({ ...context, referencedObject: reference, reason: `Endpoint property ${property} requires an endpoint scheme` });
346
+ if (!endpoint.scheme) throw new ConfigError({ ...context, referencedObject: reference, reason: `Endpoint property ${property} requires scheme` });
389
347
  return endpoint.scheme;
390
348
  };
391
349
  switch (property) {
@@ -415,172 +373,193 @@ function assertPrimaryEndpointInvariant(endpoints, context) {
415
373
  const primaries = Object.entries(endpoints).filter(([, e]) => e.primary === true);
416
374
  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}` });
417
375
  }
418
- function getPrimaryEndpoint(endpoints) {
419
- return Object.entries(endpoints).find(([, endpoint]) => endpoint.primary === true);
420
- }
421
-
422
- // src/core/config/lifecycleGraph.ts
423
- function assertAcyclicGraph(graph, context) {
424
- const visiting = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set(), stack = [];
425
- const visit = (node) => {
426
- if (visiting.has(node)) {
427
- const start = stack.indexOf(node);
428
- const cycle = [...stack.slice(start), node];
429
- throw new ConfigError({ ...context, configPath: "dependsOn", referencedObject: cycle.join(" -> "), reason: `Lifecycle cycle detected: ${cycle.join(" -> ")}` });
430
- }
431
- if (visited.has(node)) return;
432
- visiting.add(node);
433
- stack.push(node);
434
- for (const next of graph.get(node) ?? []) visit(next);
435
- stack.pop();
436
- visiting.delete(node);
437
- visited.add(node);
438
- };
439
- for (const node of graph.keys()) visit(node);
440
- }
441
376
 
442
377
  // src/core/config/stageMerge.ts
443
- function stageOverlayChain(stage) {
444
- switch (stage) {
445
- case "dev":
446
- return ["dev"];
447
- case "prod":
448
- return ["prod"];
449
- case "test":
450
- return ["test"];
451
- case "e2e":
452
- return ["prod", "e2e"];
378
+ function stageOverlayChain(stage2) {
379
+ return stage2 === "e2e" ? ["prod", "e2e"] : [stage2];
380
+ }
381
+ var plain = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
382
+ function mergeEffectiveObject(base, patch) {
383
+ if (plain(base) && plain(patch)) {
384
+ const result = structuredClone(base);
385
+ for (const [key, value] of Object.entries(patch)) result[key] = key in result ? mergeEffectiveObject(result[key], value) : structuredClone(value);
386
+ return result;
453
387
  }
388
+ return structuredClone(patch);
454
389
  }
455
- function unionStable(base = [], overlay = []) {
456
- return [.../* @__PURE__ */ new Set([...base, ...overlay])];
457
- }
458
- function mergeStringMap(base, overlay) {
459
- return { ...base ?? {}, ...overlay ?? {} };
390
+ function applyServiceOverlay(base, patch) {
391
+ const without = { ...patch };
392
+ delete without.requisites;
393
+ const result = mergeEffectiveObject(base, without);
394
+ if (patch.requisites) {
395
+ const edges = { ...base.requisites ?? {} };
396
+ for (const [target, kind] of Object.entries(patch.requisites)) {
397
+ if (kind === false) delete edges[target];
398
+ else edges[target] = kind;
399
+ }
400
+ result.requisites = edges;
401
+ }
402
+ return result;
460
403
  }
461
404
 
462
405
  // src/core/config/resolveBuildStage.ts
463
- function resolveBuildStage(build, stage, sourceFile) {
464
- const context = (configPath, value, reason, referencedObject) => new ConfigError({ sourceFile, configPath, stage, composition: "service", value, ...referencedObject ? { referencedObject } : {}, reason });
465
- const appEnv = { ...build.app.env ?? {} };
466
- const appEndpoints = structuredClone(build.app.endpoints ?? {});
467
- const dependencies = {};
468
- for (const [name, dep] of Object.entries(build.dependencies ?? {})) dependencies[name] = { ...dep, env: { ...dep.env ?? {} }, endpoints: structuredClone(dep.endpoints ?? {}), dependsOn: [...dep.dependsOn ?? []] };
469
- const layers = [{ stage: "base", appEnv: { ...build.app.env ?? {} } }];
470
- for (const overlayStage of stageOverlayChain(stage)) {
471
- const overlay = build[overlayStage];
472
- if (!overlay) continue;
473
- Object.assign(appEnv, overlay.app?.env ?? {});
474
- for (const [name, endpoint] of Object.entries(overlay.app?.endpoints ?? {})) appEndpoints[name] = { ...appEndpoints[name] ?? {}, ...endpoint };
475
- for (const [name, patch] of Object.entries(overlay.dependencies ?? {})) {
476
- const inherited = dependencies[name];
477
- if (inherited && patch.compose !== void 0) throw context(`${overlayStage}.dependencies.${name}.compose`, patch.compose, "A stage cannot replace the Compose implementation of an inherited dependency", `dependencies.${name}`);
478
- const next = inherited ?? { compose: void 0, env: {}, endpoints: {}, dependsOn: [] };
479
- if (!inherited && patch.compose !== void 0) next.compose = patch.compose;
480
- next.env = mergeStringMap(next.env, patch.env);
481
- for (const [endpointName, endpointPatch] of Object.entries(patch.endpoints ?? {})) next.endpoints[endpointName] = { ...next.endpoints[endpointName] ?? {}, ...endpointPatch };
482
- next.dependsOn = unionStable(next.dependsOn, patch.dependsOn);
483
- dependencies[name] = next;
484
- }
485
- layers.push({ stage: overlayStage, appEnv: { ...overlay.app?.env ?? {} }, ...overlay["override-compose"] ? { overrideCompose: overlay["override-compose"] } : {} });
486
- }
487
- const effective = { ...build, app: { env: appEnv, endpoints: appEndpoints }, dependencies, tester: build.tester ? { env: { ...build.tester.env ?? {} } } : void 0, layers };
488
- delete effective.dev;
489
- delete effective.prod;
490
- delete effective.test;
491
- delete effective.e2e;
492
- 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");
493
- assertPrimaryEndpointInvariant(appEndpoints, { sourceFile, configPath: "app.endpoints", stage });
494
- const graph = /* @__PURE__ */ new Map();
495
- for (const [name, dep] of Object.entries(dependencies)) {
496
- if (typeof dep.compose !== "string" || !dep.compose.trim()) throw context(`dependencies.${name}.compose`, dep.compose, "Effective dependency requires compose");
497
- for (const [epName, ep] of Object.entries(dep.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");
498
- assertPrimaryEndpointInvariant(dep.endpoints, { sourceFile, configPath: `dependencies.${name}.endpoints`, stage });
499
- const node = `dependencies.${name}`;
500
- graph.set(node, /* @__PURE__ */ new Set());
501
- for (const ref of dep.dependsOn) {
502
- const match = DEPENDENCY_REFERENCE_PATTERN.exec(ref);
503
- if (!match) throw context(`dependencies.${name}.dependsOn`, ref, "Expected dependencies.<name> lifecycle reference", ref);
504
- const targetName = match[1];
505
- if (targetName === name) throw context(`dependencies.${name}.dependsOn`, ref, "Dependency cannot depend on itself", ref);
506
- const target = dependencies[targetName];
507
- if (!target) throw context(`dependencies.${name}.dependsOn`, ref, "Unknown dependency", ref);
508
- if (!Object.keys(target.endpoints).length) throw context(`dependencies.${name}.dependsOn`, ref, "Lifecycle target is inert and has no endpoints", ref);
509
- graph.get(node).add(`dependencies.${targetName}`);
510
- }
511
- }
512
- assertAcyclicGraph(graph, { sourceFile, stage, composition: "service" });
513
- return effective;
406
+ var originFor = (sourceFile, configPath, layer) => ({ sourceFile, configPath, projectDir: path.dirname(sourceFile), scope: "build", layer });
407
+ var fail = (sourceFile, stage2, configPath, reason, value) => {
408
+ throw new ConfigError({ sourceFile, stage: stage2, composition: "service", configPath, reason, value });
409
+ };
410
+ function resolveBuildStage(build, stage2, sourceFile) {
411
+ const services2 = structuredClone(build.services);
412
+ const origins = /* @__PURE__ */ new Map();
413
+ const envOrigins = /* @__PURE__ */ new Map();
414
+ const requisiteOrigins = /* @__PURE__ */ new Map();
415
+ const layers = [];
416
+ const deletedRequisiteTargets = [];
417
+ const record = (name, entry, layer) => {
418
+ const where = layer === "base" ? `services.${name}` : `${layer}.services.${name}`;
419
+ const origin = originFor(sourceFile, where, layer);
420
+ origins.set(name, origin);
421
+ const env2 = envOrigins.get(name) ?? /* @__PURE__ */ new Map();
422
+ for (const key of Object.keys(entry.env ?? {})) env2.set(key, originFor(sourceFile, `${where}.env.${key}`, layer));
423
+ envOrigins.set(name, env2);
424
+ const edges = requisiteOrigins.get(name) ?? /* @__PURE__ */ new Map();
425
+ for (const [key, value] of Object.entries(entry.requisites ?? {})) {
426
+ if (value === false) edges.delete(key);
427
+ else edges.set(key, originFor(sourceFile, `${where}.requisites.${key}`, layer));
428
+ }
429
+ requisiteOrigins.set(name, edges);
430
+ };
431
+ for (const [name, value] of Object.entries(services2).sort(([a], [b]) => a.localeCompare(b))) record(name, value, "base");
432
+ layers.push({ stage: "base", services: structuredClone(services2), origin: originFor(sourceFile, "services", "base") });
433
+ for (const overlayStage of stageOverlayChain(stage2)) {
434
+ const patches = build[overlayStage]?.services ?? {};
435
+ for (const [name, patch] of Object.entries(patches).sort(([a], [b]) => a.localeCompare(b))) {
436
+ const current = services2[name];
437
+ const where = `${overlayStage}.services.${name}`;
438
+ if (!current && (name === "main" || name === "tester")) fail(sourceFile, stage2, where, "Required special service is missing from base");
439
+ if (current && patch.compose !== void 0 && patch.compose !== current.compose) fail(sourceFile, stage2, `${where}.compose`, `compose is immutable; previous declaration ${origins.get(name)?.configPath}.compose, attempted ${where}.compose`, patch.compose);
440
+ if (!current && name !== "main" && name !== "tester" && (typeof patch.compose !== "string" || !patch.compose.trim())) fail(sourceFile, stage2, `${where}.compose`, "Stage-introduced service requires a complete compose declaration");
441
+ services2[name] = current ? applyServiceOverlay(current, patch) : structuredClone(patch);
442
+ for (const [target, kind] of Object.entries(patch.requisites ?? {})) if (kind === false) deletedRequisiteTargets.push({ target, path: `${where}.requisites.${target}` });
443
+ record(name, patch, overlayStage);
444
+ }
445
+ layers.push({ stage: overlayStage, services: structuredClone(patches), origin: originFor(sourceFile, `${overlayStage}.services`, overlayStage) });
446
+ }
447
+ for (const deleted of deletedRequisiteTargets) if (!(deleted.target in services2)) fail(sourceFile, stage2, deleted.path, "Unknown requisite target", deleted.target);
448
+ for (const [name, value] of Object.entries(services2)) {
449
+ const originPath = origins.get(name)?.configPath ?? `services.${name}`;
450
+ if (name === "tester") {
451
+ if (typeof value.compose !== "string" || typeof value.service !== "string") fail(sourceFile, stage2, originPath, "Effective tester requires compose and service");
452
+ continue;
453
+ }
454
+ const endpoints = value.endpoints ?? {};
455
+ for (const [endpointName, endpoint] of Object.entries(endpoints)) {
456
+ if (!Number.isInteger(endpoint.port) || endpoint.port < 1 || endpoint.port > 65535) fail(sourceFile, stage2, `${originPath}.endpoints.${endpointName}.port`, "Effective endpoint requires port in 1..65535", endpoint.port);
457
+ if (name !== "main" && (typeof endpoint.service !== "string" || !endpoint.service.trim())) fail(sourceFile, stage2, `${originPath}.endpoints.${endpointName}.service`, "Effective ordinary endpoint requires service");
458
+ }
459
+ assertPrimaryEndpointInvariant(endpoints, { sourceFile, stage: stage2, configPath: `${originPath}.endpoints` });
460
+ if (name !== "main" && (typeof value.compose !== "string" || !value.compose.trim())) fail(sourceFile, stage2, `${originPath}.compose`, "Effective ordinary service requires compose");
461
+ if (name !== "main" && Object.keys(endpoints).length === 0 && (typeof value.service !== "string" || !value.service.trim())) fail(sourceFile, stage2, `${originPath}.service`, "endpoint-less service requires service");
462
+ if (name !== "main" && Object.keys(endpoints).length > 0 && typeof value.service === "string") {
463
+ const primary = Object.values(endpoints).find((endpoint) => endpoint.primary);
464
+ if (primary?.service && value.service !== primary.service) fail(sourceFile, stage2, `${originPath}.service`, "top-level service must equal primary endpoint owner", value.service);
465
+ }
466
+ value.env ??= {};
467
+ value.endpoints ??= {};
468
+ value.requisites ??= {};
469
+ value.kind = name === "main" ? "main" : "ordinary";
470
+ }
471
+ return { name: build.name, services: services2, layers, origins, envOrigins, requisiteOrigins, sourceFile, projectDir: path.dirname(sourceFile) };
514
472
  }
515
-
516
- // src/core/config/references.ts
517
- var BUILD_APP = /^app\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
518
- var BUILD_DEP = /^dependencies\.([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
519
- var MESH_APP = /^([a-z][a-z0-9-]*)\.app\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
520
- var MESH_DEP = /^([a-z][a-z0-9-]*)\.dependencies\.([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
521
- function parse2(raw, scope, context) {
522
- let match;
523
- if (scope === "build" && (match = BUILD_APP.exec(raw))) return valid({ raw, scope, target: "app", endpoint: match[1], property: match[2] }, context);
524
- if (scope === "build" && (match = BUILD_DEP.exec(raw))) return valid({ raw, scope, target: "dependency", dependency: match[1], endpoint: match[2], property: match[3] }, context);
525
- if (scope === "mesh" && (match = MESH_APP.exec(raw))) return valid({ raw, scope, meshService: match[1], target: "app", endpoint: match[2], property: match[3] }, context);
526
- if (scope === "mesh" && (match = MESH_DEP.exec(raw))) return valid({ raw, scope, meshService: match[1], target: "dependency", dependency: match[2], endpoint: match[3], property: match[4] }, context);
527
- throw new ConfigError({ ...context, referencedObject: raw, value: raw, reason: `Invalid ${scope} endpoint reference` });
473
+ function normalizeProjectName(name, projectDir) {
474
+ let normalized = name.toLowerCase().replace(/[^a-z0-9_-]/g, "-").replace(/^[-_]+/, "").replace(/[-_]+$/, "");
475
+ if (!normalized || !/^[a-z0-9]/.test(normalized)) {
476
+ if (projectDir) {
477
+ const hash = crypto.createHash("sha1").update(path.resolve(projectDir)).digest("hex").slice(0, 7);
478
+ return `project-${hash}`;
479
+ }
480
+ return "project";
481
+ }
482
+ return normalized;
528
483
  }
529
- function valid(ref, context) {
530
- if (!ENDPOINT_PROPERTIES.includes(ref.property)) {
531
- throw new ConfigError({ ...context, referencedObject: ref.raw, value: ref.property, reason: "Unknown endpoint property" });
484
+ function deriveProjectName(name, stage2, projectDir, options = {}) {
485
+ let base = normalizeProjectName(name, projectDir);
486
+ if (options.hash && projectDir) {
487
+ const hash = crypto.createHash("sha1").update(path.resolve(projectDir)).digest("hex").slice(0, 7);
488
+ base = `${base}-${hash}`;
489
+ }
490
+ if (!stage2) {
491
+ return base;
492
+ }
493
+ const s = stage2.toLowerCase();
494
+ if (s === "dev") {
495
+ return base;
496
+ }
497
+ if (s === "prod") {
498
+ return `${base}-prod`;
499
+ }
500
+ if (s === "test" || s === "test-unit") {
501
+ return `${base}-test`;
532
502
  }
533
- return ref;
503
+ if (s === "e2e" || s === "test-e2e") {
504
+ return `${base}-e2e`;
505
+ }
506
+ return `${base}-${s}`;
534
507
  }
535
- function collectBuilderReferences(value, scope, context) {
536
- const protectedValue = value.replace(/\$\$/g, "\0DOLLAR\0");
537
- const refs = [];
538
- for (const match of protectedValue.matchAll(/\$\{([^}]*)\}/g)) refs.push(parse2(match[1], scope, context));
539
- return refs;
508
+ var EXEC_MODE_KEY = "EXEC_MODE";
509
+ var INFRA_MODE_KEY = "INFRA_MODE";
510
+ var PORT_KEY = "PORT";
511
+ function assertNoBuilderOwnedEnvKeys(env2, keys, context) {
512
+ for (const key of keys) {
513
+ if (!(key in env2)) continue;
514
+ throw new ConfigError({ sourceFile: context.sourceFile, configPath: `${context.configPath}.${key}`, stage: context.stage, composition: context.composition, value: env2[key], reason: `User-controlled environment cannot set Builder-owned key "${key}"` });
515
+ }
540
516
  }
541
- function interpolateBuilderReferences(value, scope, resolve, context) {
542
- const sentinel = "\0DOLLAR\0";
543
- return value.replace(/\$\$/g, sentinel).replace(/\$\{([^}]*)\}/g, (_whole, body) => {
544
- const ref = parse2(body, scope, context);
545
- return resolve(ref, context);
546
- }).replaceAll(sentinel, "$");
547
- }
548
- function assertTesterReferencesArePublic(env, scope, baseContext) {
549
- for (const [key, value] of Object.entries(env)) {
550
- const context = { ...baseContext, configPath: `${baseContext.configPath}.${key}` };
551
- for (const ref of collectBuilderReferences(value, scope, context)) {
552
- if (!PUBLIC_ENDPOINT_PROPERTIES.has(ref.property)) {
553
- throw new ConfigError({ ...context, referencedObject: ref.raw, value: ref.raw, reason: "Tester references may use only public endpoint properties" });
554
- }
555
- }
517
+ function assertDotenvDoesNotDefineKeys(filePath, keys, context) {
518
+ if (!fs.existsSync(filePath)) return;
519
+ const forbidden = new Set(keys), lines = fs.readFileSync(filePath, "utf8").split(/\r?\n/);
520
+ for (let index = 0; index < lines.length; index += 1) {
521
+ const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*[:=]/.exec(lines[index]);
522
+ if (!match) continue;
523
+ const key = match[1];
524
+ if (!forbidden.has(key)) continue;
525
+ throw new ConfigError({ sourceFile: filePath, configPath: `${context.configPath}.${key}`, stage: context.stage, composition: context.composition, value: `line ${index + 1}`, reason: `Environment file cannot set Builder-owned key "${key}"` });
556
526
  }
557
527
  }
558
528
 
529
+ // src/core/config/executionProfile.ts
530
+ function executionProfile(stage2, composition, full = false) {
531
+ if (composition === "mesh" && stage2 === "test") throw new Error("Mesh test is a workflow, not a configuration stage");
532
+ if (stage2 === "dev") return { configStage: stage2, envStage: stage2, mainTarget: "dev", execMode: "dev", infraMode: composition === "mesh" || full ? "integrated" : "isolated", attachTester: false };
533
+ if (stage2 === "test") return { configStage: stage2, envStage: stage2, mainTarget: "test", execMode: "test", infraMode: "isolated", attachTester: false };
534
+ return { configStage: stage2, envStage: stage2, mainTarget: "prod", execMode: "prod", infraMode: "integrated", attachTester: stage2 === "e2e" };
535
+ }
536
+
559
537
  // src/errors/PortConflictError.ts
560
538
  var PortConflictError = class extends ConfigError {
561
539
  port;
562
540
  firstOwner;
563
541
  secondOwner;
564
- constructor(port, firstOwner, secondOwner, stage, sourceFile = "Builder effective composition", composition) {
565
- super({ sourceFile, configPath: secondOwner, value: port, stage, ...composition ? { composition } : {}, referencedObject: firstOwner, reason: `Host port ${port} is claimed by both ${firstOwner} and ${secondOwner}. Builder does not remap fixed public ports.` });
542
+ constructor(port2, firstOwner, secondOwner, stage2, sourceFile = "Builder effective composition", composition) {
543
+ super({ sourceFile, configPath: secondOwner, value: port2, stage: stage2, ...composition ? { composition } : {}, referencedObject: firstOwner, reason: `Host port ${port2} is claimed by both ${firstOwner} and ${secondOwner}. Builder does not remap fixed public ports.` });
566
544
  this.name = "PortConflictError";
567
- this.port = port;
545
+ this.port = port2;
568
546
  this.firstOwner = firstOwner;
569
547
  this.secondOwner = secondOwner;
570
548
  }
571
549
  };
572
550
 
573
551
  // src/core/config/hostPorts.ts
574
- function isHostPortAvailableSync(port) {
575
- 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)));`;
552
+ function isHostPortAvailableSync(port2) {
553
+ const script = `const net=require('node:net');const s=net.createServer();s.once('error',()=>process.exit(1));s.listen(${port2},'${PUBLIC_HOST}',()=>s.close(()=>process.exit(0)));`;
576
554
  const result = spawnSync(process.execPath, ["-e", script], { stdio: "ignore", timeout: 3e3 });
577
555
  return result.status === 0;
578
556
  }
579
- function allocateHostPorts(projectDir, stage, intentsInDeterministicOrder, validationMode = false, context) {
557
+ function allocateHostPorts(projectDir, stage2, intentsInDeterministicOrder, validationMode = false, context, adapters = {}) {
558
+ const probe = adapters.probe ?? isHostPortAvailableSync;
580
559
  const reserved = /* @__PURE__ */ new Map(), allocated = /* @__PURE__ */ new Map();
581
560
  for (const intent of intentsInDeterministicOrder) if (typeof intent.requested === "number") {
582
561
  const owner = reserved.get(intent.requested);
583
- if (owner) throw new PortConflictError(intent.requested, owner, intent.logicalPath, stage, context?.sourceFile, context?.composition);
562
+ if (owner) throw new PortConflictError(intent.requested, owner, intent.logicalPath, stage2, context?.sourceFile, context?.composition);
584
563
  reserved.set(intent.requested, intent.logicalPath);
585
564
  allocated.set(intent.logicalPath, intent.requested);
586
565
  }
@@ -588,7 +567,7 @@ function allocateHostPorts(projectDir, stage, intentsInDeterministicOrder, valid
588
567
  let placeholder = 6e4;
589
568
  for (const intent of intentsInDeterministicOrder) if (intent.requested === "AUTO") {
590
569
  while (reserved.has(placeholder)) placeholder--;
591
- if (placeholder < 1) throw new ConfigError({ ...context ?? {}, configPath: intent.logicalPath, stage, value: intent.requested, reason: "No validation placeholder port is available" });
570
+ if (placeholder < 1) throw new ConfigError({ ...context ?? {}, configPath: intent.logicalPath, stage: stage2, value: intent.requested, reason: "No validation placeholder port is available" });
592
571
  reserved.set(placeholder, intent.logicalPath);
593
572
  allocated.set(intent.logicalPath, placeholder--);
594
573
  }
@@ -604,81 +583,309 @@ function allocateHostPorts(projectDir, stage, intentsInDeterministicOrder, valid
604
583
  } catch {
605
584
  cached = {};
606
585
  }
607
- const nextCache = { ...cached };
608
586
  for (const intent of intentsInDeterministicOrder) if (intent.requested === "AUTO") {
609
587
  const prior = cached[intent.logicalPath];
610
- let selected = typeof prior === "number" && Number.isInteger(prior) && prior >= 1 && prior <= 65535 && !reserved.has(prior) && isHostPortAvailableSync(prior) ? prior : void 0;
588
+ let selected = typeof prior === "number" && Number.isInteger(prior) && prior >= 1 && prior <= 65535 && !reserved.has(prior) && probe(prior) ? prior : void 0;
611
589
  if (selected === void 0) {
612
- 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));
613
- selected = scan.find((p) => !reserved.has(p) && isHostPortAvailableSync(p));
590
+ const scan = adapters.candidatePorts ?? [...Array(65536 - AUTO_PORT_SCAN_START).keys()].map((i) => i + AUTO_PORT_SCAN_START).concat([...Array(19999 - 1024 + 1).keys()].map((i) => i + 1024));
591
+ selected = scan.find((p) => p >= 1 && p <= 65535 && !reserved.has(p) && probe(p));
614
592
  }
615
- if (selected === void 0) throw new ConfigError({ sourceFile: context?.sourceFile ?? "Builder effective composition", ...context?.composition ? { composition: context.composition } : {}, configPath: intent.logicalPath, stage, value: intent.requested, reason: "No available host port could be allocated" });
593
+ if (selected === void 0) throw new ConfigError({ sourceFile: context?.sourceFile ?? "Builder effective composition", ...context?.composition ? { composition: context.composition } : {}, configPath: intent.logicalPath, stage: stage2, value: intent.requested, reason: "No available host port could be allocated" });
616
594
  reserved.set(selected, intent.logicalPath);
617
595
  allocated.set(intent.logicalPath, selected);
618
- nextCache[intent.logicalPath] = selected;
619
- }
620
- if (intentsInDeterministicOrder.some((i) => i.requested === "AUTO")) {
621
- mkdirSync(path.dirname(cachePath), { recursive: true });
622
- const temp = `${cachePath}.${process.pid}.tmp`;
623
- writeFileSync(temp, JSON.stringify({ version: AUTO_PORT_CACHE_VERSION, allocations: nextCache }, null, 2));
624
- renameSync(temp, cachePath);
625
596
  }
626
597
  return allocated;
627
598
  }
628
- var EXEC_MODE_KEY = "EXEC_MODE";
629
- var INFRA_MODE_KEY = "INFRA_MODE";
630
- var PORT_KEY = "PORT";
631
- function assertNoBuilderOwnedEnvKeys(env, keys, context) {
632
- for (const key of keys) {
633
- if (!(key in env)) continue;
634
- throw new ConfigError({ sourceFile: context.sourceFile, configPath: `${context.configPath}.${key}`, stage: context.stage, composition: context.composition, value: env[key], reason: `User-controlled environment cannot set Builder-owned key "${key}"` });
599
+ function persistHostPortAllocations(projectDir, allocations) {
600
+ if (!allocations.size) return;
601
+ const cachePath = path.join(projectDir, AUTO_PORT_CACHE_RELATIVE_PATH);
602
+ let cached = {};
603
+ try {
604
+ const parsed = JSON.parse(readFileSync(cachePath, "utf8"));
605
+ if (parsed?.version === AUTO_PORT_CACHE_VERSION && parsed.allocations && typeof parsed.allocations === "object") cached = parsed.allocations;
606
+ } catch {
635
607
  }
608
+ mkdirSync(path.dirname(cachePath), { recursive: true });
609
+ const temp = `${cachePath}.${process.pid}.tmp`;
610
+ writeFileSync(temp, JSON.stringify({ version: AUTO_PORT_CACHE_VERSION, allocations: { ...cached, ...Object.fromEntries(allocations) } }, null, 2));
611
+ renameSync(temp, cachePath);
636
612
  }
637
- function assertDotenvDoesNotDefineKeys(filePath, keys, context) {
638
- if (!fs.existsSync(filePath)) return;
639
- const forbidden = new Set(keys), lines = fs.readFileSync(filePath, "utf8").split(/\r?\n/);
640
- for (let index = 0; index < lines.length; index += 1) {
641
- const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(lines[index]);
642
- if (!match) continue;
643
- const key = match[1];
644
- if (!forbidden.has(key)) continue;
645
- throw new ConfigError({ sourceFile: filePath, configPath: `${context.configPath}.${key}`, stage: context.stage, composition: context.composition, value: `line ${index + 1}`, reason: `Environment file cannot set Builder-owned key "${key}"` });
613
+ function removeHostPortAllocations(projectDir, keys) {
614
+ if (!keys.length) return;
615
+ const cachePath = path.join(projectDir, AUTO_PORT_CACHE_RELATIVE_PATH);
616
+ if (!existsSync(cachePath)) return;
617
+ const parsed = JSON.parse(readFileSync(cachePath, "utf8"));
618
+ if (parsed?.version !== AUTO_PORT_CACHE_VERSION || !parsed.allocations || typeof parsed.allocations !== "object") return;
619
+ const remaining = { ...parsed.allocations };
620
+ for (const key of keys) delete remaining[key];
621
+ if (!Object.keys(remaining).length) {
622
+ unlinkSync(cachePath);
623
+ return;
646
624
  }
625
+ const temp = `${cachePath}.${process.pid}.tmp`;
626
+ writeFileSync(temp, JSON.stringify({ version: AUTO_PORT_CACHE_VERSION, allocations: remaining }, null, 2));
627
+ renameSync(temp, cachePath);
647
628
  }
648
- function normalizeProjectName(name, projectDir) {
649
- let normalized = name.toLowerCase().replace(/[^a-z0-9_-]/g, "-").replace(/^[-_]+/, "").replace(/[-_]+$/, "");
650
- if (!normalized || !/^[a-z0-9]/.test(normalized)) {
651
- if (projectDir) {
652
- const hash = crypto.createHash("sha1").update(path.resolve(projectDir)).digest("hex").slice(0, 7);
653
- return `project-${hash}`;
654
- }
655
- return "project";
629
+
630
+ // src/core/config/types.ts
631
+ var nodeId = (meshRoot, sourceService) => JSON.stringify([meshRoot ?? null, sourceService]);
632
+ var displayNode = (id) => {
633
+ const [root, service] = JSON.parse(id);
634
+ return root ? `${root}.source.${service}` : service;
635
+ };
636
+
637
+ // src/core/config/publication.ts
638
+ function resolvePublicationIntent(graph, stage2, composition, publish, meshSourceFile, publishOrigins) {
639
+ const result = [];
640
+ const append = (id, endpoint, origin, selector) => {
641
+ const node = graph.nodes.get(id);
642
+ if (!node) throw new ConfigError({ sourceFile: origin.sourceFile, configPath: origin.configPath, stage: stage2, composition, referencedObject: selector, reason: "publish selector target is not reachable" });
643
+ const def = node.declaration.endpoints[endpoint];
644
+ if (!def) throw new ConfigError({ sourceFile: origin.sourceFile, configPath: origin.configPath, stage: stage2, composition, referencedObject: selector, reason: "publish selector target endpoint does not exist" });
645
+ if (def.publicPort === void 0) throw new ConfigError({ sourceFile: origin.sourceFile, configPath: origin.configPath, stage: stage2, composition, referencedObject: selector, reason: "publish selector requires an endpoint with publicPort capability" });
646
+ result.push({ nodeId: id, endpoint, requestedPort: def.publicPort, origin, logicalPath: `${displayNode(id)}.endpoints.${endpoint}` });
647
+ };
648
+ if (composition === "service") {
649
+ for (const [id, node] of graph.nodes) for (const [endpoint, def] of Object.entries(node.declaration.endpoints)) if (def.publicPort !== void 0) append(id, endpoint, node.origin, `${displayNode(id)}.endpoints.${endpoint}`);
650
+ } else if (publish) for (const [root, selectors] of publish) {
651
+ const main = nodeId(root, "main"), closure = graph.closures.get(main) ?? /* @__PURE__ */ new Set();
652
+ for (const selector of new Set(selectors)) {
653
+ const match = /^([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)$/.exec(selector);
654
+ const mainOrigin = graph.nodes.get(main)?.origin;
655
+ if (!mainOrigin) continue;
656
+ const origin = publishOrigins?.get(root) ?? (meshSourceFile ? { ...mainOrigin, sourceFile: meshSourceFile, configPath: `services.${root}.publish`, scope: "mesh" } : mainOrigin);
657
+ if (!match) throw new ConfigError({ sourceFile: origin.sourceFile, configPath: origin.configPath, stage: stage2, composition, referencedObject: selector, reason: "Invalid publish selector; expected <local>.endpoints.<endpoint>" });
658
+ const id = nodeId(root, match[1]);
659
+ if (!closure.has(id)) throw new ConfigError({ sourceFile: origin.sourceFile, configPath: origin.configPath, stage: stage2, composition, referencedObject: selector, reason: "publish selector target is not in source main requisite closure" });
660
+ append(id, match[2], origin, selector);
661
+ }
662
+ }
663
+ result.sort((a, b) => `${a.nodeId}:${a.endpoint}`.localeCompare(`${b.nodeId}:${b.endpoint}`));
664
+ const fixed = /* @__PURE__ */ new Map();
665
+ for (const item of result) if (typeof item.requestedPort === "number") {
666
+ const prior = fixed.get(item.requestedPort);
667
+ if (prior) throw new PortConflictError(item.requestedPort, prior.logicalPath, item.logicalPath, stage2, item.origin.sourceFile, composition);
668
+ fixed.set(item.requestedPort, item);
656
669
  }
657
- return normalized;
670
+ return result;
658
671
  }
659
- function deriveProjectName(name, stage, projectDir, options = {}) {
660
- let base = normalizeProjectName(name, projectDir);
661
- if (options.hash && projectDir) {
662
- const hash = crypto.createHash("sha1").update(path.resolve(projectDir)).digest("hex").slice(0, 7);
663
- base = `${base}-${hash}`;
664
- }
665
- if (!stage) {
666
- return base;
667
- }
668
- const s = stage.toLowerCase();
669
- if (s === "dev") {
670
- return base;
671
- }
672
- if (s === "prod") {
673
- return `${base}-prod`;
672
+
673
+ // src/core/config/references.ts
674
+ var token = /^([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
675
+ var sourceToken = /^source\.([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
676
+ var meshToken = /^([a-z][a-z0-9-]*)\.source\.([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
677
+ function fail2(context, raw, reason) {
678
+ throw new ConfigError({ sourceFile: context.origin.sourceFile, configPath: context.origin.configPath, stage: context.stage, composition: context.composition, referencedObject: raw, reason });
679
+ }
680
+ function parseBuilderReference(raw, context) {
681
+ let target, endpoint, property;
682
+ let match;
683
+ if (context.origin.scope === "build" && (match = token.exec(raw))) {
684
+ target = nodeId(context.origin.meshRoot, match[1]);
685
+ endpoint = match[2];
686
+ property = match[3];
687
+ } else if (context.origin.scope === "mesh" && (match = sourceToken.exec(raw))) {
688
+ if (!context.origin.meshRoot) fail2(context, raw, "source-relative reference requires mesh root");
689
+ target = nodeId(context.origin.meshRoot, match[1]);
690
+ endpoint = match[2];
691
+ property = match[3];
692
+ } else if (context.origin.scope === "mesh" && (match = meshToken.exec(raw))) {
693
+ target = nodeId(match[1], match[2]);
694
+ endpoint = match[3];
695
+ property = match[4];
696
+ } else fail2(context, raw, "Invalid V3 endpoint reference grammar");
697
+ if (!ENDPOINT_PROPERTIES.includes(property)) fail2(context, raw, "Unknown endpoint property");
698
+ return { raw, target, endpoint, property, origin: context.origin };
699
+ }
700
+ function resolveBuilderReference(ref, context) {
701
+ const target = context.graph.nodes.get(ref.target);
702
+ if (!target || context.consumer && !context.graph.closures.get(context.consumer)?.has(ref.target)) fail2(context, ref.raw, `outside effective requisite closure: ${context.consumer ? displayNode(context.consumer) : "tester"} -> ${displayNode(ref.target)}`);
703
+ const endpoint = context.endpoints.get(ref.target)?.[ref.endpoint];
704
+ if (!endpoint) fail2(context, ref.raw, `Unknown endpoint ${displayNode(ref.target)}.endpoints.${ref.endpoint}`);
705
+ return resolveEndpointProperty(endpoint, ref.property, { sourceFile: context.origin.sourceFile, configPath: context.origin.configPath, stage: context.stage, composition: context.composition, referencedObject: ref.raw });
706
+ }
707
+ function interpolateBuilderReferences(value, context) {
708
+ const sentinel = "\0DOLLAR\0";
709
+ const protectedValue = value.replace(/\$\$/g, sentinel);
710
+ if (protectedValue.includes("${") && /\$\{[^}]*$/.test(protectedValue)) fail2(context, protectedValue, "Malformed Builder endpoint reference");
711
+ return protectedValue.replace(/\$\{([^}]*)\}/g, (_whole, body) => resolveBuilderReference(parseBuilderReference(body, context), context)).replaceAll(sentinel, "$");
712
+ }
713
+
714
+ // src/core/config/serviceGraph.ts
715
+ var fail3 = (origin, stage2, reason, referencedObject) => {
716
+ throw new ConfigError({ sourceFile: origin.sourceFile, configPath: origin.configPath, stage: stage2, composition: origin.scope === "mesh" ? "mesh" : "service", ...referencedObject ? { referencedObject } : {}, reason });
717
+ };
718
+ function buildDeclaredGraph(input) {
719
+ const edges = [];
720
+ for (const node of input.nodes.values()) for (const [key, kind] of Object.entries(node.declaration.requisites)) {
721
+ const origin = node.requisiteOrigins.get(key) ?? node.origin;
722
+ let target;
723
+ if (key.startsWith("@mesh:")) target = nodeId(key.slice(6), "main");
724
+ else target = nodeId(node.meshRoot, key);
725
+ const displayKey = key.replace(/^@mesh:/, "");
726
+ if (key === "tester" || key === "@mesh:tester") fail3(origin, input.stage, "tester cannot be a requisite target", displayKey);
727
+ if (!input.nodes.has(target)) fail3(origin, input.stage, "Unknown requisite target", displayKey);
728
+ edges.push({ consumer: node.id, target, kind, origin });
729
+ }
730
+ edges.sort((a, b) => `${a.consumer}:${a.target}:${a.kind}`.localeCompare(`${b.consumer}:${b.target}:${b.kind}`));
731
+ return { nodes: input.nodes, roots: [...input.roots].sort(), edges };
732
+ }
733
+ function computeClosure(start, adjacency) {
734
+ const visited = /* @__PURE__ */ new Set();
735
+ const stack = [start];
736
+ while (stack.length) {
737
+ const id = stack.pop();
738
+ if (visited.has(id)) continue;
739
+ visited.add(id);
740
+ for (const edge of adjacency.get(id) ?? []) stack.push(edge.target);
741
+ }
742
+ return visited;
743
+ }
744
+ function selectReachableGraph(declared, profile) {
745
+ const adjacency = /* @__PURE__ */ new Map();
746
+ for (const edge of declared.edges) {
747
+ const list = adjacency.get(edge.consumer) ?? [];
748
+ list.push(edge);
749
+ adjacency.set(edge.consumer, list);
750
+ }
751
+ const active = /* @__PURE__ */ new Set();
752
+ if (profile.infraMode === "isolated") for (const root of declared.roots) active.add(root);
753
+ else for (const root of declared.roots) for (const id of computeClosure(root, adjacency)) active.add(id);
754
+ const nodes = new Map([...declared.nodes].filter(([id]) => active.has(id)));
755
+ const edges = profile.infraMode === "isolated" ? [] : declared.edges.filter((edge) => active.has(edge.consumer) && active.has(edge.target));
756
+ const activeAdjacency = /* @__PURE__ */ new Map();
757
+ for (const edge of edges) {
758
+ const list = activeAdjacency.get(edge.consumer) ?? [];
759
+ list.push(edge);
760
+ activeAdjacency.set(edge.consumer, list);
761
+ }
762
+ const closures = /* @__PURE__ */ new Map();
763
+ for (const id of nodes.keys()) closures.set(id, computeClosure(id, activeAdjacency));
764
+ const lifecycle = /* @__PURE__ */ new Map();
765
+ for (const id of nodes.keys()) lifecycle.set(id, "long-running");
766
+ const classification = /* @__PURE__ */ new Map();
767
+ for (const edge of edges) {
768
+ const kinds = classification.get(edge.target) ?? /* @__PURE__ */ new Map();
769
+ kinds.set(edge.kind, edge);
770
+ classification.set(edge.target, kinds);
771
+ }
772
+ for (const [id, kinds] of classification) {
773
+ if (kinds.has("dependency") && kinds.has("prerequisite")) {
774
+ const dep = kinds.get("dependency"), pre = kinds.get("prerequisite");
775
+ fail3(pre.origin, profile.stage, `Target ${displayNode(id)} is both dependency and prerequisite; dependency at ${dep.origin.sourceFile}:${dep.origin.configPath}, prerequisite at ${pre.origin.sourceFile}:${pre.origin.configPath}`, displayNode(id));
776
+ }
777
+ if (kinds.has("prerequisite")) {
778
+ if (nodes.get(id)?.kind === "main") fail3(kinds.get("prerequisite").origin, profile.stage, "main cannot be a prerequisite", displayNode(id));
779
+ lifecycle.set(id, "prerequisite");
780
+ }
781
+ }
782
+ const graph = { nodes, roots: declared.roots.filter((id) => active.has(id)), edges, closures, lifecycle };
783
+ validateGraphLifecycle(graph, profile.stage);
784
+ return graph;
785
+ }
786
+ function validateGraphLifecycle(graph, stage2 = "dev") {
787
+ const adjacency = /* @__PURE__ */ new Map();
788
+ for (const edge of graph.edges) if (edge.kind !== "requirement") {
789
+ const list = adjacency.get(edge.consumer) ?? [];
790
+ list.push(edge);
791
+ adjacency.set(edge.consumer, list);
792
+ }
793
+ const gray = /* @__PURE__ */ new Set(), black = /* @__PURE__ */ new Set(), stack = [];
794
+ const visit = (id) => {
795
+ if (black.has(id)) return;
796
+ gray.add(id);
797
+ for (const edge of adjacency.get(id) ?? []) {
798
+ if (gray.has(edge.target)) {
799
+ const first = stack.findIndex((item) => item.consumer === edge.target);
800
+ const cycle = [...stack.slice(Math.max(0, first)), edge].map((item) => `${displayNode(item.consumer)} -${item.kind}-> ${displayNode(item.target)}`).join("; ");
801
+ fail3(edge.origin, stage2, `ordering cycle: ${cycle}`, displayNode(edge.target));
802
+ }
803
+ stack.push(edge);
804
+ visit(edge.target);
805
+ stack.pop();
806
+ }
807
+ gray.delete(id);
808
+ black.add(id);
809
+ };
810
+ for (const id of graph.nodes.keys()) visit(id);
811
+ }
812
+
813
+ // src/core/config/lifecycleGraph.ts
814
+ function assertAcyclicGraph(graph, context) {
815
+ const visiting = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set(), stack = [];
816
+ const visit = (node) => {
817
+ if (visiting.has(node)) {
818
+ const start = stack.indexOf(node);
819
+ const cycle = [...stack.slice(start), node];
820
+ throw new ConfigError({ ...context, configPath: "services.depends_on", referencedObject: cycle.join(" -> "), reason: `Lifecycle cycle detected: ${cycle.join(" -> ")}` });
821
+ }
822
+ if (visited.has(node)) return;
823
+ visiting.add(node);
824
+ stack.push(node);
825
+ for (const next of graph.get(node) ?? []) visit(next);
826
+ stack.pop();
827
+ visiting.delete(node);
828
+ visited.add(node);
829
+ };
830
+ for (const node of graph.keys()) visit(node);
831
+ }
832
+
833
+ // src/core/composition/assertComposeLifecycleAcyclic.ts
834
+ function assertComposeLifecycleAcyclic(services2, context) {
835
+ const graph = new Map(
836
+ Object.keys(services2).map((name) => [name, /* @__PURE__ */ new Set()])
837
+ );
838
+ for (const [name, service] of Object.entries(services2)) {
839
+ const value = service.depends_on;
840
+ const targets = Array.isArray(value) ? value.filter((item) => typeof item === "string") : value && typeof value === "object" ? Object.keys(value) : [];
841
+ for (const target of targets) {
842
+ if (graph.has(target)) graph.get(name).add(target);
843
+ }
674
844
  }
675
- if (s === "test" || s === "test-unit") {
676
- return `${base}-test`;
845
+ assertAcyclicGraph(graph, context);
846
+ }
847
+
848
+ // src/core/composition/composeDependsOn.ts
849
+ function normalizeComposeDependsOn(value) {
850
+ const entries2 = Array.isArray(value) ? value.filter((item) => typeof item === "string").map((name) => [name, { condition: "service_started" }]) : value && typeof value === "object" ? Object.entries(value) : [];
851
+ return Object.fromEntries(entries2.map(([name, raw]) => [name, raw && typeof raw === "object" && !Array.isArray(raw) ? { condition: "service_started", ...raw } : { condition: "service_started" }]));
852
+ }
853
+ function addComposeCondition(service, target, condition) {
854
+ service.depends_on = { ...normalizeComposeDependsOn(service.depends_on), [target]: { condition } };
855
+ }
856
+
857
+ // src/core/composition/composeEnvironment.ts
858
+ function normalizeComposeEnvironment(value, context) {
859
+ const result = {};
860
+ if (value == null) return result;
861
+ if (Array.isArray(value)) {
862
+ for (const item of value) {
863
+ if (typeof item !== "string") throw new ConfigError({ configPath: context, value: item, reason: "Compose environment entries must be strings" });
864
+ const at = item.indexOf("=");
865
+ if (at < 0) {
866
+ result[item] = null;
867
+ continue;
868
+ }
869
+ result[item.slice(0, at)] = item.slice(at + 1);
870
+ }
871
+ return result;
677
872
  }
678
- if (s === "e2e" || s === "test-e2e") {
679
- return `${base}-e2e`;
873
+ if (typeof value !== "object") throw new ConfigError({ configPath: context, value, reason: "Compose environment must be a map or list" });
874
+ for (const [key, val] of Object.entries(value)) {
875
+ if (val === null || val === void 0) {
876
+ result[key] = null;
877
+ continue;
878
+ }
879
+ if (typeof val === "object") throw new ConfigError({ configPath: `${context}.${key}`, value: val, reason: "Compose environment value must be scalar" });
880
+ result[key] = String(val);
680
881
  }
681
- return `${base}-${s}`;
882
+ return result;
883
+ }
884
+
885
+ // src/core/composition/composeNetworks.ts
886
+ function normalizeNetworks(value) {
887
+ if (Array.isArray(value)) return Object.fromEntries(value.filter((name) => typeof name === "string").map((name) => [name, null]));
888
+ return value && typeof value === "object" ? { ...value } : {};
682
889
  }
683
890
  function parseVolume(mount) {
684
891
  if (typeof mount === "string") {
@@ -722,8 +929,8 @@ function isHostFilesystemRoot(source) {
722
929
  }
723
930
  return path.posix.normalize(normalized) === "/";
724
931
  }
725
- function anonymousVolumeServices(services) {
726
- return Object.entries(services).filter(([, service]) => Array.isArray(service.volumes) && service.volumes.some(isAnonymousVolume)).map(([name]) => name);
932
+ function anonymousVolumeServices(services2) {
933
+ return Object.entries(services2).filter(([, service]) => Array.isArray(service.volumes) && service.volumes.some(isAnonymousVolume)).map(([name]) => name);
727
934
  }
728
935
  var posix = (p) => p.replace(/\\/g, "/");
729
936
  function rebase(p, base, out) {
@@ -819,36 +1026,89 @@ function rebaseAppOverridePaths(document, serviceProjectDir, outputProjectDir) {
819
1026
  }
820
1027
  return doc;
821
1028
  }
822
-
823
- // src/core/composition/composeEnvironment.ts
824
- function normalizeComposeEnvironment(value, context) {
825
- const result = {};
826
- if (value == null) return result;
827
- if (Array.isArray(value)) {
828
- for (const item of value) {
829
- if (typeof item !== "string") throw new ConfigError({ configPath: context, value: item, reason: "Compose environment entries must be strings" });
830
- const at = item.indexOf("=");
831
- if (at < 0) {
832
- result[item] = null;
833
- continue;
834
- }
835
- result[item.slice(0, at)] = item.slice(at + 1);
1029
+ var GeneratedComposeNameAllocator = class {
1030
+ occupied;
1031
+ allocated = /* @__PURE__ */ new Map();
1032
+ constructor(initialNames = []) {
1033
+ this.occupied = new Set(initialNames);
1034
+ }
1035
+ allocate(identity, hint) {
1036
+ const existing = this.allocated.get(identity);
1037
+ if (existing) return existing;
1038
+ const hash = createHash("sha256").update(identity).digest("hex");
1039
+ const safeHint = hint.replace(/[^a-zA-Z0-9_-]/g, "-") || "item";
1040
+ let rootMain = false;
1041
+ try {
1042
+ const parts = JSON.parse(identity);
1043
+ rootMain = Array.isArray(parts) && parts.length === 2 && parts[1] === "main" && typeof parts[0] === "string" && parts[0].startsWith("[");
1044
+ } catch {
1045
+ rootMain = false;
836
1046
  }
837
- return result;
1047
+ for (const candidate of [
1048
+ ...rootMain ? [safeHint] : [],
1049
+ ...[12, 16, 24, 32, 64].map((length) => `${safeHint}-${hash.slice(0, length)}`)
1050
+ ]) {
1051
+ if (this.occupied.has(candidate)) continue;
1052
+ this.occupied.add(candidate);
1053
+ this.allocated.set(identity, candidate);
1054
+ return candidate;
1055
+ }
1056
+ throw new Error(`Unable to allocate unique Compose name for ${identity}`);
838
1057
  }
839
- if (typeof value !== "object") throw new ConfigError({ configPath: context, value, reason: "Compose environment must be a map or list" });
840
- for (const [key, val] of Object.entries(value)) {
841
- if (val === null || val === void 0) {
842
- result[key] = null;
843
- continue;
1058
+ assertUnique() {
1059
+ if (new Set(this.allocated.values()).size !== this.allocated.size) {
1060
+ throw new Error("Internal generated Compose name collision");
844
1061
  }
845
- if (typeof val === "object") throw new ConfigError({ configPath: `${context}.${key}`, value: val, reason: "Compose environment value must be scalar" });
846
- result[key] = String(val);
847
1062
  }
848
- return result;
1063
+ };
1064
+ function loadComposeDocument(absolutePath, context) {
1065
+ const fail4 = (reason, value) => {
1066
+ throw new ConfigError({ ...context, sourceFile: absolutePath, ...{} , reason });
1067
+ };
1068
+ if (!existsSync(absolutePath) || !statSync(absolutePath).isFile()) throw new ConfigError({ ...context, value: absolutePath, reason: "Compose file does not exist or is not a regular file" });
1069
+ let text = "";
1070
+ try {
1071
+ text = readFileSync(absolutePath, "utf8");
1072
+ } catch (e) {
1073
+ fail4(`Failed to read Compose file: ${String(e)}`);
1074
+ }
1075
+ let docs = [];
1076
+ try {
1077
+ docs = parseAllDocuments(text, { prettyErrors: true });
1078
+ } catch (e) {
1079
+ fail4(`Invalid Compose YAML: ${String(e)}`);
1080
+ }
1081
+ if (docs.length !== 1) fail4("Compose file must contain exactly one YAML document");
1082
+ const errors = docs[0].errors;
1083
+ if (errors.length) fail4(`Invalid Compose YAML: ${errors.map((e) => e.message).join("; ")}`);
1084
+ let parsed;
1085
+ try {
1086
+ parsed = parse(text);
1087
+ } catch (e) {
1088
+ fail4(`Invalid Compose YAML: ${String(e)}`);
1089
+ }
1090
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) fail4("Compose root must be an object");
1091
+ return parsed;
1092
+ }
1093
+
1094
+ // src/core/composition/mergeMainOverride.ts
1095
+ function isMap(value) {
1096
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
1097
+ const prototype = Object.getPrototypeOf(value);
1098
+ return prototype === Object.prototype || prototype === null;
1099
+ }
1100
+ function mergeValue(inherited, overlay) {
1101
+ if (overlay === void 0) return structuredClone(inherited);
1102
+ if (!isMap(inherited) || !isMap(overlay)) return structuredClone(overlay);
1103
+ return Object.fromEntries(
1104
+ [.../* @__PURE__ */ new Set([...Object.keys(inherited), ...Object.keys(overlay)])].map((key) => [
1105
+ key,
1106
+ Object.hasOwn(overlay, key) ? mergeValue(inherited[key], overlay[key]) : structuredClone(inherited[key])
1107
+ ])
1108
+ );
849
1109
  }
850
- function mergeComposeEnvironment(service, overlay) {
851
- service.environment = { ...normalizeComposeEnvironment(service.environment, "service.environment"), ...overlay };
1110
+ function mergeMainOverride(inherited, overlay) {
1111
+ return mergeValue(inherited, overlay);
852
1112
  }
853
1113
 
854
1114
  // src/core/composition/composeBuildResources.ts
@@ -955,10 +1215,99 @@ function namespaceDependencyCompose(options) {
955
1215
  if (doc.secrets) doc.secrets = rewriteResourceDefinitions(doc.secrets, secretNameMap);
956
1216
  return { document: doc, serviceNameMap, volumeNameMap, networkNameMap, configNameMap, secretNameMap };
957
1217
  }
1218
+ function validateMaterializedComposeFiles(document, sourceFile, stage2, options = {}) {
1219
+ const baseDir = options.baseDir ?? path.dirname(sourceFile);
1220
+ const within = (file, configPath, required) => {
1221
+ const absolute = path.resolve(baseDir, file), relative = path.relative(baseDir, absolute);
1222
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) throw new ConfigError({ sourceFile, configPath, stage: stage2, composition: options.composition ?? "service", value: file, reason: "Materialized Compose file escapes its project" });
1223
+ let regular = false;
1224
+ try {
1225
+ const baseReal = fs.realpathSync(baseDir), fileReal = fs.realpathSync(absolute), realRelative = path.relative(baseReal, fileReal);
1226
+ if (realRelative === ".." || realRelative.startsWith(`..${path.sep}`) || path.isAbsolute(realRelative)) throw new ConfigError({ sourceFile, configPath, stage: stage2, composition: options.composition ?? "service", value: file, reason: "Materialized Compose file symlink escapes its project" });
1227
+ regular = fs.statSync(fileReal).isFile();
1228
+ } catch (error) {
1229
+ if (error instanceof ConfigError) throw error;
1230
+ }
1231
+ if (required && !regular) throw new ConfigError({ sourceFile, configPath, stage: stage2, composition: options.composition ?? "service", value: file, reason: "Materialized Compose file resource is missing or not a regular file" });
1232
+ };
1233
+ for (const [serviceName, service] of Object.entries(document.services ?? {})) {
1234
+ const entries2 = Array.isArray(service.env_file) ? service.env_file : service.env_file === void 0 ? [] : [service.env_file];
1235
+ for (const [index, entry] of entries2.entries()) {
1236
+ const file = typeof entry === "string" ? entry : entry && typeof entry === "object" ? entry.path : void 0;
1237
+ if (typeof file !== "string") continue;
1238
+ const required = typeof entry === "string" || entry.required !== false;
1239
+ within(file, `services.${serviceName}.env_file.${index}`, required);
1240
+ }
1241
+ }
1242
+ for (const kind of ["configs", "secrets"]) {
1243
+ for (const [name, raw] of Object.entries(document[kind] ?? {})) {
1244
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) continue;
1245
+ const file = raw.file;
1246
+ if (typeof file !== "string") continue;
1247
+ within(file, `${kind}.${name}.file`, true);
1248
+ }
1249
+ }
1250
+ }
1251
+ function validateMaterializedComposeBuildInputs(document, sourceFile, stage2, composition) {
1252
+ const baseDir = path.dirname(sourceFile);
1253
+ for (const [name, service] of Object.entries(document.services ?? {})) {
1254
+ const build = service.build;
1255
+ if (build === void 0) continue;
1256
+ assertNoServiceBuildContexts(service, `services.${name}`, sourceFile);
1257
+ const objectBuild = build && typeof build === "object" && !Array.isArray(build) ? build : void 0;
1258
+ const context = typeof build === "string" ? build : objectBuild?.context ?? ".";
1259
+ const configPath = `services.${name}.build`;
1260
+ const fail4 = (field, value, reason) => {
1261
+ throw new ConfigError({
1262
+ sourceFile,
1263
+ configPath: `${configPath}.${field}`,
1264
+ stage: stage2,
1265
+ composition,
1266
+ value,
1267
+ reason
1268
+ });
1269
+ };
1270
+ if (typeof context !== "string" || context.trim() === "") {
1271
+ return fail4("context", context, "Local build context must be a non-empty path");
1272
+ }
1273
+ if (isRemoteBuildContext(context)) continue;
1274
+ const absoluteContext = path.resolve(baseDir, context);
1275
+ let directory = false;
1276
+ try {
1277
+ directory = fs.statSync(absoluteContext).isDirectory();
1278
+ } catch {
1279
+ }
1280
+ if (!directory) {
1281
+ fail4(
1282
+ "context",
1283
+ context,
1284
+ "Materialized local build context is missing or not a directory"
1285
+ );
1286
+ }
1287
+ if (objectBuild?.dockerfile_inline !== void 0) continue;
1288
+ const dockerfile = objectBuild?.dockerfile ?? "Dockerfile";
1289
+ if (typeof dockerfile !== "string" || dockerfile.trim() === "") {
1290
+ return fail4("dockerfile", dockerfile, "Dockerfile path must be a non-empty string");
1291
+ }
1292
+ const absoluteDockerfile = path.resolve(absoluteContext, dockerfile);
1293
+ let regular = false;
1294
+ try {
1295
+ regular = fs.statSync(absoluteDockerfile).isFile();
1296
+ } catch {
1297
+ }
1298
+ if (!regular) {
1299
+ fail4(
1300
+ "dockerfile",
1301
+ dockerfile,
1302
+ "Materialized local Dockerfile is missing or not a regular file"
1303
+ );
1304
+ }
1305
+ }
1306
+ }
958
1307
 
959
1308
  // src/core/composition/validateComposeResourceReferences.ts
960
1309
  function validateComposeResourceReferences(document, context, onlyServices) {
961
- const fail = (configPath, kind, name) => {
1310
+ const fail4 = (configPath, kind, name) => {
962
1311
  throw new ConfigError({
963
1312
  sourceFile: context.sourceFile,
964
1313
  configPath,
@@ -972,9 +1321,9 @@ function validateComposeResourceReferences(document, context, onlyServices) {
972
1321
  const definitions = document[kind === "volume" ? "volumes" : kind === "network" ? "networks" : kind === "config" ? "configs" : "secrets"];
973
1322
  return Boolean(definitions && Object.hasOwn(definitions, name));
974
1323
  };
975
- const check = (path22, kind, name) => {
1324
+ const check = (path25, kind, name) => {
976
1325
  if (kind === "network" && name === "default") return;
977
- if (!exists(kind, name)) fail(path22, kind, name);
1326
+ if (!exists(kind, name)) fail4(path25, kind, name);
978
1327
  };
979
1328
  for (const [serviceName, service] of Object.entries(document.services ?? {})) {
980
1329
  validateServiceResources(serviceName, service, check);
@@ -1005,109 +1354,33 @@ function validateServiceResources(serviceName, service, check) {
1005
1354
  }
1006
1355
  }
1007
1356
 
1008
- // src/core/composition/assertComposeLifecycleAcyclic.ts
1009
- function assertComposeLifecycleAcyclic(services, context) {
1010
- const graph = new Map(
1011
- Object.keys(services).map((name) => [name, /* @__PURE__ */ new Set()])
1012
- );
1013
- for (const [name, service] of Object.entries(services)) {
1014
- const value = service.depends_on;
1015
- const targets = Array.isArray(value) ? value.filter((item) => typeof item === "string") : value && typeof value === "object" ? Object.keys(value) : [];
1016
- for (const target of targets) {
1017
- if (graph.has(target)) graph.get(name).add(target);
1018
- }
1019
- }
1020
- assertAcyclicGraph(graph, context);
1021
- }
1022
-
1023
- // src/core/composition/composeHealthcheck.ts
1024
- function isEnabledValidComposeHealthcheck(value) {
1025
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1026
- const health = value;
1027
- if (health.disable === true) return false;
1028
- const test = health.test;
1029
- if (typeof test === "string") return test.trim().length > 0;
1030
- if (!Array.isArray(test) || !test.every((item) => typeof item === "string")) return false;
1031
- if (test[0] !== "CMD" && test[0] !== "CMD-SHELL") return false;
1032
- return test.length >= 2 && test.slice(1).some((item) => item.trim().length > 0);
1033
- }
1034
-
1035
- // src/core/composition/validateDependencyCompose.ts
1036
- function validateDependencyCompose(dependencyKey, dependency, document, context) {
1037
- const fail = (configPath, reason, value) => {
1038
- throw new ConfigError({ sourceFile: context.composePath, configPath, stage: context.stage, composition: "service", ...value === void 0 ? {} : { value }, reason: `Dependency "${dependencyKey}": ${reason}` });
1039
- };
1040
- if (document.include !== void 0) fail("include", "Compose include is unsupported for atomic dependency implementations");
1041
- validateComposeResourceReferences(document, { sourceFile: context.composePath, stage: context.stage, composition: "service" });
1042
- const services = document.services ?? {};
1043
- for (const [name, svc] of Object.entries(services)) {
1044
- assertNoServiceBuildContexts(svc, `services.${name}`, context.composePath);
1045
- if (svc.profiles !== void 0) fail(`services.${name}.profiles`, "dependency Compose profiles are unsupported because a materialized dependency is atomic");
1046
- if (svc.extends !== void 0) fail(`services.${name}.extends`, "dependency Compose extends is unsupported until effective endpoint-owner networking and health can be validated");
1047
- if (svc.ports !== void 0) fail(`services.${name}.ports`, "raw dependency ports are forbidden");
1048
- if (svc.network_mode === "host") fail(`services.${name}.network_mode`, "host network mode is forbidden");
1049
- if (svc.privileged === true) fail(`services.${name}.privileged`, `privileged services are forbidden`);
1050
- if (svc.container_name !== void 0) fail(`services.${name}.container_name`, `fixed container_name is forbidden`);
1051
- for (const v of Array.isArray(svc.volumes) ? svc.volumes : []) {
1052
- const mount = parseVolume(v);
1053
- if (mount?.type === "bind" && mount.source && isHostFilesystemRoot(mount.source)) fail(`services.${name}.volumes`, "host root bind mounts are forbidden", v);
1054
- }
1055
- const internalRefs = [];
1056
- if (Array.isArray(svc.depends_on)) {
1057
- for (const ref of svc.depends_on) if (typeof ref === "string") internalRefs.push(["depends_on", ref]);
1058
- } else if (svc.depends_on && typeof svc.depends_on === "object") {
1059
- for (const ref of Object.keys(svc.depends_on)) internalRefs.push(["depends_on", ref]);
1060
- }
1061
- if (Array.isArray(svc.links)) {
1062
- for (const ref of svc.links) if (typeof ref === "string") internalRefs.push(["links", ref.split(":")[0]]);
1063
- }
1064
- if (typeof svc.network_mode === "string" && svc.network_mode.startsWith("service:")) internalRefs.push(["network_mode", svc.network_mode.slice(8)]);
1065
- if (Array.isArray(svc.volumes_from)) {
1066
- for (const ref of svc.volumes_from) if (typeof ref === "string") internalRefs.push(["volumes_from", ref.split(":")[0]]);
1067
- }
1068
- for (const key of ["ipc", "pid"]) if (typeof svc[key] === "string" && svc[key].startsWith("service:")) internalRefs.push([key, svc[key].slice(8)]);
1069
- 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);
1070
- }
1071
- assertComposeLifecycleAcyclic(services, {
1072
- sourceFile: context.composePath,
1073
- stage: context.stage,
1074
- composition: "service"
1075
- });
1076
- if (!Object.keys(dependency.endpoints).length) return;
1077
- if (!Object.keys(services).length) fail("services", "endpoint-bearing dependency Compose must define services");
1078
- const owners = /* @__PURE__ */ new Set();
1079
- for (const [endpoint, definition] of Object.entries(dependency.endpoints)) {
1080
- const owner = definition.service;
1081
- if (!services[owner]) fail(`endpoints.${endpoint}.service`, `declared endpoint owner "${owner}" does not exist`, owner);
1082
- owners.add(owner);
1083
- }
1084
- for (const owner of owners) {
1085
- if (services[owner].network_mode !== void 0) fail(`services.${owner}.network_mode`, `endpoint owner cannot use network_mode`);
1086
- if (!isEnabledValidComposeHealthcheck(services[owner].healthcheck)) fail(`services.${owner}.healthcheck`, "endpoint owner requires a valid enabled Compose healthcheck");
1087
- }
1088
- }
1357
+ // src/core/composition/validateOverrideCompose.ts
1089
1358
  function canonicalBuildContext(value, baseDir) {
1090
1359
  return canonicalPath(path.resolve(baseDir, value));
1091
1360
  }
1092
1361
  function isSameBuildContext(actual, expected, baseDir) {
1093
1362
  return canonicalBuildContext(actual, baseDir) === canonicalBuildContext(expected, baseDir);
1094
1363
  }
1095
- function validateAndPrepareAppOverride(document, context) {
1096
- const fail = (path22, reason, value) => {
1097
- throw new ConfigError({ sourceFile: context.file, configPath: path22, stage: context.stage, composition: "service", ...value === void 0 ? {} : { value }, reason });
1364
+ function validateAndPrepareMainOverride(document, context) {
1365
+ const fail4 = (path25, reason, value) => {
1366
+ throw new ConfigError({ sourceFile: context.file, configPath: path25, stage: context.stage, composition: "service", ...value === void 0 ? {} : { value }, reason });
1098
1367
  };
1099
1368
  const allowedRootKeys = /* @__PURE__ */ new Set(["services", "volumes", "networks", "configs", "secrets"]);
1100
- for (const key of Object.keys(document)) if (!key.startsWith("x-") && !allowedRootKeys.has(key)) fail(key, "unsupported override Compose top-level field");
1369
+ for (const key of Object.keys(document)) if (!key.startsWith("x-") && !allowedRootKeys.has(key)) fail4(key, "unsupported override Compose top-level field");
1101
1370
  const keys = Object.keys(document.services ?? {});
1102
- if (keys.length !== 1 || keys[0] !== "app") fail("services", "override must define exactly one service named app");
1371
+ if (keys.length !== 1 || keys[0] !== "main") fail4("services", "override must define exactly one service named main");
1103
1372
  validateComposeResourceReferences(document, { sourceFile: context.file, stage: context.stage, composition: "service" });
1104
- const app = structuredClone(document.services.app);
1105
- for (const k of ["ports", "depends_on", "network_mode", "container_name", "privileged", "profiles", "extends", "env_file"]) if (app[k] !== void 0) fail(`services.app.${k}`, "override cannot own endpoint or lifecycle behavior");
1106
- if (Object.hasOwn(app, "healthcheck")) {
1107
- const healthcheck = app.healthcheck;
1373
+ const main = structuredClone(document.services.main);
1374
+ for (const volume of Array.isArray(main.volumes) ? main.volumes : []) {
1375
+ const mount = parseVolume(volume);
1376
+ if (mount?.type === "bind" && mount.source && isHostFilesystemRoot(mount.source)) fail4("services.main.volumes", "host root bind mounts are forbidden");
1377
+ }
1378
+ for (const k of ["ports", "depends_on", "network_mode", "container_name", "privileged", "profiles", "extends", "env_file"]) if (main[k] !== void 0) fail4(`services.main.${k}`, "override cannot own endpoint or lifecycle behavior");
1379
+ if (Object.hasOwn(main, "healthcheck")) {
1380
+ const healthcheck = main.healthcheck;
1108
1381
  if (healthcheck === null || typeof healthcheck !== "object" || Array.isArray(healthcheck)) {
1109
- fail(
1110
- "services.app.healthcheck",
1382
+ fail4(
1383
+ "services.main.healthcheck",
1111
1384
  "override healthcheck must be a mapping of timing fields",
1112
1385
  healthcheck
1113
1386
  );
@@ -1121,40 +1394,40 @@ function validateAndPrepareAppOverride(document, context) {
1121
1394
  ]);
1122
1395
  for (const key of Object.keys(healthcheck)) {
1123
1396
  if (!allowedTiming.has(key)) {
1124
- fail(
1125
- `services.app.healthcheck.${key}`,
1397
+ fail4(
1398
+ `services.main.healthcheck.${key}`,
1126
1399
  "override may set only healthcheck timing fields"
1127
1400
  );
1128
1401
  }
1129
1402
  }
1130
1403
  }
1131
- if (typeof app.build === "string") {
1132
- fail("services.app.build", "override cannot replace Builder-owned app build context; use object-form build.args for build arguments", app.build);
1404
+ if (typeof main.build === "string") {
1405
+ fail4("services.main.build", "override cannot replace Builder-owned main build context; use object-form build.args for build arguments", main.build);
1133
1406
  }
1134
- if (app.build && typeof app.build === "object") {
1135
- const build = app.build;
1407
+ if (main.build && typeof main.build === "object") {
1408
+ const build = main.build;
1136
1409
  for (const key of Object.keys(build)) {
1137
1410
  if (!["args", "context"].includes(key)) {
1138
- fail(`services.app.build.${key}`, "override cannot change Builder-owned build configuration");
1411
+ fail4(`services.main.build.${key}`, "override cannot change Builder-owned build configuration");
1139
1412
  }
1140
1413
  }
1141
1414
  if (build.context !== void 0) {
1142
1415
  if (typeof build.context !== "string") {
1143
- fail("services.app.build.context", "override app build context must be a string", build.context);
1416
+ fail4("services.main.build.context", "override main build context must be a string", build.context);
1144
1417
  }
1145
1418
  if (!isSameBuildContext(build.context, context.expectedBuildContext, context.buildContextBaseDir)) {
1146
- fail("services.app.build.context", "override cannot change app build context", build.context);
1419
+ fail4("services.main.build.context", "override cannot change main build context", build.context);
1147
1420
  }
1148
1421
  }
1149
1422
  }
1150
- const env = normalizeComposeEnvironment(app.environment, "services.app.environment");
1151
- for (const k of ["EXEC_MODE", "INFRA_MODE"]) if (k in env) fail(`services.app.environment.${k}`, "override cannot set Builder-owned environment");
1152
- app.environment = env;
1423
+ const env2 = normalizeComposeEnvironment(main.environment, "services.main.environment");
1424
+ for (const k of ["EXEC_MODE", "INFRA_MODE"]) if (k in env2) fail4(`services.main.environment.${k}`, "override cannot set Builder-owned environment");
1425
+ main.environment = env2;
1153
1426
  const allocator = context.allocator ?? new GeneratedComposeNameAllocator();
1154
1427
  const resourceKeys = ["volumes", "networks", "configs", "secrets"];
1155
1428
  const resources = {};
1156
1429
  for (const kind of resourceKeys) {
1157
- const defs = document[kind] ?? {}, refs = /* @__PURE__ */ new Set(), value = app[kind];
1430
+ const defs = document[kind] ?? {}, refs = /* @__PURE__ */ new Set(), value = main[kind];
1158
1431
  if (Array.isArray(value)) for (const ref of value) {
1159
1432
  if (kind === "volumes") {
1160
1433
  const volume = parseVolume(ref);
@@ -1165,345 +1438,434 @@ function validateAndPrepareAppOverride(document, context) {
1165
1438
  else if (value && typeof value === "object") for (const name of Object.keys(value)) refs.add(name);
1166
1439
  const names = /* @__PURE__ */ new Map(), mapped = {};
1167
1440
  for (const [name, definition] of Object.entries(defs)) {
1168
- if (!refs.has(name)) fail(`${kind}.${name}`, "override resource must be consumed by app");
1169
- const prefix = context.resourceNamespace && context.resourceNamespace !== "app" ? `svc--${context.resourceNamespace}--app-override` : "app-override";
1170
- const target = allocator.allocate(JSON.stringify(["service", context.resourceNamespace ?? "app", "override", context.stage, kind, name]), `${prefix}--${context.stage}--${kind.slice(0, -1)}--${name}`);
1441
+ if (!refs.has(name)) fail4(`${kind}.${name}`, "override resource must be consumed by main");
1442
+ const prefix = context.resourceNamespace && context.resourceNamespace !== "main" ? `svc--${context.resourceNamespace}--main-override` : "main-override";
1443
+ const target = allocator.allocate(JSON.stringify(["service", context.resourceNamespace ?? "main", "override", context.stage, kind, name]), `${prefix}--${context.stage}--${kind.slice(0, -1)}--${name}`);
1171
1444
  names.set(name, target);
1172
1445
  mapped[target] = namespaceResourceDefinition(name, definition);
1173
1446
  }
1174
1447
  if (names.size) resources[kind] = mapped;
1175
- if (Array.isArray(value)) app[kind] = value.map((ref) => kind === "volumes" ? namespaceVolume(ref, names) : typeof ref === "string" ? names.get(ref) ?? ref : ref && typeof ref === "object" && typeof ref.source === "string" ? { ...ref, source: names.get(ref.source) ?? ref.source } : ref);
1176
- else if (value && typeof value === "object") app[kind] = Object.fromEntries(Object.entries(value).map(([name, definition]) => [names.get(name) ?? name, definition]));
1448
+ if (Array.isArray(value)) main[kind] = value.map((ref) => kind === "volumes" ? namespaceVolume(ref, names) : typeof ref === "string" ? names.get(ref) ?? ref : ref && typeof ref === "object" && typeof ref.source === "string" ? { ...ref, source: names.get(ref.source) ?? ref.source } : ref);
1449
+ else if (value && typeof value === "object") main[kind] = Object.fromEntries(Object.entries(value).map(([name, definition]) => [names.get(name) ?? name, definition]));
1177
1450
  }
1178
- return { app, resources };
1451
+ return { main, resources };
1179
1452
  }
1180
1453
 
1181
- // src/core/composition/mergeAppOverride.ts
1182
- function isMap(value) {
1183
- if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
1184
- const prototype = Object.getPrototypeOf(value);
1185
- return prototype === Object.prototype || prototype === null;
1186
- }
1187
- function mergeValue(inherited, overlay) {
1188
- if (overlay === void 0) return structuredClone(inherited);
1189
- if (!isMap(inherited) || !isMap(overlay)) return structuredClone(overlay);
1190
- return Object.fromEntries(
1191
- [.../* @__PURE__ */ new Set([...Object.keys(inherited), ...Object.keys(overlay)])].map((key) => [
1192
- key,
1193
- Object.hasOwn(overlay, key) ? mergeValue(inherited[key], overlay[key]) : structuredClone(inherited[key])
1194
- ])
1195
- );
1196
- }
1197
- function mergeAppOverride(inherited, overlay) {
1198
- return mergeValue(inherited, overlay);
1454
+ // src/core/composition/composeHealthcheck.ts
1455
+ function isEnabledValidComposeHealthcheck(value) {
1456
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1457
+ const health = value;
1458
+ if (health.disable === true) return false;
1459
+ const test = health.test;
1460
+ if (typeof test === "string") return test.trim().length > 0 && !/^NONE$/i.test(test.trim());
1461
+ if (!Array.isArray(test) || !test.every((item) => typeof item === "string")) return false;
1462
+ const type = test[0]?.toUpperCase();
1463
+ if (type !== "CMD" && type !== "CMD-SHELL") return false;
1464
+ return test.length >= 2 && test.slice(1).some((item) => item.trim().length > 0);
1199
1465
  }
1200
1466
 
1201
- // src/core/composition/dependencyLifecycle.ts
1202
- function asMap(value) {
1203
- if (Array.isArray(value)) return Object.fromEntries(value.filter((v) => typeof v === "string").map((v) => [v, {}]));
1204
- if (value && typeof value === "object") return value;
1205
- return {};
1206
- }
1207
- function healthyMerge(target, owners) {
1208
- const current = asMap(target.depends_on);
1209
- for (const owner of owners) {
1210
- const old = current[owner];
1211
- const cond = old && typeof old === "object" ? old.condition : void 0;
1212
- current[owner] = { ...old && typeof old === "object" ? old : {}, condition: cond === "service_healthy" ? cond : "service_healthy" };
1213
- }
1214
- target.depends_on = current;
1215
- }
1216
- function applyDependencyLifecycle(app, materialized, effectiveBuild) {
1217
- const appOwners = /* @__PURE__ */ new Set();
1218
- for (const dep of Object.values(materialized)) for (const owner of dep.endpointOwners) appOwners.add(owner);
1219
- healthyMerge(app, appOwners);
1220
- for (const [key, dep] of Object.entries(materialized)) {
1221
- const config = effectiveBuild.dependencies[key];
1222
- if (!config) continue;
1223
- for (const raw of config.dependsOn) {
1224
- const match = DEPENDENCY_REFERENCE_PATTERN.exec(raw);
1225
- if (!match) continue;
1226
- const target = materialized[match[1]];
1227
- if (!target) continue;
1228
- for (const sourceOwner of dep.endpointOwners) {
1229
- const source = dep.compose.services[sourceOwner];
1230
- if (source) healthyMerge(source, target.endpointOwners);
1467
+ // src/core/composition/validateServiceCompose.ts
1468
+ function validateServiceCompose(name, declaration, document, context) {
1469
+ const fail4 = (configPath, reason, value) => {
1470
+ throw new ConfigError({ sourceFile: context.composePath, configPath, stage: context.stage, composition: context.composition, referencedObject: name, reason, value });
1471
+ };
1472
+ if (document.include !== void 0) fail4("include", "Compose include is unsupported for atomic service implementations");
1473
+ validateComposeResourceReferences(document, { sourceFile: context.composePath, stage: context.stage, composition: context.composition });
1474
+ const services2 = document.services ?? {};
1475
+ if (!Object.keys(services2).length) fail4("services", "Ordinary service Compose must define services");
1476
+ for (const [key, svc] of Object.entries(services2)) {
1477
+ if (svc.profiles !== void 0 || svc.extends !== void 0) fail4(`services.${key}`, "Compose profiles and extends are unsupported for atomic service implementations");
1478
+ if (svc.ports !== void 0 || svc.network_mode === "host" || svc.container_name !== void 0 || svc.privileged === true) fail4(`services.${key}`, "Service cannot own host ports, host networking, container_name or privileged mode");
1479
+ for (const volume of Array.isArray(svc.volumes) ? svc.volumes : []) {
1480
+ const mount = parseVolume(volume);
1481
+ if (mount?.type === "bind" && mount.source && isHostFilesystemRoot(mount.source)) fail4(`services.${key}.volumes`, "host root bind mounts are forbidden");
1482
+ }
1483
+ const references = [];
1484
+ if (Array.isArray(svc.depends_on)) references.push(...svc.depends_on.filter((value) => typeof value === "string"));
1485
+ else if (svc.depends_on && typeof svc.depends_on === "object") references.push(...Object.keys(svc.depends_on));
1486
+ if (Array.isArray(svc.links)) references.push(...svc.links.filter((value) => typeof value === "string").map((value) => value.split(":")[0]));
1487
+ if (Array.isArray(svc.volumes_from)) references.push(...svc.volumes_from.filter((value) => typeof value === "string").map((value) => value.split(":")[0]));
1488
+ for (const prop of ["network_mode", "ipc", "pid"]) {
1489
+ const raw = svc[prop];
1490
+ if (typeof raw === "string" && raw.startsWith("service:")) references.push(raw.slice(8));
1491
+ }
1492
+ for (const target of references) if (!services2[target]) fail4(`services.${key}`, `internal service reference ${target} does not exist`);
1493
+ }
1494
+ const endpoints = declaration.endpoints;
1495
+ const declarationOrigin = declaration.origin ?? context.declarationOrigin;
1496
+ const failDeclaration = (configPath, reason, value) => {
1497
+ if (declarationOrigin) throw new ConfigError({ sourceFile: declarationOrigin.sourceFile, configPath: `${declarationOrigin.configPath}.${configPath}`, stage: context.stage, composition: context.composition, referencedObject: name, reason, value });
1498
+ return fail4(configPath, reason, value);
1499
+ };
1500
+ let representative;
1501
+ if (Object.keys(endpoints).length) {
1502
+ const primary = Object.values(endpoints).find((endpoint) => endpoint.primary);
1503
+ representative = primary.service;
1504
+ if (declaration.service && declaration.service !== representative) failDeclaration("service", "top-level service must equal primary endpoint owner", declaration.service);
1505
+ } else {
1506
+ if (!declaration.service) failDeclaration("service", "endpoint-less service requires service");
1507
+ representative = declaration.service;
1508
+ }
1509
+ if (!services2[representative]) failDeclaration("service", "lifecycle representative does not exist", representative);
1510
+ for (const [endpoint, definition] of Object.entries(endpoints)) {
1511
+ if (!services2[definition.service]) failDeclaration(`endpoints.${endpoint}.service`, "endpoint owner does not exist", definition.service);
1512
+ if (services2[definition.service].network_mode !== void 0) fail4(`services.${definition.service}.network_mode`, "endpoint owner cannot use network_mode");
1513
+ }
1514
+ if (context.healthRequired) {
1515
+ const health = services2[representative].healthcheck;
1516
+ if (health === void 0 || health && typeof health === "object" && !Array.isArray(health) && health.test === void 0 && health.disable !== true) context.deferHealth?.(representative);
1517
+ else if (!isEnabledValidComposeHealthcheck(health)) fail4(`services.${representative}.healthcheck`, "requires a valid healthcheck");
1518
+ }
1519
+ if (context.prerequisite && services2[representative].restart !== void 0 && services2[representative].restart !== "no") fail4(`services.${representative}.restart`, "prerequisite cannot have a restart policy");
1520
+ assertComposeLifecycleAcyclic(services2, { sourceFile: context.composePath, stage: context.stage, composition: context.composition });
1521
+ return representative;
1522
+ }
1523
+ function readDotenvValues(file) {
1524
+ if (!fs.existsSync(file)) return {};
1525
+ const source = fs.readFileSync(file, "utf8"), result = {};
1526
+ let offset = 0;
1527
+ while (offset < source.length) {
1528
+ const start = offset;
1529
+ while (offset < source.length && source[offset] !== "\n") offset++;
1530
+ let line = source.slice(start, offset).replace(/\r$/, "");
1531
+ offset++;
1532
+ const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*[:=]\s*(.*)$/.exec(line);
1533
+ if (!match) continue;
1534
+ const key = match[1];
1535
+ let value = match[2];
1536
+ if (value.startsWith("'") || value.startsWith('"')) {
1537
+ const quote = value[0];
1538
+ value = value.slice(1);
1539
+ const closingQuote = () => {
1540
+ for (let index = 0; index < value.length; index++) {
1541
+ if (value[index] !== quote) continue;
1542
+ if (quote === "'") return index;
1543
+ let backslashes = 0;
1544
+ for (let cursor = index - 1; cursor >= 0 && value[cursor] === "\\"; cursor--) backslashes++;
1545
+ if (backslashes % 2 === 0) return index;
1546
+ }
1547
+ return -1;
1548
+ };
1549
+ let end = closingQuote();
1550
+ while (end < 0 && offset < source.length) {
1551
+ const nextStart = offset;
1552
+ while (offset < source.length && source[offset] !== "\n") offset++;
1553
+ value += "\n" + source.slice(nextStart, offset).replace(/\r$/, "");
1554
+ offset++;
1555
+ end = closingQuote();
1231
1556
  }
1232
- }
1233
- }
1234
- }
1235
-
1236
- // src/core/composition/serviceEndpoints.ts
1237
- function buildStandaloneAppEndpoints(build, stage, host = "app") {
1238
- const out = {};
1239
- 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 };
1240
- return out;
1241
- }
1242
- function buildStandaloneDependencyEndpoints(key, build, serviceNames, materialized) {
1243
- const out = {};
1244
- for (const [name, e] of Object.entries(build.dependencies[key]?.endpoints ?? {})) {
1245
- const host = serviceNames.get(e.service) ?? e.service;
1246
- 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 };
1557
+ if (end >= 0) value = value.slice(0, end);
1558
+ if (quote === '"') value = value.replace(/\\([nrt"\\])/g, (_all, char) => char === "n" ? "\n" : char === "r" ? "\r" : char === "t" ? " " : char);
1559
+ } else value = value.replace(/\s+#.*$/, "").trim();
1560
+ result[key] = value;
1247
1561
  }
1248
- return out;
1562
+ return result;
1249
1563
  }
1250
1564
 
1251
- // src/core/composition/compileServiceComposition.ts
1252
- function getExecutionProfile(stage, full) {
1253
- switch (stage) {
1254
- case "dev":
1255
- return { configStage: "dev", envStage: "dev", appTarget: "dev", execMode: "dev", infraMode: full ? "integrated" : "isolated", attachTester: false };
1256
- case "prod":
1257
- return { configStage: "prod", envStage: "prod", appTarget: "prod", execMode: "prod", infraMode: "integrated", attachTester: false };
1258
- case "test":
1259
- return { configStage: "test", envStage: "test", appTarget: "test", execMode: "test", infraMode: "isolated", attachTester: false };
1260
- case "e2e":
1261
- return { configStage: "e2e", envStage: "e2e", appTarget: "prod", execMode: "prod", infraMode: "integrated", attachTester: true, testerTarget: "test-e2e" };
1565
+ // src/core/composition/compileTester.ts
1566
+ function compileTester(input) {
1567
+ const { tester, origin, stage: stage2, composition } = input;
1568
+ const file = resolveInsideProject(origin.projectDir, tester.compose, { sourceFile: origin.sourceFile, configPath: `${origin.configPath}.compose`, stage: stage2 });
1569
+ const raw = loadComposeDocument(file, { sourceFile: origin.sourceFile, configPath: `${origin.configPath}.compose`, stage: stage2, composition });
1570
+ if (!raw.services?.[tester.service]) throw new ConfigError({ sourceFile: input.serviceOrigin?.sourceFile ?? origin.sourceFile, configPath: input.serviceOrigin?.configPath ?? `${origin.configPath}.service`, stage: stage2, composition, referencedObject: tester.service, reason: "Selected tester service does not exist" });
1571
+ if (raw.include !== void 0) throw new ConfigError({ sourceFile: file, configPath: "include", stage: stage2, composition, reason: "Tester Compose include is unsupported" });
1572
+ validateComposeResourceReferences(raw, { sourceFile: file, stage: stage2, composition });
1573
+ assertComposeLifecycleAcyclic(raw.services, { sourceFile: file, stage: stage2, composition });
1574
+ for (const [name, service] of Object.entries(raw.services)) {
1575
+ if (service.ports !== void 0 || service.container_name !== void 0 || service.privileged === true) throw new ConfigError({ sourceFile: file, configPath: `services.${name}`, stage: stage2, composition, reason: "Tester Compose cannot own ports, fixed container names or privileged mode" });
1576
+ for (const volume of Array.isArray(service.volumes) ? service.volumes : []) {
1577
+ const mount = parseVolume(volume);
1578
+ if (mount?.type === "bind" && mount.source && isHostFilesystemRoot(mount.source)) throw new ConfigError({ sourceFile: file, configPath: `services.${name}.volumes`, stage: stage2, composition, reason: "host root bind mounts are forbidden" });
1579
+ }
1580
+ assertNoBuilderOwnedEnvKeys(normalizeComposeEnvironment(service.environment, `services.${name}.environment`), ["EXEC_MODE", "INFRA_MODE"], { sourceFile: file, configPath: `services.${name}.environment`, stage: stage2, composition });
1581
+ const files = Array.isArray(service.env_file) ? service.env_file : service.env_file ? [service.env_file] : [];
1582
+ for (const item of files) {
1583
+ const candidate = typeof item === "string" ? item : item && typeof item === "object" ? item.path : void 0;
1584
+ if (typeof candidate === "string") assertDotenvDoesNotDefineKeys(path.resolve(path.dirname(file), candidate), ["EXEC_MODE", "INFRA_MODE"], { configPath: `services.${name}.env_file`, stage: stage2, composition });
1585
+ }
1586
+ }
1587
+ validateMaterializedComposeFiles(raw, file, stage2, { composition });
1588
+ validateMaterializedComposeBuildInputs(raw, file, stage2, composition);
1589
+ for (const [key, value] of Object.entries(tester.env ?? {})) {
1590
+ const leaf = input.envOrigins?.get(key) ?? { ...origin, configPath: `${origin.configPath}.env.${key}` };
1591
+ assertNoBuilderOwnedEnvKeys({ [key]: value }, ["EXEC_MODE", "INFRA_MODE"], { sourceFile: leaf.sourceFile, configPath: leaf.configPath.slice(0, leaf.configPath.lastIndexOf(".")), stage: stage2, composition });
1592
+ }
1593
+ const dotenv = path.join(origin.projectDir, ".env.e2e-tester");
1594
+ assertDotenvDoesNotDefineKeys(dotenv, ["EXEC_MODE", "INFRA_MODE"], { configPath: ".env.e2e-tester", stage: stage2, composition });
1595
+ const rebased = rebaseComposePaths(raw, file, input.projectDir);
1596
+ const named = namespaceDependencyCompose({ dependencyKey: "tester", namespacePrefix: "tester", document: rebased, allocator: input.allocator, identityPrefix: JSON.stringify([composition, "tester"]) });
1597
+ const runner = named.serviceNameMap.get(tester.service), selected = named.document.services[runner];
1598
+ for (const [name, service] of Object.entries(named.document.services)) {
1599
+ if (name === runner) continue;
1600
+ if (service.network_mode === void 0) service.networks = { ...normalizeNetworks(service.networks), builder: null };
1601
+ }
1602
+ if (raw.services[tester.service].network_mode === void 0 && raw.services[tester.service].networks === void 0) {
1603
+ selected.network_mode = "host";
1604
+ delete selected.networks;
1605
+ } else if (selected.network_mode === void 0) selected.networks = { ...normalizeNetworks(selected.networks), builder: null };
1606
+ const defaults = normalizeComposeEnvironment(selected.environment, `services.${tester.service}.environment`);
1607
+ const resolved = {};
1608
+ for (const [key, value] of Object.entries(tester.env ?? {})) {
1609
+ const leaf = input.envOrigins?.get(key) ?? { ...origin, configPath: `${origin.configPath}.env.${key}` };
1610
+ resolved[key] = interpolateBuilderReferences(value, { graph: input.graph, endpoints: input.endpoints, origin: leaf, stage: stage2, composition }).replace(/\$/g, "$$$$");
1611
+ }
1612
+ selected.env_file = [...Array.isArray(selected.env_file) ? selected.env_file : selected.env_file ? [selected.env_file] : [], { path: path.relative(input.projectDir, dotenv).replace(/\\/g, "/"), required: false }];
1613
+ const testerDotenv = Object.fromEntries(Object.entries(readDotenvValues(dotenv)).map(([key, value]) => [key, value.replace(/\$/g, "$$$$")]));
1614
+ selected.environment = { ...defaults, ...testerDotenv, ...resolved };
1615
+ return { document: named.document, runner, serviceNames: Object.keys(named.document.services) };
1616
+ }
1617
+
1618
+ // src/core/composition/compileGraphComposition.ts
1619
+ var BUILDER_OWNER_LABEL = "dev.solidstack.builder.owned";
1620
+ var unique = (array) => [...new Set(array)];
1621
+ var copyOrigin = (origin, root) => root ? { ...origin, meshRoot: root } : origin;
1622
+ function makeGraph(input) {
1623
+ const nodes = /* @__PURE__ */ new Map();
1624
+ const roots = [];
1625
+ for (const [rootKey, build] of input.instances) {
1626
+ const root = rootKey || void 0;
1627
+ roots.push(nodeId(root, "main"));
1628
+ for (const [name, declaration] of Object.entries(build.services)) {
1629
+ if (name === "tester") continue;
1630
+ const id = nodeId(root, name), origin = copyOrigin(build.origins.get(name), root);
1631
+ nodes.set(id, { id, kind: name === "main" ? "main" : "ordinary", projectDir: build.projectDir, sourceService: name, ...root ? { meshRoot: root } : {}, declaration, envLayers: [], origin, envOrigins: new Map([...build.envOrigins.get(name) ?? []].map(([key, value]) => [key, copyOrigin(value, root)])), requisiteOrigins: new Map([...build.requisiteOrigins.get(name) ?? []].map(([key, value]) => [key, copyOrigin(value, root)])) });
1632
+ }
1633
+ }
1634
+ input.mesh?.tester ?? input.instances.get("")?.services.tester;
1635
+ input.mesh ? { sourceFile: input.mesh.sourceFile, projectDir: input.projectDir} : { sourceFile: input.instances.get("").sourceFile, projectDir: input.projectDir};
1636
+ const declared = buildDeclaredGraph({ nodes, roots, stage: input.stage, composition: input.composition });
1637
+ return selectReachableGraph(declared, { infraMode: executionProfile(input.stage, input.composition, input.full).infraMode, stage: input.stage });
1638
+ }
1639
+ function mergeDocument(target, fragment, origin, stage2) {
1640
+ for (const section of ["services", "volumes", "networks", "configs", "secrets"]) {
1641
+ const values = fragment[section];
1642
+ if (!values) continue;
1643
+ const output = target[section] ??= {};
1644
+ for (const [key, value] of Object.entries(values)) {
1645
+ if (key in output) throw new ConfigError({ sourceFile: origin.sourceFile, configPath: `${origin.configPath}.${section}.${key}`, stage: stage2, composition: origin.scope === "mesh" ? "mesh" : "service", reason: "Generated Compose identity collision" });
1646
+ output[key] = value;
1647
+ }
1262
1648
  }
1263
1649
  }
1264
- function mergeDocument(target, source, context) {
1265
- for (const section of ["services", "volumes", "networks", "configs", "secrets"]) {
1266
- const src = source[section];
1267
- if (!src) continue;
1268
- const dst = target[section] ??= {};
1269
- for (const [key, value] of Object.entries(src)) {
1270
- if (key in dst) throw new ConfigError({ ...context, configPath: `${context.configPath}.${section}.${key}`, value: key, reason: "Internal Compose namespace collision" });
1271
- dst[key] = value;
1650
+ function withBuilderNetwork(service) {
1651
+ if (service.network_mode !== void 0) return;
1652
+ service.networks = { ...normalizeNetworks(service.networks), builder: null };
1653
+ }
1654
+ function markOwned(value) {
1655
+ const current = value.labels;
1656
+ const labels = Array.isArray(current) ? Object.fromEntries(current.filter((item) => typeof item === "string").map((item) => {
1657
+ const index = item.indexOf("=");
1658
+ return index < 0 ? [item, ""] : [item.slice(0, index), item.slice(index + 1)];
1659
+ })) : current && typeof current === "object" ? { ...current } : {};
1660
+ labels[BUILDER_OWNER_LABEL] = "true";
1661
+ value.labels = labels;
1662
+ }
1663
+ function selectedOverride(build, name) {
1664
+ let result;
1665
+ for (const layer of build.layers) {
1666
+ const patch = layer.services[name];
1667
+ const value = patch?.["override-compose"];
1668
+ if (typeof value === "string") {
1669
+ const base = layer.origin.configPath.endsWith(`.${name}`) ? layer.origin.configPath : `${layer.origin.configPath}.${name}`;
1670
+ result = { path: value, origin: { ...layer.origin, configPath: `${base}.override-compose` } };
1272
1671
  }
1273
1672
  }
1673
+ return result;
1274
1674
  }
1275
- function getTemplateSeed(stage, meshMode) {
1675
+ function mainSeed(stage2) {
1276
1676
  const base = parse(fs.readFileSync(getDockerComposeTemplate("docker-compose.base.yml"), "utf8"));
1277
- const stageName = stage === "e2e" ? "e2e" : stage;
1278
- const overlay = parse(fs.readFileSync(getDockerComposeTemplate(`docker-compose.${stageName}.yml`), "utf8"));
1279
- const merged = { ...base, services: { ...base.services ?? {} } };
1280
- for (const [name, svc] of Object.entries(overlay.services ?? {})) merged.services[name] = { ...merged.services[name] ?? {}, ...svc, build: { ...merged.services[name]?.build ?? {}, ...svc.build ?? {} } };
1281
- if (meshMode) delete merged.services.tester;
1282
- return merged;
1283
- }
1284
- function resolveEnv(input, registry, baseContext) {
1285
- const out = {};
1286
- for (const [key, value] of Object.entries(input)) {
1287
- if (value === null) {
1288
- out[key] = null;
1289
- continue;
1290
- }
1291
- const context = { ...baseContext, configPath: `${baseContext.configPath}.${key}` };
1292
- out[key] = interpolateBuilderReferences(value, "build", registry, context).replace(/\$/g, "$$$$");
1293
- }
1294
- return out;
1295
- }
1296
- function addPorts(service, endpointPairs, sourceFile, stage) {
1297
- for (const [ep, hostPort] of endpointPairs) {
1298
- const ports = Array.isArray(service.ports) ? service.ports : [];
1299
- if (ports.some((p) => p && typeof p === "object" && p.published === hostPort)) throw new ConfigError({ sourceFile, configPath: ep.logicalPath, stage, composition: "service", referencedObject: ep.logicalPath, value: hostPort, reason: "Duplicate host port publication" });
1300
- ports.push({ target: ep.networkPort, published: hostPort, host_ip: PUBLIC_HOST, protocol: "tcp" });
1301
- service.ports = ports;
1302
- }
1303
- }
1304
- function compileServiceComposition(stage, projectDir, options = {}) {
1305
- const root = resolveProjectDir(projectDir), buildPath = path.join(root, "build.json"), raw = getBuildJson(root), effective = resolveBuildStage(raw, stage, buildPath), profile = getExecutionProfile(stage, Boolean(options.full));
1306
- resolveApplicationDockerfile(root, raw.dockerfile ?? "Dockerfile", stage);
1307
- const seed = getTemplateSeed(stage, Boolean(options.meshMode));
1308
- const rawName = options.projectNameOverride ?? raw.name ?? path.basename(root);
1309
- const projectName = deriveProjectName(rawName, stage);
1310
- const nameAllocator = options.nameAllocator ?? new GeneratedComposeNameAllocator(["app", "tester", "default", options.appServiceName ?? "app"]);
1311
- const namespaced = {};
1312
- for (const [key, dep] of Object.entries(effective.dependencies).sort(([a], [b]) => a.localeCompare(b))) {
1313
- const sourcePath = resolveInsideProject(root, dep.compose, { sourceFile: buildPath, configPath: `dependencies.${key}.compose`, stage });
1314
- const document = rebaseComposePaths(loadComposeDocument(sourcePath, { sourceFile: buildPath, configPath: `dependencies.${key}.compose`, stage, composition: "service" }), sourcePath, options.composeOutputDir ?? root);
1315
- validateDependencyCompose(key, dep, document, { composePath: sourcePath, stage });
1316
- if (Object.keys(dep.endpoints).length) {
1317
- const ns = namespaceDependencyCompose({ dependencyKey: key, namespacePrefix: options.namespacePrefix ? `${options.namespacePrefix}${key}` : `dep--${key}`, document, allocator: nameAllocator, identityPrefix: JSON.stringify(["service", options.appServiceName ?? "app", "dependency", key]) });
1318
- namespaced[key] = { doc: ns.document, map: ns.serviceNameMap, source: sourcePath };
1319
- }
1320
- }
1321
- const materialized = {};
1322
- const compose = { ...seed, ...options.meshMode ? {} : { name: projectName }, services: { ...seed.services } };
1323
- let app = compose.services.app ?? (compose.services.app = { build: { context: "." } });
1324
- if (profile.infraMode === "integrated") for (const [key, entry] of Object.entries(namespaced)) {
1325
- if (options.suppressDependencies?.has(key)) continue;
1326
- const dep = effective.dependencies[key];
1327
- const item = structuredClone(entry.doc);
1328
- mergeDocument(compose, item, { sourceFile: entry.source, configPath: `dependencies.${key}.compose`, stage, composition: "service" });
1329
- const endpointOwnerMap = /* @__PURE__ */ new Map();
1330
- for (const [epName, ep] of Object.entries(dep.endpoints)) endpointOwnerMap.set(epName, entry.map.get(ep.service));
1331
- const endpointOwners = new Set(endpointOwnerMap.values());
1332
- materialized[key] = { key, composePath: entry.source, compose: item, serviceNameMap: entry.map, endpointOwnerMap, endpoints: {}, endpointOwners, serviceNames: new Set(Object.keys(item.services)) };
1333
- }
1334
- const appEndpoints = buildStandaloneAppEndpoints(effective, stage, options.appServiceName ?? "app");
1335
- const depEndpoints = {};
1336
- for (const [key, dep] of Object.entries(effective.dependencies)) {
1337
- depEndpoints[key] = buildStandaloneDependencyEndpoints(key, effective, namespaced[key]?.map ?? /* @__PURE__ */ new Map(), Boolean(materialized[key]));
1338
- if (options.meshMode) for (const ep of Object.values(depEndpoints[key])) {
1339
- ep.effectivelyPublished = false;
1340
- delete ep.publicHost;
1341
- delete ep.publicPort;
1342
- }
1343
- }
1344
- if (options.meshMode) for (const ep of Object.values(appEndpoints)) {
1345
- ep.effectivelyPublished = false;
1346
- delete ep.publicHost;
1347
- delete ep.publicPort;
1348
- }
1349
- const intents = [];
1350
- if (!options.meshMode) {
1351
- 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 });
1352
- for (const [key, dep] of Object.entries(effective.dependencies).sort(([a], [b]) => a.localeCompare(b))) if (materialized[key]) {
1353
- 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 });
1354
- }
1355
- }
1356
- const allocation = allocateHostPorts(root, stage, intents, Boolean(options.validationMode), { sourceFile: buildPath, composition: "service" });
1357
- for (const [name, ep] of Object.entries(appEndpoints)) if (allocation.has(ep.logicalPath)) {
1358
- ep.publicHost = PUBLIC_HOST;
1359
- ep.publicPort = allocation.get(ep.logicalPath);
1360
- ep.effectivelyPublished = true;
1361
- }
1362
- for (const [key, eps] of Object.entries(depEndpoints)) for (const [name, ep] of Object.entries(eps)) if (allocation.has(ep.logicalPath)) {
1363
- ep.publicHost = PUBLIC_HOST;
1364
- ep.publicPort = allocation.get(ep.logicalPath);
1365
- ep.effectivelyPublished = true;
1366
- }
1367
- const registry = (ref, context) => {
1368
- if (ref.target === "app") {
1369
- const ep2 = appEndpoints[ref.endpoint];
1370
- if (!ep2) throw new ConfigError({ ...context, referencedObject: ref.raw, reason: "Unknown app endpoint reference" });
1371
- return resolveEndpointProperty(ep2, ref.property, { ...context, referencedObject: ref.raw });
1372
- }
1373
- const ep = depEndpoints[ref.dependency]?.[ref.endpoint];
1374
- if (!ep) throw new ConfigError({ ...context, referencedObject: ref.raw, reason: "Unknown dependency endpoint reference" });
1375
- return resolveEndpointProperty(ep, ref.property, { ...context, referencedObject: ref.raw });
1376
- };
1377
- for (const [key, dep] of Object.entries(effective.dependencies)) {
1378
- const depEnv = options.deferReferenceResolution ? dep.env : resolveEnv(dep.env, registry, { sourceFile: buildPath, configPath: `dependencies.${key}.env`, stage, composition: "service" });
1379
- for (const svc of Object.values(materialized[key]?.compose.services ?? {})) mergeComposeEnvironment(svc, depEnv);
1380
- }
1381
- const appEnvironmentLayers = [];
1382
- for (const layer of effective.layers) {
1383
- if (Object.keys(layer.appEnv).length) {
1384
- const configPath = layer.stage === "base" ? "app.env" : `${layer.stage}.app.env`;
1385
- assertNoBuilderOwnedEnvKeys(layer.appEnv, [EXEC_MODE_KEY, INFRA_MODE_KEY, ...getPrimaryEndpoint(effective.app.endpoints) ? [PORT_KEY] : []], { sourceFile: buildPath, configPath, stage, composition: "service" });
1386
- appEnvironmentLayers.push({ kind: "build-json", stage: layer.stage, configPath, values: { ...layer.appEnv } });
1387
- }
1388
- }
1389
- const resolveAppLayers = () => {
1390
- const result = {};
1391
- const laterKeys = new Set(Object.keys(options.externalAppEnv ?? {}));
1392
- for (const [key, layer] of selectAppEnvironmentEntries(appEnvironmentLayers, laterKeys)) {
1393
- if (layer.kind === "build-json") {
1394
- const context = {
1395
- sourceFile: buildPath,
1396
- configPath: layer.configPath,
1397
- stage,
1398
- composition: "service"
1399
- };
1400
- result[key] = resolveEnv({ [key]: layer.values[key] }, registry, context)[key];
1401
- } else {
1402
- result[key] = layer.values[key];
1677
+ const overlay = parse(fs.readFileSync(getDockerComposeTemplate(`docker-compose.${stage2}.yml`), "utf8"));
1678
+ return { ...base.services.main, ...overlay.services.main, build: { ...base.services.main?.build, ...overlay.services.main?.build } };
1679
+ }
1680
+ function portKey(id, endpoint) {
1681
+ return `${displayNode(id)}.endpoints.${endpoint}`;
1682
+ }
1683
+ function addPort(service, endpoint) {
1684
+ service.ports = [...service.ports ?? [], { target: endpoint.networkPort, published: endpoint.publicPort, host_ip: "127.0.0.1", protocol: "tcp" }];
1685
+ }
1686
+ function resolveJsonEnv(node, graph, endpoints, stage2, composition, shadowed) {
1687
+ const output = {};
1688
+ for (const [key, value] of Object.entries(node.declaration.env)) {
1689
+ if (shadowed.has(key)) continue;
1690
+ const origin = node.envOrigins.get(key) ?? node.origin;
1691
+ output[key] = interpolateBuilderReferences(value, { graph, endpoints, consumer: node.id, origin, stage: stage2, composition }).replace(/\$/g, "$$$$");
1692
+ }
1693
+ return output;
1694
+ }
1695
+ function validateJsonEnv(node, graph, endpoints, stage2, composition, shadowed) {
1696
+ resolveJsonEnv(node, graph, endpoints, stage2, composition, shadowed);
1697
+ }
1698
+ function validateReserved(node, keys, stage2, composition) {
1699
+ for (const key of keys) if (key in node.declaration.env) {
1700
+ const origin = node.envOrigins.get(key) ?? node.origin;
1701
+ assertNoBuilderOwnedEnvKeys({ [key]: node.declaration.env[key] }, [key], { sourceFile: origin.sourceFile, configPath: origin.configPath.replace(/\.env\.[^.]+$/, ".env"), stage: stage2, composition });
1702
+ }
1703
+ }
1704
+ function compileGraphComposition(input) {
1705
+ const profile = executionProfile(input.stage, input.composition, input.full), graph = makeGraph(input), allocator = new GeneratedComposeNameAllocator(["builder"]);
1706
+ const projectName = deriveProjectName(input.name, input.stage, input.projectDir), compose = { name: projectName, services: {}, networks: { builder: { driver: "bridge" } } };
1707
+ const mainServiceNames = /* @__PURE__ */ new Map(), modules = /* @__PURE__ */ new Map(), runtimeServiceNames = [], deferredHealthChecks = [];
1708
+ const mainOverrideEnv = /* @__PURE__ */ new Map();
1709
+ for (const [id, node] of [...graph.nodes].sort(([a], [b]) => a.localeCompare(b))) {
1710
+ if (node.kind === "main") {
1711
+ resolveApplicationDockerfile(node.projectDir, "Dockerfile", input.stage);
1712
+ assertMainDockerfileContract(node.projectDir, profile.mainTarget);
1713
+ const serviceName = allocator.allocate(JSON.stringify([id, "main"]), node.meshRoot ?? "main");
1714
+ mainServiceNames.set(id, serviceName);
1715
+ const service = mainSeed(input.stage);
1716
+ const build = service.build;
1717
+ build.context = path.relative(input.projectDir, node.projectDir).replace(/\\/g, "/") || ".";
1718
+ build.dockerfile = "Dockerfile";
1719
+ build.target = profile.mainTarget;
1720
+ service.build = build;
1721
+ service.env_file = [{ path: path.relative(input.projectDir, path.join(node.projectDir, `.env.${profile.envStage}`)).replace(/\\/g, "/"), required: false }];
1722
+ const selected = selectedOverride(input.instances.get(node.meshRoot ?? ""), "main");
1723
+ if (selected) {
1724
+ const file = resolveInsideProject(selected.origin.projectDir, selected.path, { sourceFile: selected.origin.sourceFile, configPath: selected.origin.configPath, stage: input.stage });
1725
+ const raw = loadComposeDocument(file, { sourceFile: selected.origin.sourceFile, configPath: selected.origin.configPath, stage: input.stage, composition: input.composition });
1726
+ const rebased = rebaseAppOverridePaths(raw, selected.origin.projectDir, input.projectDir);
1727
+ const prepared = validateAndPrepareMainOverride(rebased, { file, stage: input.stage, expectedBuildContext: String(build.context), buildContextBaseDir: input.projectDir, allocator, resourceNamespace: node.meshRoot ?? "main" });
1728
+ validateMaterializedComposeFiles(raw, file, input.stage, { baseDir: selected.origin.projectDir, composition: input.composition });
1729
+ for (const section of ["volumes", "networks", "configs", "secrets"]) if (prepared.resources[section]) mergeDocument(compose, { services: {}, [section]: prepared.resources[section] }, selected.origin, input.stage);
1730
+ mainOverrideEnv.set(id, normalizeComposeEnvironment(prepared.main.environment, `${selected.origin.configPath}.services.main.environment`));
1731
+ const overlay = { ...prepared.main };
1732
+ delete overlay.environment;
1733
+ delete overlay.build;
1734
+ Object.assign(service, mergeMainOverride(service, overlay));
1735
+ if (prepared.main.build && typeof prepared.main.build === "object") Object.assign(service.build, { args: prepared.main.build.args });
1403
1736
  }
1404
- }
1405
- return result;
1406
- };
1407
- const runtimeDotenv = path.join(root, `.env.${profile.envStage}`);
1408
- assertDotenvDoesNotDefineKeys(runtimeDotenv, [EXEC_MODE_KEY, INFRA_MODE_KEY, ...getPrimaryEndpoint(effective.app.endpoints) ? [PORT_KEY] : []], { configPath: `.env.${profile.envStage}`, stage, composition: "service" });
1409
- const internal = { EXEC_MODE: profile.execMode, INFRA_MODE: profile.infraMode, ...getPrimaryEndpoint(effective.app.endpoints) ? { PORT: String(getPrimaryEndpoint(effective.app.endpoints)[1].port) } : {} };
1410
- const appBuild = app.build && typeof app.build === "object" ? app.build : { context: "." };
1411
- const outputDir = options.composeOutputDir ? path.resolve(options.composeOutputDir) : root;
1412
- const serviceContext = path.relative(outputDir, root).replace(/\\/g, "/") || ".";
1413
- appBuild.context = options.meshMode ? serviceContext : ".";
1414
- if (raw.dockerfile) appBuild.dockerfile = raw.dockerfile;
1415
- else delete appBuild.dockerfile;
1416
- appBuild.target = profile.appTarget;
1417
- app.build = appBuild;
1418
- app.env_file = [{ path: options.meshMode ? path.posix.join(serviceContext, `.env.${profile.envStage}`) : `.env.${profile.envStage}`, required: false }];
1419
- app.environment = { ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
1420
- if (stage === "dev") app.volumes = [`${options.meshMode && serviceContext !== "." ? `./${serviceContext}` : "."}:/app`, "/app/node_modules"];
1421
- for (const [name, ep] of Object.entries(appEndpoints)) if (!options.meshMode && ep.effectivelyPublished) addPorts(app, [[ep, ep.publicPort]], buildPath, stage);
1422
- for (const [key, dependency] of Object.entries(materialized)) {
1423
- for (const [epName, owner] of dependency.endpointOwnerMap.entries()) {
1424
- const endpoint = depEndpoints[key][epName];
1425
- if (!options.meshMode && endpoint.effectivelyPublished) addPorts(compose.services[owner], [[endpoint, endpoint.publicPort]], dependency.composePath, stage);
1426
- }
1427
- for (const owner of dependency.endpointOwners) {
1428
- const svc = compose.services[owner];
1429
- if (!options.meshMode && svc.networks !== void 0) {
1430
- const nets = svc.networks;
1431
- if (Array.isArray(nets)) {
1432
- if (!nets.includes("default")) nets.push("default");
1433
- } else if (nets && typeof nets === "object") nets.default = null;
1737
+ withBuilderNetwork(service);
1738
+ compose.services[serviceName] = service;
1739
+ runtimeServiceNames.push(serviceName);
1740
+ } else {
1741
+ const def = node.declaration;
1742
+ if (def.kind !== "ordinary") continue;
1743
+ const file = resolveInsideProject(node.projectDir, def.compose, { sourceFile: node.origin.sourceFile, configPath: `${node.origin.configPath}.compose`, stage: input.stage });
1744
+ const raw = loadComposeDocument(file, { sourceFile: node.origin.sourceFile, configPath: `${node.origin.configPath}.compose`, stage: input.stage, composition: input.composition });
1745
+ for (const [local, service] of Object.entries(raw.services ?? {})) {
1746
+ const envFiles = Array.isArray(service.env_file) ? service.env_file : service.env_file ? [service.env_file] : [];
1747
+ for (const item of envFiles) {
1748
+ const candidate = typeof item === "string" ? item : item && typeof item === "object" ? item.path : void 0;
1749
+ if (typeof candidate === "string") assertDotenvDoesNotDefineKeys(path.resolve(path.dirname(file), candidate), [EXEC_MODE_KEY, INFRA_MODE_KEY], { configPath: `services.${local}.env_file`, stage: input.stage, composition: input.composition });
1750
+ }
1751
+ }
1752
+ let deferredHealthRepresentative;
1753
+ const representative = validateServiceCompose(displayNode(id), def, raw, { composePath: file, stage: input.stage, composition: input.composition, declarationOrigin: node.origin, healthRequired: input.stage === "e2e" && graph.lifecycle.get(id) !== "prerequisite" || graph.edges.some((edge) => edge.target === id && edge.kind === "dependency"), prerequisite: graph.lifecycle.get(id) === "prerequisite", deferHealth: (name) => {
1754
+ deferredHealthRepresentative = name;
1755
+ } });
1756
+ validateMaterializedComposeFiles(raw, file, input.stage, { composition: input.composition });
1757
+ validateMaterializedComposeBuildInputs(raw, file, input.stage, input.composition);
1758
+ const rebased = rebaseComposePaths(raw, file, input.projectDir), prefix = node.meshRoot ? `svc--${node.meshRoot}--${node.sourceService}` : `svc--${node.sourceService}`;
1759
+ const named = namespaceDependencyCompose({ dependencyKey: displayNode(id), namespacePrefix: prefix, document: rebased, allocator, identityPrefix: id });
1760
+ if (deferredHealthRepresentative) {
1761
+ const serviceName = named.serviceNameMap.get(deferredHealthRepresentative), service = named.document.services[serviceName];
1762
+ const image = typeof service.image === "string" ? service.image : `${projectName}-${serviceName}`;
1763
+ if (service.build === void 0 && service.image === void 0) throw new ConfigError({ sourceFile: file, configPath: `services.${deferredHealthRepresentative}.healthcheck`, stage: input.stage, composition: input.composition, reason: "Required healthcheck has no Compose declaration or inspectable image" });
1764
+ deferredHealthChecks.push({ serviceName, image, sourceFile: file, configPath: `services.${deferredHealthRepresentative}.healthcheck` });
1765
+ }
1766
+ for (const service of Object.values(named.document.services)) withBuilderNetwork(service);
1767
+ const endpointOwnerMap = /* @__PURE__ */ new Map();
1768
+ for (const [endpoint, value] of Object.entries(def.endpoints)) endpointOwnerMap.set(endpoint, named.serviceNameMap.get(value.service));
1769
+ const module = { nodeId: id, sourceFile: file, document: named.document, serviceNameMap: named.serviceNameMap, representative: named.serviceNameMap.get(representative), serviceNames: Object.keys(named.document.services), endpointOwnerMap };
1770
+ modules.set(id, module);
1771
+ mergeDocument(compose, named.document, node.origin, input.stage);
1772
+ runtimeServiceNames.push(...module.serviceNames);
1773
+ }
1774
+ }
1775
+ const endpoints = /* @__PURE__ */ new Map();
1776
+ for (const [id, node] of graph.nodes) {
1777
+ const records = {};
1778
+ for (const [name, definition] of Object.entries(node.declaration.endpoints)) {
1779
+ const owner = node.kind === "main" ? mainServiceNames.get(id) : modules.get(id).endpointOwnerMap.get(name);
1780
+ records[name] = { logicalPath: portKey(id, name), networkHost: owner, networkPort: definition.port, ...definition.scheme ? { scheme: definition.scheme } : {}, effectivelyPublished: false };
1781
+ }
1782
+ endpoints.set(id, records);
1783
+ }
1784
+ const publish = input.mesh ? new Map(Object.entries(input.mesh.services).map(([root, entry]) => [root, entry.publish])) : void 0;
1785
+ const publishOrigins = input.mesh ? new Map(Object.entries(input.mesh.services).flatMap(([root, entry]) => entry.publishOrigin ? [[root, entry.publishOrigin]] : [])) : void 0;
1786
+ const intents = resolvePublicationIntent(graph, input.stage, input.composition, publish, input.mesh?.sourceFile, publishOrigins);
1787
+ for (const item of intents) {
1788
+ const record = endpoints.get(item.nodeId)[item.endpoint];
1789
+ record.effectivelyPublished = true;
1790
+ record.publicHost = "127.0.0.1";
1791
+ record.publicPort = 1;
1792
+ }
1793
+ for (const [id, node] of graph.nodes) {
1794
+ const override = mainOverrideEnv.get(id) ?? {};
1795
+ const shadowed = new Set(node.kind === "main" ? Object.keys(override).filter((key) => node.envOrigins.get(key)?.scope !== "mesh") : []);
1796
+ validateJsonEnv(node, graph, endpoints, input.stage, input.composition, shadowed);
1797
+ }
1798
+ const tester = input.mesh?.tester ?? input.instances.get("")?.services.tester;
1799
+ const testerOrigin = input.mesh ? { sourceFile: input.mesh.sourceFile, configPath: "services.tester", projectDir: input.projectDir, scope: "mesh", layer: "base" } : { sourceFile: input.instances.get("").sourceFile, configPath: "services.tester", projectDir: input.projectDir, scope: "build", layer: "base" };
1800
+ const testerLayers = input.mesh ? input.mesh.testerLayers.map((layer) => ({ entry: layer.services.tester, origin: layer.origin })) : input.instances.get("").layers.map((layer) => ({ entry: layer.services.tester, origin: { ...layer.origin, configPath: `${layer.origin.configPath}.tester` } }));
1801
+ let serviceOrigin = { ...testerOrigin, configPath: `${testerOrigin.configPath}.service` };
1802
+ const testerEnvOrigins = /* @__PURE__ */ new Map();
1803
+ for (const layer of testerLayers) {
1804
+ const entry = layer.entry;
1805
+ if (!entry) continue;
1806
+ if (entry.service !== void 0) serviceOrigin = { ...layer.origin, configPath: `${layer.origin.configPath}.service` };
1807
+ for (const key of Object.keys(entry.env ?? {})) testerEnvOrigins.set(key, { ...layer.origin, configPath: `${layer.origin.configPath}.env.${key}` });
1808
+ }
1809
+ profile.attachTester ? compileTester({ tester, origin: testerOrigin, serviceOrigin, envOrigins: testerEnvOrigins, graph, endpoints, stage: input.stage, composition: input.composition, projectDir: input.projectDir, allocator}) : void 0;
1810
+ const allocations = allocateHostPorts(input.projectDir, input.stage, intents.map((item) => ({ logicalPath: item.logicalPath, requested: item.requestedPort })), Boolean(input.validationMode), { sourceFile: input.mesh?.sourceFile ?? input.instances.get("").sourceFile, composition: input.composition });
1811
+ for (const item of intents) {
1812
+ const record = endpoints.get(item.nodeId)[item.endpoint];
1813
+ record.publicPort = allocations.get(item.logicalPath);
1814
+ const owner = graph.nodes.get(item.nodeId).kind === "main" ? mainServiceNames.get(item.nodeId) : modules.get(item.nodeId).endpointOwnerMap.get(item.endpoint);
1815
+ addPort(compose.services[owner], record);
1816
+ }
1817
+ for (const [id, node] of graph.nodes) {
1818
+ const primary = Object.values(node.declaration.endpoints).find((endpoint) => endpoint.primary);
1819
+ const reserved = node.kind === "main" ? [EXEC_MODE_KEY, INFRA_MODE_KEY, ...primary ? [PORT_KEY] : []] : [EXEC_MODE_KEY, INFRA_MODE_KEY];
1820
+ validateReserved(node, reserved, input.stage, input.composition);
1821
+ if (node.kind === "main") {
1822
+ const service = compose.services[mainServiceNames.get(id)], override = mainOverrideEnv.get(id) ?? {};
1823
+ assertNoBuilderOwnedEnvKeys(override, reserved, { sourceFile: node.origin.sourceFile, configPath: "services.main.override-compose.environment", stage: input.stage, composition: input.composition });
1824
+ assertDotenvDoesNotDefineKeys(path.join(node.projectDir, `.env.${profile.envStage}`), reserved, { configPath: `.env.${profile.envStage}`, stage: input.stage, composition: input.composition });
1825
+ const buildEnv = resolveJsonEnv(node, graph, endpoints, input.stage, input.composition, new Set(Object.keys(override).filter((key) => node.envOrigins.get(key)?.scope !== "mesh")));
1826
+ const sourceEnv = Object.fromEntries(Object.entries(buildEnv).filter(([key]) => node.envOrigins.get(key)?.scope !== "mesh"));
1827
+ const meshEnv = Object.fromEntries(Object.entries(buildEnv).filter(([key]) => node.envOrigins.get(key)?.scope === "mesh"));
1828
+ service.environment = { ...sourceEnv, ...override, ...meshEnv, EXEC_MODE: profile.execMode, INFRA_MODE: profile.infraMode, ...primary ? { PORT: String(primary.port) } : {} };
1829
+ } else {
1830
+ const module = modules.get(id);
1831
+ for (const name of module.serviceNames) {
1832
+ const service = compose.services[name];
1833
+ const defaults = normalizeComposeEnvironment(service.environment, `services.${name}.environment`);
1834
+ assertNoBuilderOwnedEnvKeys(defaults, [EXEC_MODE_KEY, INFRA_MODE_KEY], { sourceFile: module.sourceFile, configPath: `services.${name}.environment`, stage: input.stage, composition: input.composition });
1835
+ service.environment = { ...defaults, ...resolveJsonEnv(node, graph, endpoints, input.stage, input.composition, /* @__PURE__ */ new Set()) };
1434
1836
  }
1435
1837
  }
1436
- for (const [epName, ep] of Object.entries(depEndpoints[key])) dependency.endpoints[epName] = ep;
1437
1838
  }
1438
- for (const layer of effective.layers) {
1439
- if (!layer.overrideCompose) continue;
1440
- const overridePath = resolveInsideProject(root, layer.overrideCompose, {
1441
- sourceFile: buildPath,
1442
- configPath: `${layer.stage}.override-compose`,
1443
- stage
1444
- });
1445
- const loadedOverride = loadComposeDocument(overridePath, {
1446
- sourceFile: buildPath,
1447
- configPath: `${layer.stage}.override-compose`,
1448
- stage,
1449
- composition: "service"
1450
- });
1451
- const overrideDocument = rebaseAppOverridePaths(loadedOverride, root, outputDir);
1452
- const prepared = validateAndPrepareAppOverride(overrideDocument, {
1453
- file: overridePath,
1454
- stage: layer.stage === "base" ? stage : layer.stage,
1455
- expectedBuildContext: String(appBuild.context),
1456
- buildContextBaseDir: outputDir,
1457
- allocator: nameAllocator,
1458
- resourceNamespace: options.meshMode ? options.appServiceName ?? "app" : "app"
1459
- });
1460
- for (const section of ["volumes", "networks", "configs", "secrets"]) if (prepared.resources[section]) mergeDocument(compose, { services: {}, [section]: prepared.resources[section] }, { sourceFile: overridePath, configPath: `${layer.stage}.override-compose`, stage, composition: "service" });
1461
- const rawOverrideEnv = normalizeComposeEnvironment(prepared.app.environment, `${layer.stage}.override-compose.services.app.environment`);
1462
- const overrideEnv = rawOverrideEnv;
1463
- 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" });
1464
- const overrideStage = layer.stage === "base" ? stage : layer.stage;
1465
- const stageOrder = { base: 0, dev: 1, prod: 1, test: 1, e2e: 2 };
1466
- let insertAt = appEnvironmentLayers.findIndex((item) => (stageOrder[item.stage] ?? 0) > (stageOrder[overrideStage] ?? 0));
1467
- if (insertAt < 0) insertAt = appEnvironmentLayers.length;
1468
- appEnvironmentLayers.splice(insertAt, 0, { kind: "override-compose", stage: overrideStage, sourceFile: overridePath, configPath: `${layer.stage}.override-compose.services.app.environment`, values: overrideEnv });
1469
- const preparedApp = { ...prepared.app };
1470
- delete preparedApp.environment;
1471
- delete preparedApp.build;
1472
- const merged = mergeAppOverride(app, preparedApp);
1473
- merged.environment = { ...app.environment, ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
1474
- const overrideBuild = prepared.app.build && typeof prepared.app.build === "object" ? prepared.app.build : {};
1475
- if (overrideBuild.args !== void 0) {
1476
- const current = appBuild.args, incoming = overrideBuild.args;
1477
- appBuild.args = current && incoming && typeof current === "object" && typeof incoming === "object" && !Array.isArray(current) && !Array.isArray(incoming) ? { ...current, ...incoming } : incoming;
1478
- }
1479
- merged.build = appBuild;
1480
- merged.env_file = app.env_file;
1481
- merged.depends_on = app.depends_on;
1482
- merged.networks = { ...!options.meshMode ? { default: null } : {}, ...normalizeNetworks(app.networks), ...normalizeNetworks(prepared.app.networks) };
1483
- compose.services.app = merged;
1484
- app = merged;
1485
- }
1486
- if (!options.deferReferenceResolution) {
1487
- const finalEnv = resolveAppLayers();
1488
- app.environment = { ...finalEnv, ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
1489
- }
1490
- if (options.meshMode && options.appServiceName && options.appServiceName !== "app") {
1491
- delete compose.services.app;
1492
- compose.services[options.appServiceName] = app;
1493
- }
1494
- if (profile.infraMode === "integrated") applyDependencyLifecycle(app, materialized, effective);
1495
- if (profile.attachTester && !options.meshMode) {
1496
- const testerDotenvPath = path.join(root, ".env.e2e-tester"), testerBuilderKeys = [EXEC_MODE_KEY, INFRA_MODE_KEY];
1497
- assertDotenvDoesNotDefineKeys(testerDotenvPath, testerBuilderKeys, { configPath: ".env.e2e-tester", stage: "e2e", composition: "service" });
1498
- const testerEnvRaw = effective.tester?.env ?? {};
1499
- assertNoBuilderOwnedEnvKeys(testerEnvRaw, testerBuilderKeys, { sourceFile: buildPath, configPath: "tester.env", stage: "e2e", composition: "service" });
1500
- const testerContext = { sourceFile: buildPath, configPath: "tester.env", stage: "e2e", composition: "service" };
1501
- assertTesterReferencesArePublic(testerEnvRaw, "build", testerContext);
1502
- const testerEnv = options.deferReferenceResolution ? testerEnvRaw : resolveEnv(testerEnvRaw, registry, testerContext);
1503
- compose.services.tester = { build: { context: ".", ...raw.dockerfile ? { dockerfile: raw.dockerfile } : {}, target: profile.testerTarget ?? "test-e2e" }, network_mode: "host", env_file: [{ path: ".env.e2e-tester", required: false }], environment: { ...testerEnv, EXEC_MODE: "e2e" }, depends_on: { app: { condition: "service_healthy" } } };
1504
- }
1505
- nameAllocator.assertUnique();
1506
- return { compose, effectiveBuild: effective, endpoints: { app: appEndpoints, dependencies: depEndpoints }, projectName, ...profile.attachTester && !options.meshMode ? { testerServiceName: "tester" } : {}, appEnvironmentLayers, builderInternalEnvironment: { ...internal }, externalAppEnvironment: { ...options.externalAppEnv ?? {} }, dependencyServiceNames: Object.fromEntries(Object.entries(materialized).map(([key, dep]) => [key, [...dep.serviceNames]])), dependencyEnvironments: Object.fromEntries(Object.entries(effective.dependencies).map(([key, dep]) => [key, dep.env])) };
1839
+ for (const edge of graph.edges) {
1840
+ if (edge.kind === "requirement") continue;
1841
+ const consumer = graph.nodes.get(edge.consumer), target = graph.nodes.get(edge.target);
1842
+ const targetName = target.kind === "main" ? mainServiceNames.get(edge.target) : modules.get(edge.target).representative;
1843
+ const memberNames = consumer.kind === "main" ? [mainServiceNames.get(edge.consumer)] : modules.get(edge.consumer).serviceNames;
1844
+ for (const name of memberNames) addComposeCondition(compose.services[name], targetName, edge.kind === "dependency" ? "service_healthy" : "service_completed_successfully");
1845
+ }
1846
+ let testerServiceName, testerServiceNames = [];
1847
+ if (profile.attachTester) {
1848
+ const built = compileTester({ tester, origin: testerOrigin, serviceOrigin, envOrigins: testerEnvOrigins, graph, endpoints, stage: input.stage, composition: input.composition, projectDir: input.projectDir, allocator});
1849
+ mergeDocument(compose, built.document, testerOrigin, input.stage);
1850
+ testerServiceName = built.runner;
1851
+ testerServiceNames = built.serviceNames;
1852
+ const runner = compose.services[built.runner];
1853
+ for (const [id, node] of graph.nodes) {
1854
+ const target = node.kind === "main" ? mainServiceNames.get(id) : modules.get(id).representative;
1855
+ addComposeCondition(runner, target, graph.lifecycle.get(id) === "prerequisite" ? "service_completed_successfully" : "service_healthy");
1856
+ }
1857
+ }
1858
+ assertComposeLifecycleAcyclic(compose.services, { sourceFile: input.mesh?.sourceFile ?? input.instances.get("").sourceFile, stage: input.stage, composition: input.composition });
1859
+ allocator.assertUnique();
1860
+ for (const service of Object.values(compose.services)) markOwned(service);
1861
+ for (const section of ["networks", "volumes"]) for (const resource of Object.values(compose[section] ?? {})) if (resource && typeof resource === "object" && !Array.isArray(resource) && !resource.external) markOwned(resource);
1862
+ return { compose, projectName, graph, mainServiceNames, modules, endpoints, runtimeServiceNames: unique(runtimeServiceNames), testerServiceNames, ...testerServiceName ? { testerServiceName } : {}, allocations, deferredHealthChecks };
1863
+ }
1864
+
1865
+ // src/core/composition/compileServiceComposition.ts
1866
+ function compileServiceComposition(stage2, projectDir, options = {}) {
1867
+ const root = resolveProjectDir(projectDir), build = resolveBuildStage(getBuildJson(root), stage2, path.join(root, "build.json"));
1868
+ return compileGraphComposition({ stage: stage2, composition: "service", projectDir: root, name: build.name, instances: /* @__PURE__ */ new Map([["", build]]), full: Boolean(options.full), validationMode: Boolean(options.validationMode) });
1507
1869
  }
1508
1870
 
1509
1871
  // src/core/checkers/checkEffectiveServiceStages.ts
@@ -1516,14 +1878,13 @@ function checkAllEffectiveServiceStages(projectDir) {
1516
1878
  }
1517
1879
 
1518
1880
  // src/core/checkers/checkInfra.ts
1519
- function checkInfra(projectDir = process.cwd()) {
1881
+ function checkInfra(projectDir = process.cwd(), adapters = {}) {
1520
1882
  const absProjectDir = resolveProjectDir(projectDir);
1521
1883
  const buildJson = getBuildJson(absProjectDir);
1522
- checkDockerfile(buildJson, absProjectDir);
1523
- checkDockerfileContract(buildJson, absProjectDir);
1524
- checkYamlFiles(buildJson, absProjectDir);
1884
+ (adapters.dockerfile ?? checkDockerfile)(buildJson, absProjectDir);
1885
+ (adapters.dockerfileContract ?? checkDockerfileContract)(buildJson, absProjectDir);
1525
1886
  checkAllEffectiveServiceStages(absProjectDir);
1526
- console.log(pc14.green("\n\u2705 All V2 service infrastructure and contract checks passed.\n"));
1887
+ console.log(pc9.green("\nAll V3 service infrastructure and contract checks passed.\n"));
1527
1888
  }
1528
1889
  function checkComposeAvailability() {
1529
1890
  const composeCheck = spawnSync(
@@ -1568,7 +1929,7 @@ function checkDependencies() {
1568
1929
  const count = (networkCheck.stdout || "").trim().split("\n").filter(Boolean).length;
1569
1930
  if (count > 25) {
1570
1931
  console.warn(
1571
- pc14.yellow(
1932
+ pc9.yellow(
1572
1933
  `
1573
1934
  \u26A0\uFE0F High Docker Network Count Warning: Detected ${count} networks. Docker's default address pool can become exhausted, resulting in "could not find an available, non-overlapping IPv4 address pool" errors.
1574
1935
  To resolve, run "builder prune" or "docker network prune -f", or configure default-address-pools in /etc/docker/daemon.json.
@@ -1607,14 +1968,65 @@ Examples:
1607
1968
  }
1608
1969
  });
1609
1970
  };
1610
- var identifierSchema2 = z.string().regex(BUILDER_IDENTIFIER_PATTERN, "must match ^[a-z][a-z0-9-]*$");
1611
- var serviceNameSchema = identifierSchema2.refine((name) => !RESERVED_MESH_SERVICE_NAMES.has(name), { message: "is reserved and cannot be used as a mesh service name" });
1612
- var envSchema2 = z.record(z.string(), z.string());
1613
- 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();
1614
- 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();
1615
- var meshStageSchema = z.object({ services: z.record(serviceNameSchema, meshServiceStageOverlaySchema).optional() }).strict();
1616
- var rootServicesSchema = z.record(serviceNameSchema, meshServiceSchema).refine((services) => Object.keys(services).length >= 1, { message: "must contain at least one root service" });
1617
- 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: rootServicesSchema, dev: meshStageSchema.optional(), prod: meshStageSchema.optional(), test: meshStageSchema.optional(), e2e: meshStageSchema.optional() }).strict();
1971
+
1972
+ // src/core/mesh/types.ts
1973
+ var MESH_CONFIG_STAGES = ["dev", "prod", "e2e"];
1974
+ var MESH_COMMAND_STAGES = ["dev", "prod", "test"];
1975
+
1976
+ // src/core/config/meshStageContract.ts
1977
+ var REMOVED_MESH_TEST_MESSAGE = "mesh.json.test is no longer supported. A mesh has no test topology. Put service-owned isolated test settings in build.json.test; put global E2E topology settings in mesh.json.e2e. The mesh test command runs independent service tests, then global E2E.";
1978
+ function assertNoLegacyMeshTest(input, sourceFile) {
1979
+ if (input !== null && typeof input === "object" && !Array.isArray(input) && Object.prototype.hasOwnProperty.call(input, "test")) {
1980
+ throw new ConfigError({
1981
+ sourceFile,
1982
+ configPath: "test",
1983
+ composition: "mesh",
1984
+ reason: REMOVED_MESH_TEST_MESSAGE
1985
+ });
1986
+ }
1987
+ }
1988
+ function assertMeshConfigStage(stage2, sourceFile) {
1989
+ if (typeof stage2 !== "string" || !MESH_CONFIG_STAGES.includes(stage2)) {
1990
+ throw new ConfigError({
1991
+ sourceFile,
1992
+ configPath: "<stage>",
1993
+ composition: "mesh",
1994
+ reason: "Unsupported mesh configuration stage. Supported stages: dev, prod, e2e. test is a pipeline command, not a mesh configuration stage."
1995
+ });
1996
+ }
1997
+ }
1998
+ function meshStageOverlayChain(stage2) {
1999
+ return stage2 === "e2e" ? ["prod", "e2e"] : [stage2];
2000
+ }
2001
+ var identifier2 = z.string().regex(BUILDER_IDENTIFIER_PATTERN);
2002
+ var nonblank2 = z.string().min(1).refine((value) => value.trim().length > 0, "must not be blank");
2003
+ var meshRequisites = z.record(z.string().regex(/^(?:source\.)?[a-z][a-z0-9-]*$/), z.union([z.enum(["requirement", "dependency", "prerequisite"]), z.literal(false)]));
2004
+ var meshMainOverlay = mainOverlaySchema.extend({ requisites: meshRequisites.optional() }).strict();
2005
+ var meshOrdinaryOverlay = ordinaryOverlaySchema.extend({ requisites: meshRequisites.optional() }).strict();
2006
+ var extendsSchema = z.record(identifier2, z.unknown()).superRefine((value, context) => {
2007
+ for (const [key, entry] of Object.entries(value)) {
2008
+ const parsed = (key === "main" ? meshMainOverlay : key === "tester" ? testerOverlaySchema : meshOrdinaryOverlay).safeParse(entry);
2009
+ if (!parsed.success) for (const issue of parsed.error.issues) context.addIssue({ ...issue, path: [key, ...issue.path] });
2010
+ }
2011
+ });
2012
+ var meshSourceSchema = z.object({ source: nonblank2, extends: extendsSchema.optional(), publish: z.array(z.string()).optional() }).strict();
2013
+ var meshSourceOverlaySchema = meshSourceSchema.partial().strict();
2014
+ var services = (overlay) => z.record(identifier2, z.unknown()).superRefine((value, context) => {
2015
+ if (!overlay) {
2016
+ if (!("tester" in value)) context.addIssue({ code: "custom", path: ["tester"], message: "tester is required" });
2017
+ if (!Object.keys(value).some((key) => key !== "tester" && key !== "main")) context.addIssue({ code: "custom", message: "at least one source is required" });
2018
+ }
2019
+ for (const [key, entry] of Object.entries(value)) {
2020
+ if (key === "main") {
2021
+ context.addIssue({ code: "custom", path: [key], message: "main is reserved as a mesh source name" });
2022
+ continue;
2023
+ }
2024
+ const parsed = (key === "tester" ? overlay ? testerOverlaySchema : testerServiceSchema : overlay ? meshSourceOverlaySchema : meshSourceSchema).safeParse(entry);
2025
+ if (!parsed.success) for (const issue of parsed.error.issues) context.addIssue({ ...issue, path: [key, ...issue.path] });
2026
+ }
2027
+ });
2028
+ var stage = z.object({ services: services(true).optional() }).strict();
2029
+ var meshSchema = z.object({ $schema: z.string().optional(), name: nonblank2, services: services(false), dev: stage.optional(), prod: stage.optional(), e2e: stage.optional() }).strict();
1618
2030
 
1619
2031
  // src/core/mesh/getMeshJson.ts
1620
2032
  function getMeshJson(projectDir = process.cwd()) {
@@ -1632,6 +2044,7 @@ function getMeshJson(projectDir = process.cwd()) {
1632
2044
  } catch (err) {
1633
2045
  throw new ScriptError(`Failed to parse mesh.json at ${meshPath}: ${errorMessage(err)}`);
1634
2046
  }
2047
+ assertNoLegacyMeshTest(parsed, meshPath);
1635
2048
  const result = meshSchema.safeParse(parsed);
1636
2049
  if (!result.success) {
1637
2050
  const reason = result.error.issues.map((issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`).join("; ");
@@ -1639,630 +2052,130 @@ function getMeshJson(projectDir = process.cwd()) {
1639
2052
  }
1640
2053
  return result.data;
1641
2054
  }
1642
-
1643
- // src/core/config/resolveMeshStage.ts
1644
- function resolveMeshStage(mesh, stage, sourceFile) {
1645
- if (Object.keys(mesh.services).length === 0) throw new ConfigError({ sourceFile, configPath: "services", stage, composition: "mesh", reason: "mesh.json must declare at least one root service" });
1646
- const services = {};
1647
- for (const [name, service] of Object.entries(mesh.services)) services[name] = { path: service.path, env: { ...service.env ?? {} }, dependencies: { ...service.dependencies ?? {} }, dependsOn: [...service.dependsOn ?? []], publish: [...service.publish ?? []] };
1648
- for (const overlayStage of stageOverlayChain(stage)) for (const [name, patch] of Object.entries(mesh[overlayStage]?.services ?? {})) {
1649
- const prior = services[name] ?? { path: void 0, env: {}, dependencies: {}, dependsOn: [], publish: [] };
1650
- services[name] = { path: patch.path ?? prior.path, env: mergeStringMap(prior.env, patch.env), dependencies: { ...prior.dependencies, ...patch.dependencies ?? {} }, dependsOn: unionStable(prior.dependsOn, patch.dependsOn), publish: unionStable(prior.publish, patch.publish) };
1651
- }
1652
- if (!Object.keys(services).length) throw new ConfigError({ sourceFile, configPath: "services", stage, composition: "mesh", reason: "At least one effective mesh service is required" });
1653
- for (const [name, service] of Object.entries(services)) if (!service.path) throw new ConfigError({ sourceFile, configPath: `services.${name}.path`, stage, composition: "mesh", reason: "Effective mesh service requires path" });
1654
- const graph = /* @__PURE__ */ new Map();
1655
- for (const [name, service] of Object.entries(services)) {
1656
- 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" });
1657
- graph.set(name, /* @__PURE__ */ new Set());
1658
- for (const target of service.dependsOn) {
1659
- if (target === name) throw new ConfigError({ sourceFile, configPath: `services.${name}.dependsOn`, stage, composition: "mesh", referencedObject: target, reason: "Mesh service cannot depend on itself" });
1660
- if (!services[target]) throw new ConfigError({ sourceFile, configPath: `services.${name}.dependsOn`, stage, composition: "mesh", referencedObject: target, reason: "Unknown mesh lifecycle target" });
1661
- graph.get(name).add(target);
1662
- }
1663
- }
1664
- assertAcyclicGraph(graph, { sourceFile, stage, composition: "mesh" });
1665
- const result = { ...mesh, services };
1666
- delete result.dev;
1667
- delete result.prod;
1668
- delete result.test;
1669
- delete result.e2e;
1670
- return result;
1671
- }
1672
- function loadEffectiveMeshServices(meshDir, effectiveMesh, stage) {
1673
- const out = {};
1674
- for (const [name, svc] of Object.entries(effectiveMesh.services).sort(([a], [b]) => a.localeCompare(b))) {
1675
- const abs = resolveInsideProject(meshDir, svc.path, { sourceFile: path.join(meshDir, "mesh.json"), configPath: `services.${name}.path`, stage });
1676
- if (!fs.existsSync(abs) || !fs.statSync(abs).isDirectory()) throw new ConfigError({ sourceFile: path.join(meshDir, "mesh.json"), configPath: `services.${name}.path`, stage, composition: "mesh", value: svc.path, reason: "Mesh service directory does not exist" });
1677
- const buildJsonPath = path.join(abs, "build.json"), build = getBuildJson(abs), effectiveBuild = resolveBuildStage(build, stage, buildJsonPath);
1678
- out[name] = { name, path: svc.path, absolutePath: abs, buildJsonPath, effectiveBuild, meshEnv: { ...svc.env ?? {} }, dependencyBindings: { ...svc.dependencies ?? {} }, dependsOn: [...svc.dependsOn ?? []], publish: [...svc.publish ?? []] };
1679
- }
1680
- return out;
1681
- }
1682
-
1683
- // src/core/mesh/v2/substitution.ts
1684
- function buildDependencyBindings(services, stage, meshJsonPath) {
1685
- const out = [];
1686
- for (const service of Object.values(services)) {
1687
- for (const [logicalDependency, providerService] of Object.entries(service.dependencyBindings)) {
1688
- 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}` });
1689
- 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" });
1690
- out.push({ consumerService: service.name, logicalDependency, providerService });
1691
- }
1692
- }
1693
- return out;
1694
- }
1695
- function bindingKey(consumer, dependency) {
1696
- return `${consumer}::${dependency}`;
1697
- }
1698
- function bindingsMap(bindings) {
1699
- return new Map(bindings.map((b) => [bindingKey(b.consumerService, b.logicalDependency), b.providerService]));
1700
- }
1701
-
1702
- // src/core/mesh/v2/publication.ts
1703
- var APP = /^app\.endpoints\.([a-z][a-z0-9-]*)$/;
1704
- var DEP = /^dependencies\.([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)$/;
1705
- function resolveMeshPublication(services, bindings, stage, meshJsonPath) {
1706
- const out = [];
1707
- for (const svc of Object.values(services).sort((a, b) => a.name.localeCompare(b.name))) for (const raw of svc.publish) {
1708
- let m;
1709
- if (m = APP.exec(raw)) {
1710
- const ep = m[1], endpoint = svc.effectiveBuild.app.endpoints[ep];
1711
- if (!endpoint) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${svc.name}.publish`, stage, composition: "mesh", value: raw, reason: "Published app endpoint does not exist" });
1712
- 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" });
1713
- out.push({ logicalPath: `${svc.name}.app.endpoints.${ep}`, ownerMeshService: svc.name, target: "app", endpoint: ep });
2055
+ var originFor2 = (sourceFile, configPath, layer) => ({ sourceFile, configPath, projectDir: path.dirname(sourceFile), scope: "mesh", layer });
2056
+ function resolveMeshStage(mesh, stage2, sourceFile) {
2057
+ assertMeshConfigStage(stage2, sourceFile);
2058
+ const sources = {};
2059
+ const baseSources = Object.keys(mesh.services).filter((name) => name !== "tester").sort();
2060
+ const testerLayers = [];
2061
+ let tester = structuredClone(mesh.services.tester);
2062
+ testerLayers.push({ stage: "base", services: { tester: structuredClone(tester) }, origin: originFor2(sourceFile, "services.tester", "base") });
2063
+ for (const name of baseSources) {
2064
+ const entry = mesh.services[name];
2065
+ sources[name] = { source: entry.source, publish: [...entry.publish ?? []], publishOrigin: originFor2(sourceFile, `services.${name}.publish`, "base"), extendsLayers: entry.extends ? [{ layer: "base", patches: structuredClone(entry.extends), origin: originFor2(sourceFile, `services.${name}.extends`, "base") }] : [], origin: originFor2(sourceFile, `services.${name}`, "base") };
2066
+ }
2067
+ for (const layer of meshStageOverlayChain(stage2)) for (const [name, patch] of Object.entries(mesh[layer]?.services ?? {}).sort(([a], [b]) => a.localeCompare(b))) {
2068
+ if (name === "tester") {
2069
+ const next2 = patch;
2070
+ if (next2.compose !== void 0 && next2.compose !== tester.compose) throw new ConfigError({ sourceFile, configPath: `${layer}.services.tester.compose`, stage: stage2, composition: "mesh", reason: "compose is immutable; previous services.tester.compose", value: next2.compose });
2071
+ tester = mergeEffectiveObject(tester, next2);
2072
+ testerLayers.push({ stage: layer, services: { tester: structuredClone(next2) }, origin: originFor2(sourceFile, `${layer}.services.tester`, layer) });
1714
2073
  continue;
1715
2074
  }
1716
- if (m = DEP.exec(raw)) {
1717
- const dependency = m[1], endpoint = m[2], dep = svc.effectiveBuild.dependencies[dependency];
1718
- 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" });
1719
- 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" });
1720
- 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" });
1721
- 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" });
1722
- out.push({ logicalPath: `${svc.name}.dependencies.${dependency}.endpoints.${endpoint}`, ownerMeshService: svc.name, target: "dependency", dependency, endpoint });
1723
- continue;
1724
- }
1725
- 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>" });
1726
- }
1727
- return out;
1728
- }
1729
-
1730
- // src/core/mesh/v2/meshReferences.ts
1731
- function resolveMesh(ref, ctx, context) {
1732
- const name = ref.meshService;
1733
- if (!ctx.services[name]) throw new ConfigError({ ...context, referencedObject: ref.raw, reason: `Unknown mesh service reference "${name}"` });
1734
- const provider = ref.target === "dependency" ? ctx.bindings.get(bindingKey(name, ref.dependency)) : void 0;
1735
- const endpoint = ref.target === "app" ? ctx.endpoints.app[name]?.[ref.endpoint] : provider ? ctx.endpoints.app[provider]?.[ref.endpoint] : ctx.endpoints.dependencies[name]?.[ref.dependency]?.[ref.endpoint];
1736
- if (!endpoint) throw new ConfigError({ ...context, referencedObject: ref.raw, reason: "Referenced endpoint does not exist" });
1737
- return resolveEndpointProperty(endpoint, ref.property, { ...context, referencedObject: ref.raw });
1738
- }
1739
- function resolveBuild(ref, consumer, ctx, context) {
1740
- const provider = ref.target === "dependency" ? ctx.bindings.get(bindingKey(consumer, ref.dependency)) : void 0;
1741
- const endpoint = ref.target === "app" ? ctx.endpoints.app[consumer]?.[ref.endpoint] : provider ? ctx.endpoints.app[provider]?.[ref.endpoint] : ctx.endpoints.dependencies[consumer]?.[ref.dependency]?.[ref.endpoint];
1742
- if (!endpoint) {
1743
- const reason = provider ? `Provider "${provider}" does not expose endpoint "${ref.endpoint}"` : "Referenced endpoint does not exist";
1744
- throw new ConfigError({ ...context, referencedObject: ref.raw, reason });
1745
- }
1746
- try {
1747
- return resolveEndpointProperty(endpoint, ref.property, { ...context, referencedObject: ref.raw });
1748
- } catch (error) {
1749
- if (provider && error instanceof ConfigError) {
1750
- throw new ConfigError({
1751
- ...context,
1752
- referencedObject: `${consumer}.dependencies.${ref.dependency}.endpoints.${ref.endpoint}.${ref.property} -> ${provider}.app.endpoints.${ref.endpoint}.${ref.property}`,
1753
- reason: error.message
1754
- });
1755
- }
1756
- throw error;
1757
- }
1758
- }
1759
- function interpolate(value, scope, ctx, configPath, consumer) {
1760
- const context = {
1761
- sourceFile: scope === "mesh" ? ctx.meshJsonPath : ctx.services[consumer]?.buildJsonPath ?? ctx.meshJsonPath,
1762
- configPath,
1763
- stage: ctx.stage,
1764
- composition: scope === "mesh" ? "mesh" : "service"
1765
- };
1766
- return interpolateBuilderReferences(value, scope, (ref, refContext) => scope === "mesh" ? resolveMesh(ref, ctx, refContext) : resolveBuild(ref, consumer, ctx, refContext), context).replace(/\$/g, "$$$$");
1767
- }
1768
- function resolveMeshEnvMap(env, ctx, sourcePrefix) {
1769
- return Object.fromEntries(Object.entries(env).map(([key, value]) => [key, interpolate(value, "mesh", ctx, `${sourcePrefix}.${key}`)]));
1770
- }
1771
- function resolveServiceBuildEnvThroughMesh(consumer, env, ctx, sourcePrefix) {
1772
- return Object.fromEntries(Object.entries(env).map(([key, value]) => [key, interpolate(value, "build", ctx, `${sourcePrefix}.${key}`, consumer)]));
1773
- }
1774
- function assertMeshTesterEnvPublic(env, ctx, configPath = "tester.env") {
1775
- assertTesterReferencesArePublic(env, "mesh", {
1776
- sourceFile: ctx.meshJsonPath,
1777
- configPath,
1778
- stage: ctx.stage,
1779
- composition: "mesh"
1780
- });
1781
- }
1782
-
1783
- // src/core/mesh/v2/lifecycle.ts
1784
- function buildMeshLifecycleEdges(services, bindings, stage, meshJsonPath) {
1785
- const result = [];
1786
- const seen = /* @__PURE__ */ new Set();
1787
- 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)]) {
1788
- 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" });
1789
- const source = svc.dependsOn.includes(provider) ? "dependsOn" : "dependency-binding";
1790
- const id = `${svc.name}\0${provider}`;
1791
- if (!seen.has(id)) {
1792
- seen.add(id);
1793
- result.push({ consumer: svc.name, provider, source });
1794
- }
1795
- }
1796
- const graph = new Map(Object.keys(services).map((name) => [name, /* @__PURE__ */ new Set()]));
1797
- for (const edge of result) graph.get(edge.consumer).add(edge.provider);
1798
- assertAcyclicGraph(graph, { sourceFile: meshJsonPath, stage, composition: "mesh" });
1799
- return result;
1800
- }
1801
- function applyMeshLifecycleEdges(services, edges) {
1802
- for (const edge of edges) {
1803
- const consumer = services[edge.consumer];
1804
- const old = consumer.depends_on && typeof consumer.depends_on === "object" && !Array.isArray(consumer.depends_on) ? consumer.depends_on : {};
1805
- old[edge.provider] = { condition: "service_healthy" };
1806
- consumer.depends_on = old;
1807
- }
1808
- }
1809
-
1810
- // src/core/composition/composeDependsOn.ts
1811
- function normalizeComposeDependsOn(value) {
1812
- if (Array.isArray(value)) {
1813
- return Object.fromEntries(value.filter((item) => typeof item === "string").map((name) => [name, {}]));
1814
- }
1815
- return value && typeof value === "object" ? { ...value } : {};
1816
- }
1817
-
1818
- // src/core/mesh/v2/compileMeshTester.ts
1819
- function appendEnvFile(existing, next) {
1820
- if (existing === void 0) return [next];
1821
- return Array.isArray(existing) ? [...existing, next] : [existing, next];
1822
- }
1823
- function envFilePaths(value) {
1824
- const entries2 = Array.isArray(value) ? value : [value];
1825
- return entries2.flatMap((entry) => typeof entry === "string" ? [entry] : entry && typeof entry === "object" && typeof entry.path === "string" ? [entry.path] : []);
1826
- }
1827
- function validateServiceReferences(document, sourceFile, stage) {
1828
- for (const [name, service] of Object.entries(document.services)) {
1829
- const refs = [];
1830
- const add = (value) => {
1831
- if (typeof value === "string" && value) refs.push(value);
1832
- };
1833
- if (Array.isArray(service.depends_on)) service.depends_on.forEach(add);
1834
- else if (service.depends_on && typeof service.depends_on === "object") Object.keys(service.depends_on).forEach(add);
1835
- if (Array.isArray(service.links)) service.links.forEach((value) => add(typeof value === "string" ? value.split(":")[0] : void 0));
1836
- if (Array.isArray(service.volumes_from)) service.volumes_from.forEach((value) => add(typeof value === "string" ? value.split(":")[0] : void 0));
1837
- for (const key of ["network_mode", "ipc", "pid"]) {
1838
- const value = service[key];
1839
- if (typeof value === "string" && value.startsWith("service:")) add(value.slice("service:".length));
1840
- }
1841
- for (const ref of refs) if (!document.services[ref]) throw new ConfigError({ sourceFile, configPath: `services.${name}`, stage, composition: "mesh", referencedObject: ref, reason: "Tester Compose service reference does not exist" });
1842
- }
1843
- }
1844
- function applyTesterBuildTarget(service) {
1845
- if (service.build === void 0) return;
1846
- if (typeof service.build === "string") {
1847
- service.build = { context: service.build, target: "test-e2e" };
1848
- return;
1849
- }
1850
- if (service.build && typeof service.build === "object" && !Array.isArray(service.build)) service.build = { ...service.build, target: "test-e2e" };
1851
- }
1852
- function compileMeshTester(meshDir, tester, endpointRegistry, effectiveTopLevelApps, stage, referenceContext, nameAllocator = new GeneratedComposeNameAllocator(effectiveTopLevelApps)) {
1853
- const meshPath = path.join(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);
1854
- 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" });
1855
- validateComposeResourceReferences(raw, { sourceFile: file, stage, composition: "mesh" });
1856
- validateServiceReferences(raw, file, stage);
1857
- assertComposeLifecycleAcyclic(raw.services, {
1858
- sourceFile: file,
1859
- stage,
1860
- composition: "mesh"
1861
- });
1862
- for (const [serviceName, service] of Object.entries(raw.services)) {
1863
- if (service.extends !== void 0) throw new ConfigError({ sourceFile: file, configPath: `services.${serviceName}.extends`, stage, composition: "mesh", reason: "Tester Compose extends is unsupported until effective Compose inheritance can be validated safely" });
1864
- assertNoServiceBuildContexts(service, `services.${serviceName}`, file);
1865
- }
1866
- const selectedRaw = raw.services[tester.service];
1867
- if (selectedRaw.network_mode !== void 0 && selectedRaw.network_mode !== "host") throw new ConfigError({ sourceFile: file, configPath: `services.${tester.service}.network_mode`, stage, composition: "mesh", reason: "Selected tester runner must be compatible with host networking" });
1868
- if (selectedRaw.networks !== void 0) throw new ConfigError({ sourceFile: file, configPath: `services.${tester.service}.networks`, stage, composition: "mesh", reason: "Selected host-network tester runner cannot declare Compose networks" });
1869
- if (selectedRaw.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" });
1870
- const meshCtx = referenceContext ?? { services: {}, bindings: /* @__PURE__ */ new Map(), endpoints: endpointRegistry, stage, meshJsonPath: meshPath };
1871
- const testerBuilderKeys = [EXEC_MODE_KEY, INFRA_MODE_KEY], rawRunnerEnvironment = normalizeComposeEnvironment(selectedRaw.environment, "tester runner environment");
1872
- assertNoBuilderOwnedEnvKeys(rawRunnerEnvironment, testerBuilderKeys, { sourceFile: file, configPath: `services.${tester.service}.environment`, stage, composition: "mesh" });
1873
- for (const envFile of envFilePaths(selectedRaw.env_file)) assertDotenvDoesNotDefineKeys(path.resolve(meshDir, envFile), testerBuilderKeys, { configPath: `services.${tester.service}.env_file`, stage, composition: "mesh" });
1874
- const meshTesterDotenv = path.join(meshDir, ".env.e2e-tester");
1875
- assertDotenvDoesNotDefineKeys(meshTesterDotenv, testerBuilderKeys, { configPath: ".env.e2e-tester", stage, composition: "mesh" });
1876
- const testerEnv = tester.env ?? {};
1877
- assertNoBuilderOwnedEnvKeys(testerEnv, testerBuilderKeys, { sourceFile: meshPath, configPath: "tester.env", stage, composition: "mesh" });
1878
- assertMeshTesterEnvPublic(testerEnv, meshCtx);
1879
- const ns = namespaceDependencyCompose({ dependencyKey: "mesh-tester", namespacePrefix: "mesh-tester", document: raw, allocator: nameAllocator, identityPrefix: JSON.stringify(["mesh-tester"]) });
1880
- const runner = ns.serviceNameMap.get(tester.service);
1881
- const runnerSvc = ns.document.services[runner];
1882
- applyTesterBuildTarget(runnerSvc);
1883
- runnerSvc.network_mode = "host";
1884
- delete runnerSvc.networks;
1885
- runnerSvc.env_file = appendEnvFile(runnerSvc.env_file, { path: ".env.e2e-tester", required: false });
1886
- runnerSvc.environment = { ...normalizeComposeEnvironment(runnerSvc.environment, "tester runner environment"), ...resolveMeshEnvMap(testerEnv, meshCtx, "tester.env"), EXEC_MODE: "e2e" };
1887
- const depends = normalizeComposeDependsOn(runnerSvc.depends_on);
1888
- for (const app of effectiveTopLevelApps) depends[app] = { condition: "service_healthy" };
1889
- runnerSvc.depends_on = depends;
1890
- 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 };
1891
- }
1892
-
1893
- // src/core/mesh/v2/resolveMeshAppEnvironment.ts
1894
- function resolveMeshAppEnvironmentLayers(serviceName, layers, context, laterKeys = /* @__PURE__ */ new Set()) {
1895
- const result = {};
1896
- for (const [key, layer] of selectAppEnvironmentEntries(layers, laterKeys)) {
1897
- if (layer.kind === "build-json") {
1898
- result[key] = resolveServiceBuildEnvThroughMesh(
1899
- serviceName,
1900
- { [key]: layer.values[key] },
1901
- context,
1902
- `services.${serviceName}.${layer.configPath}`
1903
- )[key];
1904
- } else {
1905
- result[key] = layer.values[key];
1906
- }
1907
- }
1908
- return result;
1909
- }
1910
- function validPort(value) {
1911
- if (!/^\d+$/.test(value)) return void 0;
1912
- const port = Number(value);
1913
- return Number.isInteger(port) && port >= 1 && port <= 65535 ? port : void 0;
1914
- }
1915
- function parsePublishedHostPort(value) {
1916
- if (value && typeof value === "object") {
1917
- const published = value.published;
1918
- if (typeof published === "number" && Number.isInteger(published)) {
1919
- return published >= 1 && published <= 65535 ? published : void 0;
1920
- }
1921
- if (typeof published === "string") return validPort(published);
1922
- return void 0;
1923
- }
1924
- if (typeof value !== "string") return void 0;
1925
- const mapping = value.replace(/\/(?:tcp|udp|sctp)$/i, "");
1926
- if (/^\d+(?:-\d+)?$/.test(mapping)) return void 0;
1927
- if (mapping.startsWith("[")) {
1928
- const close = mapping.indexOf("]");
1929
- if (close < 0 || isIP(mapping.slice(1, close)) !== 6) return void 0;
1930
- const suffix = mapping.slice(close + 1);
1931
- const match = suffix.match(/^:(\d+)(?:-\d+)?:\d+(?:-\d+)?$/);
1932
- return match ? validPort(match[1]) : void 0;
1933
- }
1934
- const parts = mapping.split(":");
1935
- if (parts.length === 2) return validPort(parts[0]);
1936
- if (parts.length >= 3) {
1937
- const hostIp = parts.slice(0, -2).join(":");
1938
- if (isIP(hostIp) === 4) return validPort(parts[parts.length - 2]);
1939
- }
1940
- return void 0;
1941
- }
1942
-
1943
- // src/utils/assertUniqueHostPortMappings.ts
1944
- function assertUniqueHostPortMappings(yamlConfig) {
1945
- const parsed = parse(yamlConfig);
1946
- const owners = /* @__PURE__ */ new Map();
1947
- for (const [serviceName, service] of Object.entries(parsed?.services ?? {})) {
1948
- for (const port of service?.ports ?? []) {
1949
- const hostPort = parsePublishedHostPort(port);
1950
- if (hostPort === void 0) continue;
1951
- const existing = owners.get(hostPort);
1952
- if (existing) {
1953
- throw new ScriptError(
1954
- `Port Collision Detected: Host port ${hostPort} is requested by both "${existing}" and "${serviceName}".`
1955
- );
1956
- }
1957
- owners.set(hostPort, serviceName);
1958
- }
1959
- }
1960
- }
1961
-
1962
- // src/core/mesh/v2/compileMeshComposition.ts
1963
- function mergeFragment(target, fragment, owner) {
1964
- for (const key of ["services", "volumes", "networks", "configs", "secrets"]) {
1965
- const incoming = fragment[key];
1966
- if (!incoming) continue;
1967
- const dest = target[key] ??= {};
1968
- for (const [name, value] of Object.entries(incoming)) {
1969
- if (name in dest) throw new ConfigError({ configPath: `${key}.${name}`, referencedObject: owner, reason: "Mesh composition name collision" });
1970
- dest[name] = value;
1971
- }
1972
- }
1973
- }
1974
- function appendPort(service, target, published) {
1975
- const ports = Array.isArray(service.ports) ? service.ports : [];
1976
- ports.push({ target, published, host_ip: PUBLIC_HOST, protocol: "tcp" });
1977
- service.ports = ports;
1978
- }
1979
- function buildMeshPortIntents(services, publication) {
1980
- const intents = [];
1981
- for (const name of Object.keys(services).sort((a, b) => a.localeCompare(b))) {
1982
- const service = services[name];
1983
- const appPublications = publication.filter((pub) => pub.ownerMeshService === name && pub.target === "app").sort((a, b) => a.endpoint.localeCompare(b.endpoint));
1984
- for (const pub of appPublications) {
1985
- const endpoint = service.effectiveBuild.app.endpoints[pub.endpoint];
1986
- intents.push({ logicalPath: pub.logicalPath, requested: endpoint.publicPort });
1987
- }
1988
- const dependencyNames = [...new Set(publication.filter((pub) => pub.ownerMeshService === name && pub.target === "dependency").map((pub) => pub.dependency))].sort((a, b) => a.localeCompare(b));
1989
- for (const dependency of dependencyNames) {
1990
- const dependencyPublications = publication.filter((pub) => pub.ownerMeshService === name && pub.target === "dependency" && pub.dependency === dependency).sort((a, b) => a.endpoint.localeCompare(b.endpoint));
1991
- for (const pub of dependencyPublications) {
1992
- const endpoint = service.effectiveBuild.dependencies[dependency].endpoints[pub.endpoint];
1993
- intents.push({ logicalPath: pub.logicalPath, requested: endpoint.publicPort });
1994
- }
1995
- }
1996
- }
1997
- return intents;
1998
- }
1999
- function ownerFor(pub, fragment) {
2000
- return pub.target === "app" ? pub.ownerMeshService : fragment.endpoints.dependencies[pub.dependency]?.[pub.endpoint]?.networkHost ?? "";
2001
- }
2002
- function setEnv(service, env) {
2003
- const current = service.environment && typeof service.environment === "object" && !Array.isArray(service.environment) ? service.environment : {};
2004
- service.environment = { ...current, ...env };
2005
- }
2006
- function attachNetworkIfCompatible(service, networkName) {
2007
- if (service.network_mode !== void 0) return;
2008
- service.networks = { ...normalizeNetworks(service.networks), [networkName]: null };
2009
- }
2010
- function compileMeshComposition(stage, meshDir, options = {}) {
2011
- const meshPath = path.join(meshDir, "mesh.json"), raw = getMeshJson(meshDir), effective = resolveMeshStage(raw, stage, meshPath), services = loadEffectiveMeshServices(meshDir, effective, stage), bindings = buildDependencyBindings(services, stage, meshPath), bindingMap = bindingsMap(bindings);
2012
- const rawName = raw.name ?? path.basename(meshDir), projectName = deriveProjectName(rawName, stage, meshDir);
2013
- const nameAllocator = new GeneratedComposeNameAllocator(["mesh", "default", ...Object.keys(services), ...Object.keys(services).map((name) => `mesh--${name}`)]);
2014
- const fragments = {};
2015
- const compose = { name: projectName, services: {}, networks: { mesh: { driver: "bridge" } } };
2016
- for (const [name, svc] of Object.entries(services).sort(([a], [b]) => a.localeCompare(b))) {
2017
- 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" });
2018
- const suppress = new Set(Object.keys(svc.dependencyBindings));
2019
- const fragment = compileServiceComposition(stage, svc.absolutePath, { nameAllocator, full: true, meshMode: true, projectNameOverride: projectName, namespacePrefix: `svc--${name}--dep--`, suppressDependencies: suppress, externalAppEnv: svc.meshEnv, deferReferenceResolution: true, appServiceName: name, composeOutputDir: meshDir, validationMode: options.validationMode });
2020
- fragments[name] = fragment;
2021
- mergeFragment(compose, fragment.compose, name);
2022
- const app = compose.services[name];
2023
- const networks = { mesh: null };
2024
- const localDeps = Object.keys(fragment.endpoints.dependencies).filter((dep) => !bindingMap.has(bindingKey(name, dep)) && Object.keys(fragment.effectiveBuild.dependencies[dep]?.endpoints ?? {}).length > 0);
2025
- if (localDeps.length) {
2026
- const privateName = `mesh--${name}`;
2027
- networks[privateName] = null;
2028
- compose.networks[privateName] = { driver: "bridge" };
2029
- for (const dep of localDeps) {
2030
- for (const ep of Object.values(fragment.endpoints.dependencies[dep] ?? {})) {
2031
- const owner = ep.networkHost;
2032
- const ownerService = compose.services[owner];
2033
- if (ownerService) {
2034
- attachNetworkIfCompatible(ownerService, privateName);
2035
- attachNetworkIfCompatible(ownerService, "mesh");
2036
- }
2037
- }
2038
- for (const generated of fragment.dependencyServiceNames?.[dep] ?? []) {
2039
- const ownerService = compose.services[generated];
2040
- attachNetworkIfCompatible(ownerService, privateName);
2041
- }
2075
+ const next = patch;
2076
+ const old = sources[name];
2077
+ if (old && next.source !== void 0 && next.source !== old.source) throw new ConfigError({ sourceFile, configPath: `${layer}.services.${name}.source`, stage: stage2, composition: "mesh", reason: `source is immutable; previous ${old.origin.configPath}.source`, value: next.source });
2078
+ if (!old && (!next.source || !next.source.trim())) throw new ConfigError({ sourceFile, configPath: `${layer}.services.${name}.source`, stage: stage2, composition: "mesh", reason: "Stage-introduced source requires source" });
2079
+ const entry = old ?? { source: next.source, publish: [], publishOrigin: originFor2(sourceFile, `${layer}.services.${name}.publish`, layer), extendsLayers: [], origin: originFor2(sourceFile, `${layer}.services.${name}`, layer) };
2080
+ if (next.publish !== void 0) {
2081
+ entry.publish = structuredClone(next.publish);
2082
+ entry.publishOrigin = originFor2(sourceFile, `${layer}.services.${name}.publish`, layer);
2083
+ }
2084
+ if (next.extends) entry.extendsLayers.push({ layer, patches: structuredClone(next.extends), origin: originFor2(sourceFile, `${layer}.services.${name}.extends`, layer) });
2085
+ sources[name] = entry;
2086
+ }
2087
+ return { name: mesh.name, services: sources, tester, testerLayers, sourceFile, projectDir: path.dirname(sourceFile), baseSources, raw: mesh };
2088
+ }
2089
+
2090
+ // src/core/mesh/applyMeshExtends.ts
2091
+ function applyMeshExtends(mesh, builds, stage2) {
2092
+ for (const [root, build] of builds) {
2093
+ const entry = mesh.services[root];
2094
+ for (const layer of entry.extendsLayers) for (const [name, patch] of Object.entries(layer.patches).sort(([a], [b]) => a.localeCompare(b))) {
2095
+ const old = build.services[name];
2096
+ const origin = { ...layer.origin, meshRoot: root, configPath: `${layer.origin.configPath}.${name}` };
2097
+ if (!old) throw new ConfigError({ sourceFile: mesh.sourceFile, configPath: origin.configPath, stage: stage2, composition: "mesh", referencedObject: `${root}.source.${name}`, reason: "extends target does not exist" });
2098
+ if (patch.compose !== void 0 && patch.compose !== old.compose) throw new ConfigError({ sourceFile: mesh.sourceFile, configPath: `${origin.configPath}.compose`, stage: stage2, composition: "mesh", reason: `compose is immutable; previous ${build.origins.get(name)?.configPath}.compose`, value: patch.compose });
2099
+ for (const [target, kind] of Object.entries(patch.requisites ?? {})) if (kind === false) {
2100
+ const exists = target.startsWith("source.") ? Boolean(build.services[target.slice(7)]) : Boolean(mesh.services[target]);
2101
+ if (!exists) throw new ConfigError({ sourceFile: mesh.sourceFile, configPath: `${origin.configPath}.requisites.${target}`, stage: stage2, composition: "mesh", referencedObject: target, reason: "Unknown requisite target" });
2042
2102
  }
2043
- }
2044
- app.networks = { ...normalizeNetworks(app.networks), ...networks };
2045
- }
2046
- const publication = resolveMeshPublication(services, bindingMap, stage, meshPath), intents = buildMeshPortIntents(services, publication), ports = allocateHostPorts(meshDir, stage, intents, Boolean(options.validationMode), { sourceFile: meshPath, composition: "mesh" });
2047
- const endpoints = { app: {}, dependencies: {} };
2048
- for (const [name, svc] of Object.entries(services)) {
2049
- endpoints.app[name] = {};
2050
- for (const [epName, ep] of Object.entries(svc.effectiveBuild.app.endpoints)) {
2051
- const host = name;
2052
- const record = { logicalPath: `${name}.app.endpoints.${epName}`, networkHost: host, networkPort: ep.port, ...ep.scheme ? { scheme: ep.scheme } : {}, effectivelyPublished: false };
2053
- endpoints.app[name][epName] = record;
2054
- }
2055
- endpoints.dependencies[name] = {};
2056
- const fragment = fragments[name];
2057
- for (const [depName, dep] of Object.entries(svc.effectiveBuild.dependencies)) {
2058
- if (bindingMap.has(bindingKey(name, depName))) continue;
2059
- endpoints.dependencies[name][depName] = {};
2060
- for (const [epName, def] of Object.entries(dep.endpoints)) {
2061
- const local = fragment.endpoints.dependencies[depName]?.[epName];
2062
- if (!local) continue;
2063
- endpoints.dependencies[name][depName][epName] = { ...local, logicalPath: `${name}.dependencies.${depName}.endpoints.${epName}`, effectivelyPublished: false };
2103
+ const canonicalPatch = structuredClone(patch);
2104
+ if (canonicalPatch.requisites) {
2105
+ canonicalPatch.requisites = Object.fromEntries(Object.entries(canonicalPatch.requisites).map(([target, kind]) => [target.startsWith("source.") ? target.slice(7) : `@mesh:${target}`, kind]));
2064
2106
  }
2065
- }
2066
- }
2067
- for (const pub of publication) {
2068
- const ep = pub.target === "app" ? endpoints.app[pub.ownerMeshService]?.[pub.endpoint] : endpoints.dependencies[pub.ownerMeshService]?.[pub.dependency]?.[pub.endpoint];
2069
- if (!ep) continue;
2070
- ep.publicHost = PUBLIC_HOST;
2071
- ep.publicPort = ports.get(pub.logicalPath);
2072
- ep.effectivelyPublished = true;
2073
- }
2074
- for (const pub of publication) {
2075
- const fragment = fragments[pub.ownerMeshService], endpoint = pub.target === "app" ? endpoints.app[pub.ownerMeshService][pub.endpoint] : endpoints.dependencies[pub.ownerMeshService][pub.dependency][pub.endpoint];
2076
- const owner = ownerFor(pub, fragment);
2077
- const service = compose.services[owner];
2078
- if (service && endpoint) appendPort(service, endpoint.networkPort, endpoint.publicPort);
2079
- }
2080
- const refContext = { services, bindings: bindingMap, endpoints, stage, meshJsonPath: meshPath };
2081
- for (const [name, fragment] of Object.entries(fragments)) {
2082
- const app = compose.services[name];
2083
- const meshEnv = resolveMeshEnvMap(fragment.externalAppEnvironment ?? {}, refContext, `services.${name}.env`);
2084
- const serviceEnv = resolveMeshAppEnvironmentLayers(name, fragment.appEnvironmentLayers, refContext, new Set(Object.keys(meshEnv)));
2085
- app.environment = { ...serviceEnv, ...meshEnv, ...fragment.builderInternalEnvironment ?? {} };
2086
- for (const [depName, depEnv] of Object.entries(fragment.dependencyEnvironments ?? {})) {
2087
- const logicalBinding = bindingMap.get(bindingKey(name, depName));
2088
- if (logicalBinding) continue;
2089
- const resolvedDep = resolveServiceBuildEnvThroughMesh(name, depEnv, refContext, `services.${name}.dependencies.${depName}.env`);
2090
- for (const serviceName of fragment.dependencyServiceNames?.[depName] ?? []) {
2091
- const service = compose.services[serviceName];
2092
- if (service) setEnv(service, resolvedDep);
2107
+ const merged = applyServiceOverlay(old, canonicalPatch);
2108
+ if (name !== "main" && name !== "tester") {
2109
+ const ordinary = merged;
2110
+ const primary = Object.values(ordinary.endpoints ?? {}).find((endpoint) => endpoint.primary);
2111
+ if (primary?.service && ordinary.service && ordinary.service !== primary.service) throw new ConfigError({ sourceFile: mesh.sourceFile, configPath: `${origin.configPath}.service`, stage: stage2, composition: "mesh", referencedObject: `${root}.source.${name}`, reason: "top-level service must equal primary endpoint owner", value: ordinary.service });
2093
2112
  }
2094
- }
2095
- }
2096
- const edges = buildMeshLifecycleEdges(services, bindingMap, stage, meshPath);
2097
- applyMeshLifecycleEdges(compose.services, edges);
2098
- for (const [name, svc] of Object.entries(services)) for (const [sourceDep, dep] of Object.entries(svc.effectiveBuild.dependencies)) {
2099
- if (bindingMap.has(bindingKey(name, sourceDep))) continue;
2100
- for (const rawTarget of dep.dependsOn) {
2101
- const targetKey = rawTarget.slice("dependencies.".length);
2102
- const provider = bindingMap.get(bindingKey(name, targetKey));
2103
- if (!provider) continue;
2104
- const localEndpoints = endpoints.dependencies[name]?.[sourceDep] ?? {};
2105
- for (const ep of Object.values(localEndpoints)) {
2106
- const localOwner = ep.networkHost, localSvc = compose.services[localOwner];
2107
- if (!localSvc) continue;
2108
- const ds = localSvc.depends_on && typeof localSvc.depends_on === "object" && !Array.isArray(localSvc.depends_on) ? localSvc.depends_on : {};
2109
- ds[provider] = { condition: "service_healthy" };
2110
- localSvc.depends_on = ds;
2111
- const net2 = localSvc.networks && typeof localSvc.networks === "object" && !Array.isArray(localSvc.networks) ? localSvc.networks : {};
2112
- net2.mesh = null;
2113
- localSvc.networks = net2;
2113
+ build.services[name] = merged;
2114
+ const env2 = build.envOrigins.get(name) ?? /* @__PURE__ */ new Map();
2115
+ for (const key of Object.keys(patch.env ?? {})) env2.set(key, { ...origin, configPath: `${origin.configPath}.env.${key}` });
2116
+ build.envOrigins.set(name, env2);
2117
+ const edges = build.requisiteOrigins.get(name) ?? /* @__PURE__ */ new Map();
2118
+ for (const [target, kind] of Object.entries(patch.requisites ?? {})) {
2119
+ const canonical = target.startsWith("source.") ? target.slice(7) : `@mesh:${target}`;
2120
+ if (kind === false) edges.delete(canonical);
2121
+ else edges.set(canonical, { ...origin, configPath: `${origin.configPath}.requisites.${target}` });
2114
2122
  }
2123
+ build.requisiteOrigins.set(name, edges);
2124
+ build.layers.push({ stage: layer.layer, services: { [name]: structuredClone(patch) }, origin });
2115
2125
  }
2116
2126
  }
2117
- const fullGraph = new Map(Object.keys(compose.services).map((name) => [name, /* @__PURE__ */ new Set()]));
2118
- for (const [serviceName, service] of Object.entries(compose.services)) {
2119
- const dependencies = service.depends_on;
2120
- if (dependencies && typeof dependencies === "object" && !Array.isArray(dependencies)) for (const target of Object.keys(dependencies)) {
2121
- if (fullGraph.has(target)) fullGraph.get(serviceName).add(target);
2122
- }
2123
- }
2124
- assertAcyclicGraph(fullGraph, { sourceFile: meshPath, stage, composition: "mesh" });
2125
- let testerServiceName;
2126
- if (stage === "e2e") {
2127
- 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? }" });
2128
- const built = raw.tester ? compileMeshTester(meshDir, raw.tester, endpoints, Object.keys(services).sort(), "e2e", refContext, nameAllocator) : void 0;
2129
- if (built) {
2130
- 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 } : {} };
2131
- mergeFragment(compose, fragment, "mesh tester");
2132
- testerServiceName = built.runnerServiceName;
2133
- }
2127
+ }
2128
+ function loadMeshSources(mesh, stage2) {
2129
+ const result = /* @__PURE__ */ new Map();
2130
+ for (const [root, entry] of Object.entries(mesh.services).sort(([a], [b]) => a.localeCompare(b))) {
2131
+ const projectDir = resolveInsideProject(mesh.projectDir, entry.source, { sourceFile: mesh.sourceFile, configPath: `${entry.origin.configPath}.source`, stage: stage2 });
2132
+ result.set(root, resolveBuildStage(getBuildJson(projectDir), stage2, path.join(projectDir, "build.json")));
2134
2133
  }
2135
- nameAllocator.assertUnique();
2136
- const yaml = stringify(compose);
2137
- assertUniqueHostPortMappings(yaml);
2138
- return { compose, effectiveMesh: effective, loadedServices: services, endpoints, projectName, ...testerServiceName ? { testerServiceName } : {} };
2134
+ return result;
2139
2135
  }
2140
2136
 
2141
- // src/core/mesh/v2/validateMeshTestStage.ts
2142
- function validateMeshTestStage(services, meshDir, meshPath, validationMode = false) {
2143
- const bindings = bindingsMap(buildDependencyBindings(services, "test", meshPath));
2144
- const publication = resolveMeshPublication(
2145
- services,
2146
- bindings,
2147
- "test",
2148
- meshPath
2149
- );
2150
- for (const pub of publication) {
2151
- if (pub.target === "dependency") {
2152
- throw new ConfigError({
2153
- sourceFile: meshPath,
2154
- configPath: `services.${pub.ownerMeshService}.publish`,
2155
- stage: "test",
2156
- composition: "mesh",
2157
- value: pub.logicalPath,
2158
- reason: "mesh.test is isolated; dependency endpoints are not materialized and cannot be published"
2159
- });
2160
- }
2161
- }
2162
- const appPublications = publication.filter((pub) => pub.target === "app").sort(
2163
- (a, b) => a.ownerMeshService.localeCompare(b.ownerMeshService) || a.endpoint.localeCompare(b.endpoint)
2164
- ).map((pub) => {
2165
- const endpoint = services[pub.ownerMeshService].effectiveBuild.app.endpoints[pub.endpoint];
2166
- return {
2167
- meshService: pub.ownerMeshService,
2168
- endpoint: pub.endpoint,
2169
- logicalPath: pub.logicalPath,
2170
- containerPort: endpoint.port,
2171
- requested: endpoint.publicPort
2172
- };
2173
- });
2174
- const allocatedPorts = /* @__PURE__ */ new Map();
2175
- for (const name of Object.keys(services).sort((a, b) => a.localeCompare(b))) {
2176
- const intents = appPublications.filter((pub) => pub.meshService === name).map((pub) => ({
2177
- logicalPath: pub.logicalPath,
2178
- requested: pub.requested
2179
- }));
2180
- const ownPorts = allocateHostPorts(
2181
- meshDir,
2182
- "test",
2183
- intents,
2184
- validationMode,
2185
- { sourceFile: meshPath, composition: "mesh" }
2186
- );
2187
- for (const [logicalPath, port] of ownPorts) allocatedPorts.set(logicalPath, port);
2188
- }
2189
- return { bindings, appPublications, allocatedPorts };
2190
- }
2191
- function applyTestAppPublications(validated, meshService, app, endpointRegistry) {
2192
- for (const publication of validated.appPublications) {
2193
- if (publication.meshService !== meshService) continue;
2194
- const published = validated.allocatedPorts.get(publication.logicalPath);
2195
- const ports = Array.isArray(app.ports) ? app.ports : [];
2196
- ports.push({
2197
- target: publication.containerPort,
2198
- published,
2199
- host_ip: PUBLIC_HOST,
2200
- protocol: "tcp"
2201
- });
2202
- app.ports = ports;
2203
- const endpoint = endpointRegistry[publication.endpoint];
2204
- if (endpoint) {
2205
- endpoint.publicHost = PUBLIC_HOST;
2206
- endpoint.publicPort = published;
2207
- endpoint.effectivelyPublished = true;
2208
- }
2209
- }
2137
+ // src/core/mesh/compileMeshComposition.ts
2138
+ function compileMeshComposition(stage2, projectDir, options = {}) {
2139
+ const root = resolveProjectDir(projectDir);
2140
+ const mesh = resolveMeshStage(getMeshJson(root), stage2, path.join(root, "mesh.json"));
2141
+ const builds = loadMeshSources(mesh, stage2);
2142
+ applyMeshExtends(mesh, builds, stage2);
2143
+ return compileGraphComposition({ stage: stage2, composition: "mesh", projectDir: root, name: mesh.name, instances: builds, mesh, validationMode: Boolean(options.validationMode) });
2210
2144
  }
2211
2145
 
2212
2146
  // src/core/mesh/checkers/checkMeshServices.ts
2213
- function checkMeshServices(mesh, meshDir, options = {}) {
2214
- const root = resolveProjectDir(meshDir), meshPath = path.join(root, "mesh.json");
2215
- const checked = /* @__PURE__ */ new Set();
2216
- const stages = options.includeTestStage ? ["dev", "prod", "test", "e2e"] : ["dev", "prod", "e2e"];
2217
- for (const stage of stages) {
2218
- const effective = resolveMeshStage(mesh, stage, meshPath);
2219
- const services = loadEffectiveMeshServices(root, effective, stage);
2220
- const testValidation = stage === "test" ? validateMeshTestStage(services, root, meshPath, true) : void 0;
2221
- for (const [name, svc] of Object.entries(services)) {
2222
- if (!checked.has(svc.absolutePath)) {
2223
- console.log(pc14.cyan(`
2224
- \u{1F50D} Checking mesh service ${name}...`));
2225
- checkInfra(svc.absolutePath);
2226
- checked.add(svc.absolutePath);
2227
- }
2228
- if (stage === "test") {
2229
- const fragment = compileServiceComposition("test", svc.absolutePath, { validationMode: true, meshMode: true, deferReferenceResolution: true });
2230
- applyTestAppPublications(testValidation, name, fragment.compose.services.app, fragment.endpoints.app);
2231
- const endpoints = { app: { [name]: fragment.endpoints.app }, dependencies: { [name]: fragment.endpoints.dependencies } };
2232
- const ctx = { services: { [name]: svc }, bindings: /* @__PURE__ */ new Map(), endpoints, stage: "test", meshJsonPath: meshPath };
2233
- for (const key of ["EXEC_MODE", "INFRA_MODE", ...Object.values(svc.effectiveBuild.app.endpoints).some((ep) => ep.primary) ? ["PORT"] : []]) {
2234
- 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" });
2235
- }
2236
- resolveMeshAppEnvironmentLayers(name, fragment.appEnvironmentLayers, ctx, new Set(Object.keys(svc.meshEnv)));
2237
- for (const [depName, depEnv] of Object.entries(fragment.dependencyEnvironments ?? {})) resolveServiceBuildEnvThroughMesh(name, depEnv, ctx, `services.${name}.dependencies.${depName}.env`);
2238
- resolveMeshEnvMap(svc.meshEnv, ctx, `services.${name}.env`);
2147
+ function checkMeshServices(mesh, meshDir, policy = checkDockerfileContract) {
2148
+ const root = resolveProjectDir(meshDir), checked = /* @__PURE__ */ new Set();
2149
+ for (const [layer, services2] of [["", mesh.services], ["dev.", mesh.dev?.services], ["prod.", mesh.prod?.services], ["e2e.", mesh.e2e?.services]]) {
2150
+ if (!services2) continue;
2151
+ for (const [name, entry] of Object.entries(services2)) {
2152
+ if (name === "tester") continue;
2153
+ const source = entry.source;
2154
+ if (!source) continue;
2155
+ const dir = resolveInsideProject(root, source, { sourceFile: path.join(root, "mesh.json"), configPath: `${layer}services.${name}.source` });
2156
+ if (!checked.has(dir)) {
2157
+ policy(getBuildJson(dir), dir);
2158
+ checked.add(dir);
2239
2159
  }
2240
2160
  }
2241
- if (stage !== "test") compileMeshComposition(stage, root, { validationMode: true, allowMissingTester: true });
2242
2161
  }
2162
+ for (const stage2 of MESH_CONFIG_STAGES) compileMeshComposition(stage2, root, { validationMode: true });
2243
2163
  }
2244
- function checkMeshTester(mesh, meshDir, options = {}) {
2245
- const root = resolveProjectDir(meshDir);
2246
- if (!mesh.tester) {
2247
- if (options.required) throw new ConfigError({ sourceFile: path.join(root, "mesh.json"), configPath: "tester", stage: "e2e", composition: "mesh", reason: "Global mesh E2E requires root tester" });
2248
- return;
2249
- }
2250
- const file = resolveInsideProject(root, mesh.tester.compose, { sourceFile: path.join(root, "mesh.json"), configPath: "tester.compose", stage: "e2e" });
2251
- loadComposeDocument(file, { sourceFile: path.join(root, "mesh.json"), configPath: "tester.compose", stage: "e2e", composition: "mesh" });
2252
- compileMeshComposition("e2e", root, { validationMode: true });
2164
+
2165
+ // src/core/mesh/checkers/checkMeshTester.ts
2166
+ function checkMeshTester(_mesh, meshDir) {
2167
+ compileMeshComposition("e2e", resolveProjectDir(meshDir), { validationMode: true });
2253
2168
  }
2254
2169
 
2255
2170
  // src/core/mesh/checkers/checkMesh.ts
2256
2171
  function checkMesh(meshDir = process.cwd(), options = {}) {
2257
2172
  const absMeshDir = resolveProjectDir(meshDir);
2258
2173
  const mesh = getMeshJson(absMeshDir);
2259
- checkMeshServices(mesh, absMeshDir, {
2260
- includeTestStage: Boolean(options.includeTestStage)
2261
- });
2262
- checkMeshTester(mesh, absMeshDir, { required: Boolean(options.requireTester) });
2174
+ checkMeshServices(mesh, absMeshDir, options.dockerfileContract);
2175
+ checkMeshTester(mesh, absMeshDir);
2263
2176
  console.log(
2264
- pc14.bold(
2265
- pc14.green("\n\u{1F389} All V2 mesh infrastructure, services, and contract checks passed!\n")
2177
+ pc9.bold(
2178
+ pc9.green("\nAll V3 mesh infrastructure, services, and contract checks passed.\n")
2266
2179
  )
2267
2180
  );
2268
2181
  }
@@ -2301,14 +2214,7 @@ Examples:
2301
2214
  }
2302
2215
  });
2303
2216
  };
2304
- function compileMeshEnvironment(stage, rawMeshDir = process.cwd(), options = {}) {
2305
- const meshDir = resolveProjectDir(rawMeshDir), compiled = compileMeshComposition(stage, meshDir), yaml = stringify(compiled.compose);
2306
- if (options.validateWithDocker !== false) {
2307
- const result = spawnSync("docker", ["compose", "--project-directory", meshDir, "-f", "-", "config", "--quiet"], { cwd: meshDir, encoding: "utf-8", input: yaml });
2308
- 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 });
2309
- }
2310
- return { yaml, ...compiled.testerServiceName ? { testerServiceName: compiled.testerServiceName } : {} };
2311
- }
2217
+ var compileEnvironment = (stage2, projectDir = process.cwd(), options = {}) => stringify(compileServiceComposition(stage2, projectDir, options).compose);
2312
2218
  var activeComposeSet = /* @__PURE__ */ new Set();
2313
2219
  var signalHandlersRegistered = false;
2314
2220
  var activeChildProcess = null;
@@ -2336,8 +2242,15 @@ function registerActiveCompose(yamlConfig, projectDir, options = {}) {
2336
2242
  ensureSignalHandlers();
2337
2243
  return () => {
2338
2244
  activeComposeSet.delete(entry);
2245
+ if (activeComposeSet.size === 0 && activeChildProcess === null) releaseSignalHandlers();
2339
2246
  };
2340
2247
  }
2248
+ function releaseSignalHandlers() {
2249
+ for (const [sig, listener] of registeredListeners) process.removeListener(sig, listener);
2250
+ registeredListeners.length = 0;
2251
+ signalHandlersRegistered = false;
2252
+ isShuttingDown = false;
2253
+ }
2341
2254
  function ensureSignalHandlers() {
2342
2255
  if (signalHandlersRegistered) return;
2343
2256
  signalHandlersRegistered = true;
@@ -2399,9 +2312,11 @@ function ensureSignalHandlers() {
2399
2312
  const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
2400
2313
  for (const sig of SIGNALS) {
2401
2314
  const listener = () => handleSignal(sig);
2315
+ registeredListeners.push([sig, listener]);
2402
2316
  process.on(sig, listener);
2403
2317
  }
2404
2318
  }
2319
+ var registeredListeners = [];
2405
2320
 
2406
2321
  // src/core/teardownCompose.ts
2407
2322
  function runSpawn(executable, args, cwd, input, silent = false, timeoutMs = 6e4) {
@@ -2463,8 +2378,8 @@ async function teardownCompose(yamlConfig, projectDir, options = {}) {
2463
2378
  }
2464
2379
  const inputData = options.projectName ? void 0 : yamlConfig;
2465
2380
  if (!removeVolumes) {
2466
- const services = yamlConfig.trim() ? anonymousVolumeServices(parse(yamlConfig)?.services ?? {}) : options.anonymousVolumeServices ?? [];
2467
- if (services.length) await runSpawn("docker", [...baseArgs, "rm", "-s", "-f", "-v", ...services], absProjectDir, inputData, true, 15e3);
2381
+ const services2 = yamlConfig.trim() ? anonymousVolumeServices(parse(yamlConfig)?.services ?? {}) : options.anonymousVolumeServices ?? [];
2382
+ if (services2.length) await runSpawn("docker", [...baseArgs, "rm", "-s", "-f", "-v", ...services2], absProjectDir, inputData, true, 15e3);
2468
2383
  }
2469
2384
  const downArgs = [...baseArgs, "down"];
2470
2385
  if (removeVolumes) {
@@ -2526,14 +2441,19 @@ function writeRunState(projectDir, state) {
2526
2441
  }
2527
2442
  const fullState = {
2528
2443
  ...state,
2444
+ version: 3,
2529
2445
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
2530
2446
  };
2531
- writeFileSync(
2532
- path.resolve(builderDir, "run.state"),
2533
- JSON.stringify(fullState, null, 2),
2534
- "utf-8"
2535
- );
2536
- } catch {
2447
+ const target = path.resolve(builderDir, "run.state");
2448
+ const temporary = path.resolve(builderDir, `run.state.${process.pid}.tmp`);
2449
+ try {
2450
+ writeFileSync(temporary, JSON.stringify(fullState, null, 2), "utf-8");
2451
+ renameSync(temporary, target);
2452
+ } finally {
2453
+ if (existsSync(temporary)) unlinkSync(temporary);
2454
+ }
2455
+ } catch (error) {
2456
+ throw new Error(`Failed to persist Builder run state in ${projectDir}`, { cause: error });
2537
2457
  }
2538
2458
  }
2539
2459
  function readRunState(projectDir) {
@@ -2541,9 +2461,15 @@ function readRunState(projectDir) {
2541
2461
  const statePath = getRunStatePath(projectDir);
2542
2462
  if (!existsSync(statePath)) return null;
2543
2463
  const content = readFileSync(statePath, "utf-8");
2544
- return JSON.parse(content);
2545
- } catch {
2546
- return null;
2464
+ const value = JSON.parse(content);
2465
+ if (!value || typeof value !== "object" || !("projectName" in value) || typeof value.projectName !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(value.projectName) || !("stage" in value) || typeof value.stage !== "string" || !("projectDir" in value) || typeof value.projectDir !== "string") {
2466
+ throw new Error("Saved run state is malformed");
2467
+ }
2468
+ if ("version" in value && value.version !== 2 && value.version !== 3) throw new Error("Saved run state version is unsupported");
2469
+ if (path.resolve(value.projectDir) !== resolveProjectDir(projectDir)) throw new Error("Saved run state belongs to another project directory");
2470
+ return value;
2471
+ } catch (error) {
2472
+ throw new Error(`Cannot read saved Builder run state in ${projectDir}; inspect .builder/run.state before cleanup`, { cause: error });
2547
2473
  }
2548
2474
  }
2549
2475
  function clearRunState(projectDir) {
@@ -2552,10 +2478,11 @@ function clearRunState(projectDir) {
2552
2478
  if (existsSync(statePath)) {
2553
2479
  unlinkSync(statePath);
2554
2480
  }
2555
- } catch {
2481
+ } catch (error) {
2482
+ throw new Error(`Failed to clear Builder run state in ${projectDir}`, { cause: error });
2556
2483
  }
2557
2484
  }
2558
- function projectNamesForServiceStage(projectDir, stage) {
2485
+ function projectNamesForServiceStage(projectDir, stage2) {
2559
2486
  const absDir = resolveProjectDir(projectDir);
2560
2487
  let rawName;
2561
2488
  try {
@@ -2564,7 +2491,7 @@ function projectNamesForServiceStage(projectDir, stage) {
2564
2491
  } catch {
2565
2492
  rawName = path.basename(absDir);
2566
2493
  }
2567
- const s = stage.toLowerCase();
2494
+ const s = stage2.toLowerCase();
2568
2495
  if (s === "dev") {
2569
2496
  return [deriveProjectName(rawName, "dev")];
2570
2497
  }
@@ -2585,66 +2512,139 @@ function projectNamesForServiceStage(projectDir, stage) {
2585
2512
  }
2586
2513
  return [deriveProjectName(rawName, s)];
2587
2514
  }
2588
- function projectNamesForMeshStage(meshDir, stage) {
2515
+ function projectNamesForMeshStage(meshDir, stage2) {
2589
2516
  const absDir = resolveProjectDir(meshDir);
2590
- let rawMeshName;
2591
- let serviceNames = [];
2517
+ let rawMeshName = path.basename(absDir);
2592
2518
  try {
2593
- const mesh = getMeshJson(absDir);
2594
- rawMeshName = mesh.name || path.basename(absDir);
2595
- serviceNames = Object.keys(resolveMeshStage(mesh, "test", path.join(absDir, "mesh.json")).services);
2519
+ rawMeshName = getMeshJson(absDir).name || rawMeshName;
2596
2520
  } catch {
2597
- rawMeshName = path.basename(absDir);
2598
2521
  }
2599
- const s = stage.toLowerCase();
2600
- if (s === "dev") {
2601
- return [deriveProjectName(rawMeshName, "dev")];
2522
+ const s = stage2.toLowerCase();
2523
+ if (s === "test" || s === "test-e2e") {
2524
+ return [deriveProjectName(rawMeshName, "e2e")];
2602
2525
  }
2603
- if (s === "prod") {
2604
- return [deriveProjectName(rawMeshName, "prod")];
2526
+ return [deriveProjectName(rawMeshName, s)];
2527
+ }
2528
+
2529
+ // src/commands/service/commands/down/handler.ts
2530
+ async function handleServiceDown(rawStage = "dev", options = {}) {
2531
+ const projectDir = resolveProjectDir(options.projectDir);
2532
+ const stage2 = (rawStage || "dev").toLowerCase();
2533
+ const validStages = ["dev", "prod", "test", "test-unit", "test-e2e"];
2534
+ if (!validStages.includes(stage2)) {
2535
+ throw new ScriptError(
2536
+ `Unknown environment stage: "${rawStage}". Supported stages: dev, prod, test, test-unit, test-e2e`
2537
+ );
2605
2538
  }
2606
- if (s === "test-e2e") {
2607
- return [deriveProjectName(rawMeshName, "e2e")];
2539
+ console.log(
2540
+ pc9.cyan(`
2541
+ \u{1F9F9} Stopping and tearing down service environment [${stage2}]...`)
2542
+ );
2543
+ if (options.debug) {
2544
+ try {
2545
+ let env2 = "dev";
2546
+ if (stage2 === "prod") env2 = "prod";
2547
+ else if (stage2 === "test" || stage2 === "test-unit") env2 = "test";
2548
+ else if (stage2 === "test-e2e") env2 = "e2e";
2549
+ const finalYamlConfig = compileEnvironment(env2, projectDir);
2550
+ console.log(
2551
+ pc9.yellow("Final merged YAML configuration:\n"),
2552
+ redactYamlSecrets(finalYamlConfig)
2553
+ );
2554
+ } catch {
2555
+ }
2608
2556
  }
2609
- if (s === "test-unit") {
2610
- return serviceNames.map((name) => `${deriveProjectName(rawMeshName, "dev")}-${name}-test`);
2557
+ const runState = readRunState(projectDir);
2558
+ if (runState && stage2 !== "test" && runState.stage !== stage2) {
2559
+ throw new ScriptError(`Saved runtime is for ${runState.stage}; use builder service down ${runState.stage} -C ${projectDir}`);
2611
2560
  }
2612
- if (s === "test") {
2613
- return [...serviceNames.map((name) => `${deriveProjectName(rawMeshName, "dev")}-${name}-test`), deriveProjectName(rawMeshName, "e2e")];
2561
+ if (runState && stage2 === "test" && !["test", "test-unit", "test-e2e"].includes(runState.stage)) {
2562
+ throw new ScriptError(`Saved runtime is for ${runState.stage}; use its matching down command`);
2614
2563
  }
2615
- return [deriveProjectName(rawMeshName, s)];
2564
+ const candidateProjects = runState?.projectName ? [runState.projectName] : projectNamesForServiceStage(projectDir, stage2);
2565
+ const uniqueProjects = Array.from(new Set(candidateProjects));
2566
+ for (const proj of uniqueProjects) {
2567
+ await teardownCompose("", projectDir, {
2568
+ projectName: proj,
2569
+ ...runState?.projectName === proj && runState.anonymousVolumeServices ? { anonymousVolumeServices: runState.anonymousVolumeServices } : {},
2570
+ removeVolumes: Boolean(options.volumes)
2571
+ });
2572
+ }
2573
+ clearRunState(projectDir);
2574
+ console.log(
2575
+ pc9.green(`\u2705 Service environment [${stage2}] stopped and removed.
2576
+ `)
2577
+ );
2578
+ return 0;
2579
+ }
2580
+ function compileMeshEnvironment(stage2, rawMeshDir = process.cwd(), options = {}) {
2581
+ const meshDir = resolveProjectDir(rawMeshDir), compiled = compileMeshComposition(stage2, meshDir, options), yaml = stringify(compiled.compose);
2582
+ if (options.validateWithDocker !== false) {
2583
+ const result = spawnSync("docker", ["compose", "--project-directory", meshDir, "-f", "-", "config", "--quiet"], { cwd: meshDir, encoding: "utf-8", input: yaml });
2584
+ 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 });
2585
+ }
2586
+ return { yaml, ...compiled.testerServiceName ? { testerServiceName: compiled.testerServiceName } : {} };
2616
2587
  }
2617
2588
 
2618
2589
  // src/commands/mesh/commands/down/handler.ts
2590
+ function rootServiceDirsForCleanup(meshDir) {
2591
+ try {
2592
+ const mesh = getMeshJson(meshDir);
2593
+ const dirs = Object.entries(mesh.services).sort(([a], [b]) => a.localeCompare(b)).filter(([name]) => name !== "tester").map(([name, service]) => resolveInsideProject(meshDir, service.source, {
2594
+ sourceFile: path.join(meshDir, "mesh.json"),
2595
+ configPath: `services.${name}.source`
2596
+ }));
2597
+ return [...new Set(dirs)];
2598
+ } catch {
2599
+ return [];
2600
+ }
2601
+ }
2619
2602
  async function handleMeshDown(rawStage = "dev", options = {}) {
2620
- const stage = (rawStage || "dev").toLowerCase();
2603
+ const stage2 = (rawStage || "dev").toLowerCase();
2621
2604
  const meshDir = resolveProjectDir(options.projectDir);
2622
- const validStages = ["dev", "prod", "test", "test-unit", "test-e2e"];
2623
- if (!validStages.includes(stage)) {
2605
+ if (stage2 === "test-unit") {
2606
+ throw new ScriptError(
2607
+ "mesh down test-unit is no longer supported because meshes have no test topology. Use builder service down test-unit -C <service> for service recovery, or builder mesh down test for the complete test pipeline."
2608
+ );
2609
+ }
2610
+ if (!MESH_COMMAND_STAGES.includes(stage2)) {
2624
2611
  throw new ScriptError(
2625
- `Unknown mesh stage: "${rawStage}". Supported stages: dev, prod, test, test-unit, test-e2e`
2612
+ `Unknown mesh stage: "${rawStage}". Supported stages: ${MESH_COMMAND_STAGES.join(", ")}`
2626
2613
  );
2627
2614
  }
2628
2615
  console.log(
2629
- pc14.cyan(`
2630
- \u{1F9F9} Stopping and tearing down global mesh environment [${stage}]...`)
2616
+ pc9.cyan(`
2617
+ \u{1F9F9} Stopping and tearing down global mesh environment [${stage2}]...`)
2631
2618
  );
2632
2619
  if (options.debug) {
2633
2620
  try {
2634
- const mode = stage === "dev" ? "dev" : stage === "test-e2e" ? "e2e" : "prod";
2621
+ const mode = stage2 === "dev" ? "dev" : stage2 === "test" || stage2 === "test-e2e" ? "e2e" : "prod";
2635
2622
  const { yaml } = compileMeshEnvironment(mode, meshDir, { validateWithDocker: false });
2636
2623
  console.log(
2637
- pc14.yellow("\nFinal merged Mesh YAML configuration:\n"),
2624
+ pc9.yellow("\nFinal merged Mesh YAML configuration:\n"),
2638
2625
  redactYamlSecrets(yaml)
2639
2626
  );
2640
2627
  } catch {
2641
2628
  }
2642
2629
  }
2643
2630
  const runState = readRunState(meshDir);
2644
- const candidateProjects = projectNamesForMeshStage(meshDir, stage);
2645
- if (runState?.projectName) {
2646
- candidateProjects.unshift(runState.projectName);
2631
+ if (runState && stage2 !== "test" && runState.stage !== stage2) {
2632
+ throw new ScriptError(`Saved runtime is for ${runState.stage}; use builder mesh down ${runState.stage} -C ${meshDir}`);
2633
+ }
2634
+ if (runState && stage2 === "test" && !["test", "test-e2e"].includes(runState.stage)) {
2635
+ throw new ScriptError(`Saved runtime is for ${runState.stage}; use its matching down command`);
2636
+ }
2637
+ if (stage2 === "test") {
2638
+ for (const serviceDir of rootServiceDirsForCleanup(meshDir)) {
2639
+ const status = await handleServiceDown("test", {
2640
+ projectDir: serviceDir,
2641
+ volumes: Boolean(options.volumes),
2642
+ debug: Boolean(options.debug)
2643
+ });
2644
+ if (status !== 0) return status;
2645
+ }
2647
2646
  }
2647
+ const candidateProjects = runState?.projectName ? [runState.projectName] : projectNamesForMeshStage(meshDir, stage2);
2648
2648
  const uniqueProjects = Array.from(new Set(candidateProjects));
2649
2649
  for (const proj of uniqueProjects) {
2650
2650
  await teardownCompose("", meshDir, {
@@ -2655,7 +2655,7 @@ async function handleMeshDown(rawStage = "dev", options = {}) {
2655
2655
  }
2656
2656
  clearRunState(meshDir);
2657
2657
  console.log(
2658
- pc14.green(`\u2705 Global mesh environment [${stage}] stopped and removed.
2658
+ pc9.green(`\u2705 Global mesh environment [${stage2}] stopped and removed.
2659
2659
  `)
2660
2660
  );
2661
2661
  return 0;
@@ -2680,8 +2680,8 @@ Examples:
2680
2680
  $ builder mesh down prod
2681
2681
  $ builder mesh down -v`
2682
2682
  ).action(
2683
- async (stage = "dev", options = {}) => {
2684
- const exitCode = await handleMeshDown(stage, {
2683
+ async (stage2 = "dev", options = {}) => {
2684
+ const exitCode = await handleMeshDown(stage2, {
2685
2685
  projectDir: options.projectDir,
2686
2686
  volumes: options.volumes,
2687
2687
  debug: options.debug
@@ -2690,38 +2690,64 @@ Examples:
2690
2690
  process.exit(exitCode);
2691
2691
  }
2692
2692
  }
2693
- );
2694
- };
2695
-
2696
- // src/core/runWithCleanup.ts
2697
- async function runWithCleanup(run, cleanup) {
2698
- let executionFailed = false;
2699
- let executionError;
2700
- try {
2701
- const status = await run();
2702
- if (status !== 0) {
2703
- executionFailed = true;
2704
- executionError = new ScriptError(`Compose execution exited with code ${status}`, { exitCode: status });
2705
- }
2706
- return status;
2707
- } catch (error) {
2708
- executionFailed = true;
2709
- executionError = error;
2710
- throw error;
2711
- } finally {
2693
+ );
2694
+ };
2695
+ function inspectImage(image, projectDir) {
2696
+ const result = spawnSync("docker", ["image", "inspect", "--format", "{{json .Config}}", image], { cwd: projectDir, encoding: "utf8" });
2697
+ if (result.error || result.status !== 0) throw new Error(`Could not inspect image ${image}: ${result.error?.message ?? result.stderr?.trim() ?? "unknown Docker error"}`);
2698
+ try {
2699
+ return { Config: JSON.parse(result.stdout) };
2700
+ } catch {
2701
+ throw new Error(`Docker returned invalid image metadata for ${image}`);
2702
+ }
2703
+ }
2704
+ function inspectRequiredHealth(checks, projectDir, inspect = inspectImage, stage2 = "prod", composition = "service") {
2705
+ for (const check of checks) {
2706
+ let metadata;
2712
2707
  try {
2713
- await cleanup();
2714
- } catch (cleanupError) {
2715
- if (executionFailed) {
2716
- throw new AggregateError(
2717
- [executionError, cleanupError],
2718
- `Compose execution failed (${errorMessage(executionError)}); cleanup also failed (${errorMessage(cleanupError)}). Saved run state was retained`
2719
- );
2720
- }
2721
- throw cleanupError;
2708
+ metadata = inspect(check.image, projectDir);
2709
+ } catch (error) {
2710
+ throw new ConfigError({ sourceFile: check.sourceFile, configPath: check.configPath, stage: stage2, composition, reason: `Required image health metadata unavailable for ${check.serviceName}: ${error instanceof Error ? error.message : String(error)}` });
2711
+ }
2712
+ const inherited = metadata.Config?.Healthcheck;
2713
+ const command = inherited && typeof inherited === "object" && !Array.isArray(inherited) ? inherited.Test : void 0;
2714
+ if (!isEnabledValidComposeHealthcheck({ test: command })) throw new ConfigError({ sourceFile: check.sourceFile, configPath: check.configPath, stage: stage2, composition, reason: `Required image healthcheck is absent or disabled for ${check.serviceName}` });
2715
+ }
2716
+ }
2717
+ function validPort(value) {
2718
+ if (!/^\d+$/.test(value)) return void 0;
2719
+ const port2 = Number(value);
2720
+ return Number.isInteger(port2) && port2 >= 1 && port2 <= 65535 ? port2 : void 0;
2721
+ }
2722
+ function parsePublishedHostPort(value) {
2723
+ if (value && typeof value === "object") {
2724
+ const published = value.published;
2725
+ if (typeof published === "number" && Number.isInteger(published)) {
2726
+ return published >= 1 && published <= 65535 ? published : void 0;
2722
2727
  }
2728
+ if (typeof published === "string") return validPort(published);
2729
+ return void 0;
2730
+ }
2731
+ if (typeof value !== "string") return void 0;
2732
+ const mapping = value.replace(/\/(?:tcp|udp|sctp)$/i, "");
2733
+ if (/^\d+(?:-\d+)?$/.test(mapping)) return void 0;
2734
+ if (mapping.startsWith("[")) {
2735
+ const close = mapping.indexOf("]");
2736
+ if (close < 0 || isIP(mapping.slice(1, close)) !== 6) return void 0;
2737
+ const suffix = mapping.slice(close + 1);
2738
+ const match = suffix.match(/^:(\d+)(?:-\d+)?:\d+(?:-\d+)?$/);
2739
+ return match ? validPort(match[1]) : void 0;
2740
+ }
2741
+ const parts = mapping.split(":");
2742
+ if (parts.length === 2) return validPort(parts[0]);
2743
+ if (parts.length >= 3) {
2744
+ const hostIp = parts.slice(0, -2).join(":");
2745
+ if (isIP(hostIp) === 4) return validPort(parts[parts.length - 2]);
2723
2746
  }
2747
+ return void 0;
2724
2748
  }
2749
+
2750
+ // src/utils/checkPortCollision.ts
2725
2751
  function extractHostPorts(yamlConfig) {
2726
2752
  const ports = [];
2727
2753
  try {
@@ -2740,7 +2766,7 @@ function extractHostPorts(yamlConfig) {
2740
2766
  }
2741
2767
  return ports;
2742
2768
  }
2743
- async function isPortInUse(port) {
2769
+ async function isPortInUse(port2) {
2744
2770
  return new Promise((resolve) => {
2745
2771
  const server = net.createServer();
2746
2772
  server.once("error", (err) => {
@@ -2753,16 +2779,46 @@ async function isPortInUse(port) {
2753
2779
  server.once("listening", () => {
2754
2780
  server.close(() => resolve(false));
2755
2781
  });
2756
- server.listen(port, "0.0.0.0");
2782
+ server.listen(port2, "0.0.0.0");
2757
2783
  });
2758
2784
  }
2759
2785
  async function checkHostPortCollisions(ports) {
2760
- for (const port of ports) {
2761
- if (port > 0 && port < 65536) {
2762
- const inUse = await isPortInUse(port);
2786
+ for (const port2 of ports) {
2787
+ if (port2 > 0 && port2 < 65536) {
2788
+ const inUse = await isPortInUse(port2);
2763
2789
  if (inUse) {
2764
- throw new ScriptError(`Host port ${port} is already in use. Builder does not remap fixed public ports.`);
2790
+ throw new ScriptError(`Host port ${port2} is already in use. Builder does not remap fixed public ports.`);
2791
+ }
2792
+ }
2793
+ }
2794
+ }
2795
+
2796
+ // src/core/runWithCleanup.ts
2797
+ async function runWithCleanup(run, cleanup) {
2798
+ let executionFailed = false;
2799
+ let executionError;
2800
+ try {
2801
+ const status = await run();
2802
+ if (status !== 0) {
2803
+ executionFailed = true;
2804
+ executionError = new ScriptError(`Compose execution exited with code ${status}`, { exitCode: status });
2805
+ }
2806
+ return status;
2807
+ } catch (error) {
2808
+ executionFailed = true;
2809
+ executionError = error;
2810
+ throw error;
2811
+ } finally {
2812
+ try {
2813
+ await cleanup();
2814
+ } catch (cleanupError) {
2815
+ if (executionFailed) {
2816
+ throw new AggregateError(
2817
+ [executionError, cleanupError],
2818
+ `Compose execution failed (${errorMessage(executionError)}); cleanup also failed (${errorMessage(cleanupError)}). Saved run state was retained`
2819
+ );
2765
2820
  }
2821
+ throw cleanupError;
2766
2822
  }
2767
2823
  }
2768
2824
  }
@@ -2774,7 +2830,7 @@ async function runCompose(args, yamlConfig, projectDir, options = {}) {
2774
2830
  return new Promise((resolve, reject) => {
2775
2831
  let child;
2776
2832
  try {
2777
- child = spawn(
2833
+ child = (options.spawnProcess ?? spawn)(
2778
2834
  "docker",
2779
2835
  ["compose", "--project-directory", absProjectDir, "-f", "-", ...args],
2780
2836
  {
@@ -2791,6 +2847,14 @@ async function runCompose(args, yamlConfig, projectDir, options = {}) {
2791
2847
  );
2792
2848
  }
2793
2849
  setActiveChild(child);
2850
+ let timer;
2851
+ if (options.timeoutMs) {
2852
+ timer = setTimeout(() => {
2853
+ child.kill("SIGTERM");
2854
+ reject(new ScriptError(`Compose readiness deadline exceeded after ${options.timeoutMs}ms`));
2855
+ }, options.timeoutMs);
2856
+ timer.unref();
2857
+ }
2794
2858
  child.stdin?.on("error", () => {
2795
2859
  });
2796
2860
  if (child.stdin) {
@@ -2798,6 +2862,7 @@ async function runCompose(args, yamlConfig, projectDir, options = {}) {
2798
2862
  child.stdin.end();
2799
2863
  }
2800
2864
  child.on("error", (err) => {
2865
+ if (timer) clearTimeout(timer);
2801
2866
  setActiveChild(null);
2802
2867
  unregister();
2803
2868
  reject(
@@ -2807,6 +2872,7 @@ async function runCompose(args, yamlConfig, projectDir, options = {}) {
2807
2872
  );
2808
2873
  });
2809
2874
  child.on("close", (code, signal) => {
2875
+ if (timer) clearTimeout(timer);
2810
2876
  setActiveChild(null);
2811
2877
  unregister();
2812
2878
  if (signal) {
@@ -2819,224 +2885,149 @@ async function runCompose(args, yamlConfig, projectDir, options = {}) {
2819
2885
  });
2820
2886
  }
2821
2887
 
2822
- // src/core/mesh/runners/runMeshDev.ts
2823
- async function runMeshDev(options = {}) {
2824
- const meshDir = resolveProjectDir(options.projectDir);
2825
- console.log(pc14.cyan(`
2826
- \u{1F680} Starting Global DEV Mesh Environment...`));
2827
- const { yaml } = compileMeshEnvironment("dev", meshDir);
2828
- const parsed = parse(yaml);
2829
- const projectName = parsed?.name || "mesh-dev";
2830
- if (options.debug) {
2831
- console.log(
2832
- pc14.yellow("\nFinal merged Mesh Dev YAML configuration:\n"),
2833
- redactYamlSecrets(yaml)
2834
- );
2835
- }
2836
- if (options.dryRun) {
2837
- console.log(pc14.green("Dry run complete. Compose was not started."));
2838
- return 0;
2839
- }
2840
- const hostPorts = extractHostPorts(yaml);
2841
- await checkHostPortCollisions(hostPorts);
2842
- writeRunState(meshDir, {
2843
- projectName,
2844
- anonymousVolumeServices: anonymousVolumeServices(parsed?.services ?? {}),
2845
- stage: "dev",
2846
- projectDir: meshDir
2847
- });
2848
- const upArgs = ["up", "--build"];
2849
- if (options.detach) {
2850
- upArgs.push("-d");
2851
- }
2852
- const status = await runWithCleanup(
2853
- () => runCompose(upArgs, yaml, meshDir, {
2854
- removeVolumes: false
2855
- }),
2856
- async () => {
2857
- if (!options.detach) {
2858
- await teardownCompose(yaml, meshDir, { removeVolumes: false });
2859
- clearRunState(meshDir);
2860
- }
2861
- }
2862
- );
2863
- return status;
2864
- }
2865
- async function runMeshProd(options = {}) {
2866
- const meshDir = resolveProjectDir(options.projectDir);
2867
- console.log(pc14.cyan(`
2868
- \u{1F3ED} Starting Global PROD Mesh Environment...`));
2869
- const { yaml } = compileMeshEnvironment("prod", meshDir);
2870
- const parsed = parse(yaml);
2871
- const projectName = parsed?.name || "mesh-prod";
2872
- if (options.debug) {
2873
- console.log(
2874
- pc14.yellow("\nFinal merged Mesh Prod YAML configuration:\n"),
2875
- redactYamlSecrets(yaml)
2876
- );
2888
+ // src/core/runners/runLongLived.ts
2889
+ async function runLongLived(stage2, projectDir, options, compile, composition, adapters = {}) {
2890
+ const compiled = compile(Boolean(options.dryRun)), yaml = stringify(compiled.compose);
2891
+ if (options.debug) console.log(redactYamlSecrets(yaml));
2892
+ if (options.dryRun) return 0;
2893
+ await (adapters.checkPorts ?? checkHostPortCollisions)(extractHostPorts(yaml));
2894
+ persistHostPortAllocations(projectDir, compiled.allocations);
2895
+ try {
2896
+ writeRunState(projectDir, { projectName: compiled.projectName, stage: stage2, configStage: stage2, workflow: stage2, composition, projectDir, runtimeServiceNames: compiled.runtimeServiceNames, testerServiceNames: [], allocatedEndpointKeys: [...compiled.allocations.keys()], anonymousVolumeServices: anonymousVolumeServices(compiled.compose.services) });
2897
+ } catch (error) {
2898
+ removeHostPortAllocations(projectDir, [...compiled.allocations.keys()]);
2899
+ throw error;
2877
2900
  }
2878
- if (options.dryRun) {
2879
- console.log(pc14.green("Dry run complete. Compose was not started."));
2880
- return 0;
2881
- }
2882
- const hostPorts = extractHostPorts(yaml);
2883
- await checkHostPortCollisions(hostPorts);
2884
- writeRunState(meshDir, {
2885
- projectName,
2886
- anonymousVolumeServices: anonymousVolumeServices(parsed?.services ?? {}),
2887
- stage: "prod",
2888
- projectDir: meshDir
2901
+ let succeeded = false;
2902
+ return runWithCleanup(async () => {
2903
+ const built = compiled.runtimeServiceNames.filter((name) => compiled.compose.services[name]?.build !== void 0);
2904
+ const images = compiled.runtimeServiceNames.filter((name) => compiled.compose.services[name]?.build === void 0 && compiled.compose.services[name]?.image !== void 0);
2905
+ if (built.length) {
2906
+ const result = await (adapters.compose ?? runCompose)(["build", ...built], yaml, projectDir, { removeVolumes: false });
2907
+ if (result !== 0) return result;
2908
+ }
2909
+ if (images.length) {
2910
+ const result = await (adapters.compose ?? runCompose)(["pull", "--policy", "missing", ...images], yaml, projectDir, { removeVolumes: false });
2911
+ if (result !== 0) return result;
2912
+ }
2913
+ inspectRequiredHealth(compiled.deferredHealthChecks, projectDir, adapters.inspectImage, stage2, composition);
2914
+ await (adapters.checkPorts ?? checkHostPortCollisions)(extractHostPorts(yaml));
2915
+ const status = await (adapters.compose ?? runCompose)(["up", "--no-build", ...options.detach ? ["--detach"] : [], ...compiled.runtimeServiceNames], yaml, projectDir, { removeVolumes: false });
2916
+ succeeded = status === 0;
2917
+ return status;
2918
+ }, async () => {
2919
+ if (options.detach && succeeded) return;
2920
+ await (adapters.teardown ?? teardownCompose)(yaml, projectDir, { removeVolumes: false });
2921
+ removeHostPortAllocations(projectDir, [...compiled.allocations.keys()]);
2922
+ clearRunState(projectDir);
2889
2923
  });
2890
- const upArgs = ["up", "--build"];
2891
- if (options.detach) {
2892
- upArgs.push("-d");
2893
- }
2894
- const status = await runWithCleanup(
2895
- () => runCompose(upArgs, yaml, meshDir, {
2896
- removeVolumes: false
2897
- }),
2898
- async () => {
2899
- if (!options.detach) {
2900
- await teardownCompose(yaml, meshDir, { removeVolumes: false });
2901
- clearRunState(meshDir);
2902
- }
2903
- }
2904
- );
2905
- return status;
2906
2924
  }
2907
- var compileEnvironment = (stage, projectDir = process.cwd(), options = {}) => stringify(compileServiceComposition(stage, projectDir, { full: Boolean(options.full), silenceWarnings: options.silenceWarnings }).compose);
2908
2925
 
2909
- // src/core/runners/runTestUnit.ts
2910
- var runTestUnit = async (options) => {
2911
- if (!options.skipBanner) {
2912
- console.log(pc14.bold(pc14.blue(`
2913
- ========================================`)));
2914
- console.log(pc14.bold(pc14.blue(`\u{1F9EA} STAGE: UNIT & ISOLATED TESTS`)));
2915
- console.log(pc14.bold(pc14.blue(`========================================
2916
- `)));
2917
- }
2918
- const finalYamlConfig = compileEnvironment("test", options.projectDir, {
2919
- silenceWarnings: options.silenceWarnings
2920
- });
2921
- const parsed = parse(finalYamlConfig);
2922
- const projectName = parsed?.name || "test";
2923
- if (options.debug) {
2924
- console.log(
2925
- pc14.yellow("Final merged YAML configuration:\n"),
2926
- redactYamlSecrets(finalYamlConfig)
2927
- );
2928
- }
2929
- if (options.dryRun) {
2930
- console.log(pc14.green("[DRY-RUN] Unit tests simulated. Compose was not started."));
2931
- return 0;
2932
- }
2933
- await checkHostPortCollisions(extractHostPorts(finalYamlConfig));
2934
- await teardownCompose(finalYamlConfig, options.projectDir, {
2935
- removeVolumes: true,
2936
- silent: true
2937
- });
2938
- writeRunState(options.projectDir, {
2939
- projectName,
2940
- stage: "test-unit",
2941
- projectDir: options.projectDir
2942
- });
2943
- const status = await runWithCleanup(
2944
- () => runCompose(
2945
- ["up", "--build", "--abort-on-container-exit", "--exit-code-from", "app"],
2946
- finalYamlConfig,
2947
- options.projectDir,
2948
- { removeVolumes: true }
2949
- ),
2950
- async () => {
2951
- await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
2952
- clearRunState(options.projectDir);
2953
- }
2954
- );
2955
- if (status === 0) {
2956
- console.log(pc14.bold(pc14.green(`
2957
- \u2705 Unit tests passed successfully.
2958
- `)));
2959
- } else {
2960
- console.error(pc14.red(`
2961
- \u274C Unit tests failed with exit code ${status}.
2962
- `));
2963
- }
2964
- return status;
2926
+ // src/core/mesh/runners/runMeshDev.ts
2927
+ var runMeshDev = (options = {}) => {
2928
+ const root = resolveProjectDir(options.projectDir);
2929
+ return runLongLived("dev", root, options, (validationMode) => compileMeshComposition("dev", root, { validationMode }), "mesh");
2965
2930
  };
2966
- var runTestE2e = async (options) => {
2967
- if (!options.skipBanner) {
2968
- console.log(pc14.bold(pc14.blue(`
2969
- ========================================`)));
2970
- console.log(pc14.bold(pc14.blue(`\u{1F6A6} STAGE: INTEGRATED E2E TESTS`)));
2971
- console.log(pc14.bold(pc14.blue(`========================================
2972
- `)));
2973
- }
2974
- const finalYamlConfig = compileEnvironment("e2e", options.projectDir, {
2975
- silenceWarnings: options.silenceWarnings
2931
+
2932
+ // src/core/mesh/runners/runMeshProd.ts
2933
+ var runMeshProd = (options = {}) => {
2934
+ const root = resolveProjectDir(options.projectDir);
2935
+ return runLongLived("prod", root, options, (validationMode) => compileMeshComposition("prod", root, { validationMode }), "mesh");
2936
+ };
2937
+ async function runTestUnit(options, adapters = {}) {
2938
+ const compiled = compileServiceComposition("test", options.projectDir, { validationMode: Boolean(options.dryRun) }), yaml = stringify(compiled.compose);
2939
+ const main = compiled.mainServiceNames.get(nodeId(void 0, "main"));
2940
+ if (options.debug) console.log(redactYamlSecrets(yaml));
2941
+ if (options.dryRun) return 0;
2942
+ await (adapters.checkPorts ?? checkHostPortCollisions)(extractHostPorts(yaml));
2943
+ await (adapters.teardown ?? teardownCompose)(yaml, options.projectDir, { removeVolumes: true, silent: true });
2944
+ persistHostPortAllocations(options.projectDir, compiled.allocations);
2945
+ writeRunState(options.projectDir, { projectName: compiled.projectName, stage: "test-unit", configStage: "test", workflow: "test", composition: "service", projectDir: options.projectDir, runtimeServiceNames: [main], testerServiceNames: [], allocatedEndpointKeys: [...compiled.allocations.keys()] });
2946
+ return runWithCleanup(() => (adapters.compose ?? runCompose)(["up", "--build", "--abort-on-container-exit", "--exit-code-from", main, main], yaml, options.projectDir, { removeVolumes: true }), async () => {
2947
+ await (adapters.teardown ?? teardownCompose)(yaml, options.projectDir, { removeVolumes: true });
2948
+ removeHostPortAllocations(options.projectDir, [...compiled.allocations.keys()]);
2949
+ clearRunState(options.projectDir);
2976
2950
  });
2977
- const parsed = parse(finalYamlConfig);
2978
- const projectName = parsed?.name || "e2e";
2979
- if (options.debug) {
2980
- console.log(
2981
- pc14.yellow("Final merged YAML configuration:\n"),
2982
- redactYamlSecrets(finalYamlConfig)
2983
- );
2984
- }
2985
- if (options.dryRun) {
2986
- console.log(pc14.green("[DRY-RUN] E2E tests simulated. Compose was not started."));
2987
- return 0;
2951
+ }
2952
+ function inspectRunnerExit(yaml, projectDir, runner) {
2953
+ const ps = spawnSync("docker", ["compose", "--project-directory", projectDir, "-f", "-", "ps", "-aq", runner], { cwd: projectDir, encoding: "utf8", input: yaml });
2954
+ const id = ps.stdout?.trim();
2955
+ if (ps.status !== 0 || !id) return void 0;
2956
+ const inspected = spawnSync("docker", ["inspect", "--format", "{{.State.ExitCode}}", id], { cwd: projectDir, encoding: "utf8" });
2957
+ const code = Number(inspected.stdout?.trim());
2958
+ return inspected.status === 0 && Number.isInteger(code) ? code : void 0;
2959
+ }
2960
+ async function runFiniteTester(compiled, projectDir, adapters = {}) {
2961
+ const compose = adapters.compose ?? runCompose;
2962
+ if (!compiled.testerServiceName) throw new Error("Finite tester composition has no selected runner");
2963
+ const yaml = stringify(compiled.compose);
2964
+ const members = [.../* @__PURE__ */ new Set([...compiled.runtimeServiceNames, ...compiled.testerServiceNames])];
2965
+ const built = members.filter((name) => compiled.compose.services[name]?.build !== void 0);
2966
+ const images = members.filter((name) => compiled.compose.services[name]?.build === void 0 && compiled.compose.services[name]?.image !== void 0);
2967
+ if (built.length) {
2968
+ const buildStatus = await compose(["build", ...built], yaml, projectDir, { removeVolumes: true });
2969
+ if (buildStatus !== 0) return buildStatus;
2970
+ }
2971
+ if (images.length) {
2972
+ const pullStatus = await compose(["pull", "--policy", "missing", ...images], yaml, projectDir, { removeVolumes: true });
2973
+ if (pullStatus !== 0) return pullStatus;
2974
+ }
2975
+ inspectRequiredHealth(compiled.deferredHealthChecks ?? [], projectDir, adapters.inspectImage, "e2e", [...compiled.graph.nodes.values()].some((node) => node.meshRoot !== void 0) ? "mesh" : "service");
2976
+ await (adapters.checkPorts ?? checkHostPortCollisions)(extractHostPorts(yaml));
2977
+ let startStatus;
2978
+ try {
2979
+ startStatus = await compose(["up", "--no-build", "--detach", ...members], yaml, projectDir, { removeVolumes: true, timeoutMs: 12e4 });
2980
+ } catch (error) {
2981
+ throw new Error(`Tester startup failed while waiting for ${members.join(", ")}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
2988
2982
  }
2989
- await checkHostPortCollisions(extractHostPorts(finalYamlConfig));
2990
- await teardownCompose(finalYamlConfig, options.projectDir, {
2991
- removeVolumes: true,
2992
- silent: true
2993
- });
2994
- writeRunState(options.projectDir, {
2995
- projectName,
2996
- stage: "test-e2e",
2997
- projectDir: options.projectDir
2998
- });
2999
- const status = await runWithCleanup(
3000
- () => runCompose(
3001
- [
3002
- "up",
3003
- "--build",
3004
- "--abort-on-container-exit",
3005
- "--exit-code-from",
3006
- "tester"
3007
- ],
3008
- finalYamlConfig,
3009
- options.projectDir,
3010
- { removeVolumes: true }
3011
- ),
3012
- async () => {
3013
- await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
3014
- clearRunState(options.projectDir);
2983
+ if (startStatus !== 0) {
2984
+ try {
2985
+ await compose(["logs", "--no-color"], yaml, projectDir, { removeVolumes: true });
2986
+ } catch (error) {
2987
+ console.warn("Could not collect startup logs", error);
3015
2988
  }
3016
- );
3017
- if (status === 0) {
3018
- console.log(pc14.bold(pc14.green(`
3019
- \u2705 E2E tests passed successfully.
3020
- `)));
3021
- } else {
3022
- console.error(pc14.red(`
3023
- \u274C E2E tests failed with exit code ${status}.
3024
- `));
2989
+ return startStatus;
2990
+ }
2991
+ const waited = await compose(["wait", compiled.testerServiceName], yaml, projectDir, { removeVolumes: true });
2992
+ const inspected = (adapters.inspectRunnerExit ?? inspectRunnerExit)(yaml, projectDir, compiled.testerServiceName);
2993
+ const status = inspected ?? (waited === 0 ? 1 : waited);
2994
+ try {
2995
+ await compose(["logs", "--no-color"], yaml, projectDir, { removeVolumes: true });
2996
+ } catch (error) {
2997
+ console.warn("Could not collect tester logs", error);
3025
2998
  }
3026
2999
  return status;
3027
- };
3000
+ }
3001
+
3002
+ // src/core/runners/runTestE2e.ts
3003
+ async function runTestE2e(options, adapters = {}) {
3004
+ const compiled = compileServiceComposition("e2e", options.projectDir, { validationMode: Boolean(options.dryRun) }), yaml = stringify(compiled.compose);
3005
+ if (options.debug) console.log(redactYamlSecrets(yaml));
3006
+ if (options.dryRun) return 0;
3007
+ await (adapters.checkPorts ?? checkHostPortCollisions)(extractHostPorts(yaml));
3008
+ await (adapters.teardown ?? teardownCompose)(yaml, options.projectDir, { removeVolumes: true, silent: true });
3009
+ persistHostPortAllocations(options.projectDir, compiled.allocations);
3010
+ writeRunState(options.projectDir, { projectName: compiled.projectName, stage: "test-e2e", configStage: "e2e", workflow: "test", composition: "service", projectDir: options.projectDir, runtimeServiceNames: compiled.runtimeServiceNames, testerServiceNames: compiled.testerServiceNames, allocatedEndpointKeys: [...compiled.allocations.keys()] });
3011
+ return runWithCleanup(() => runFiniteTester(compiled, options.projectDir, adapters.finite), async () => {
3012
+ await (adapters.teardown ?? teardownCompose)(yaml, options.projectDir, { removeVolumes: true });
3013
+ removeHostPortAllocations(options.projectDir, [...compiled.allocations.keys()]);
3014
+ clearRunState(options.projectDir);
3015
+ });
3016
+ }
3028
3017
 
3029
3018
  // src/core/runners/runTest.ts
3030
- var runTest = async (options) => {
3031
- console.log(pc14.bold(pc14.blue(`
3019
+ var runTest = async (options, adapters = {}) => {
3020
+ compileServiceComposition("test", options.projectDir, { validationMode: true });
3021
+ compileServiceComposition("e2e", options.projectDir, { validationMode: true });
3022
+ console.log(pc9.bold(pc9.blue(`
3032
3023
  ========================================`)));
3033
- console.log(pc14.bold(pc14.blue(`\u{1F9EA} [1/2] STAGE: UNIT & ISOLATED TESTS`)));
3034
- console.log(pc14.bold(pc14.blue(`========================================
3024
+ console.log(pc9.bold(pc9.blue(`\u{1F9EA} [1/2] STAGE: UNIT & ISOLATED TESTS`)));
3025
+ console.log(pc9.bold(pc9.blue(`========================================
3035
3026
  `)));
3036
- const unitStatus = await runTestUnit({ ...options, skipBanner: true });
3027
+ const unitStatus = await runTestUnit({ ...options, skipBanner: true }, adapters.unit);
3037
3028
  if (unitStatus !== 0) {
3038
3029
  console.error(
3039
- pc14.red(
3030
+ pc9.red(
3040
3031
  `
3041
3032
  \u274C [1/2] Unit tests failed with exit code ${unitStatus}. Aborting E2E tests.
3042
3033
  `
@@ -3045,29 +3036,29 @@ var runTest = async (options) => {
3045
3036
  return unitStatus;
3046
3037
  }
3047
3038
  console.log(
3048
- pc14.bold(pc14.green(`
3039
+ pc9.bold(pc9.green(`
3049
3040
  \u2705 [1/2] Unit tests passed successfully.
3050
3041
  `))
3051
3042
  );
3052
- console.log(pc14.bold(pc14.blue(`========================================`)));
3053
- console.log(pc14.bold(pc14.blue(`\u{1F6A6} [2/2] STAGE: INTEGRATED E2E TESTS`)));
3054
- console.log(pc14.bold(pc14.blue(`========================================
3043
+ console.log(pc9.bold(pc9.blue(`========================================`)));
3044
+ console.log(pc9.bold(pc9.blue(`\u{1F6A6} [2/2] STAGE: INTEGRATED E2E TESTS`)));
3045
+ console.log(pc9.bold(pc9.blue(`========================================
3055
3046
  `)));
3056
- const e2eStatus = await runTestE2e({ ...options, skipBanner: true });
3047
+ const e2eStatus = await runTestE2e({ ...options, skipBanner: true }, adapters.e2e);
3057
3048
  if (e2eStatus !== 0) {
3058
3049
  console.error(
3059
- pc14.red(`
3050
+ pc9.red(`
3060
3051
  \u274C [2/2] E2E tests failed with exit code ${e2eStatus}.
3061
3052
  `)
3062
3053
  );
3063
3054
  return e2eStatus;
3064
3055
  }
3065
- console.log(pc14.bold(pc14.green(`
3056
+ console.log(pc9.bold(pc9.green(`
3066
3057
  \u2705 [2/2] E2E tests passed successfully.
3067
3058
  `)));
3068
3059
  console.log(
3069
- pc14.bold(
3070
- pc14.green(`\u{1F389} All test stages (unit + e2e) completed successfully!
3060
+ pc9.bold(
3061
+ pc9.green(`\u{1F389} All test stages (unit + e2e) completed successfully!
3071
3062
  `)
3072
3063
  )
3073
3064
  );
@@ -3075,120 +3066,81 @@ var runTest = async (options) => {
3075
3066
  };
3076
3067
 
3077
3068
  // src/core/mesh/runners/runMeshServiceTests.ts
3078
- async function runMeshServiceTests(options = {}) {
3069
+ async function runMeshServiceTests(options = {}, runtime = {}) {
3079
3070
  const meshDir = resolveProjectDir(options.projectDir), meshPath = path.join(meshDir, "mesh.json"), mesh = getMeshJson(meshDir);
3080
- const rootServices = Object.entries(mesh.services).sort(([left], [right]) => left.localeCompare(right));
3071
+ const rootServices = Object.entries(mesh.services).filter(([name]) => name !== "tester").sort(([left], [right]) => left.localeCompare(right));
3081
3072
  for (const [serviceName, service] of rootServices) {
3082
- const serviceDir = resolveInsideProject(meshDir, service.path, { sourceFile: meshPath, configPath: `services.${serviceName}.path`, stage: "test" });
3083
- console.log(pc14.bold(pc14.cyan(`
3073
+ const serviceDir = resolveInsideProject(meshDir, service.source, { sourceFile: meshPath, configPath: `services.${serviceName}.source`, stage: "test" });
3074
+ console.log(pc9.bold(pc9.cyan(`
3084
3075
  -> Running full standalone test lifecycle for [${serviceName}]
3085
3076
  `)));
3086
- const status = await runTest({ projectDir: serviceDir, debug: Boolean(options.debug), detach: false, skipBanner: true, silenceWarnings: false, ...options.dryRun !== void 0 ? { dryRun: options.dryRun } : {} });
3077
+ const status = await runTest({ projectDir: serviceDir, debug: Boolean(options.debug), detach: false, skipBanner: true, silenceWarnings: false, ...options.dryRun !== void 0 ? { dryRun: options.dryRun } : {} }, runtime);
3087
3078
  if (status !== 0) return status;
3088
3079
  }
3089
3080
  return 0;
3090
3081
  }
3091
- async function runMeshTestE2e(options = {}) {
3092
- const meshDir = resolveProjectDir(options.projectDir), mesh = getMeshJson(meshDir);
3093
- if (!mesh.tester) throw new ScriptError("Global mesh E2E requires root mesh.json.tester { compose, service, env? }");
3094
- const { yaml, testerServiceName } = compileMeshEnvironment("e2e", meshDir);
3095
- if (!testerServiceName) throw new ScriptError("Global mesh E2E tester runner could not be compiled.");
3096
- if (options.debug) console.log(pc14.yellow("\nFinal global mesh E2E YAML configuration:\n"), redactYamlSecrets(yaml));
3097
- if (options.dryRun) {
3098
- console.log(pc14.green("[DRY-RUN] Global mesh E2E compiled; Compose was not started."));
3099
- return 0;
3100
- }
3101
- await checkHostPortCollisions(extractHostPorts(yaml));
3102
- const projectName = parse(yaml)?.name || "mesh-e2e";
3103
- await teardownCompose(yaml, meshDir, { removeVolumes: true, silent: true });
3104
- writeRunState(meshDir, { projectName, stage: "test-e2e", projectDir: meshDir });
3105
- const status = await runWithCleanup(() => runCompose(["up", "--build", "--abort-on-container-exit", "--exit-code-from", testerServiceName], yaml, meshDir, { removeVolumes: true }), async () => {
3106
- await teardownCompose(yaml, meshDir, { removeVolumes: true });
3107
- clearRunState(meshDir);
3082
+ async function runMeshTestE2e(options = {}, adapters = {}) {
3083
+ const root = resolveProjectDir(options.projectDir), compiled = compileMeshComposition("e2e", root, { validationMode: Boolean(options.dryRun) }), yaml = stringify(compiled.compose);
3084
+ if (options.debug) console.log(redactYamlSecrets(yaml));
3085
+ if (options.dryRun) return 0;
3086
+ await (adapters.checkPorts ?? checkHostPortCollisions)(extractHostPorts(yaml));
3087
+ await (adapters.teardown ?? teardownCompose)(yaml, root, { removeVolumes: true, silent: true });
3088
+ persistHostPortAllocations(root, compiled.allocations);
3089
+ writeRunState(root, { projectName: compiled.projectName, stage: "test-e2e", configStage: "e2e", workflow: "test", composition: "mesh", projectDir: root, runtimeServiceNames: compiled.runtimeServiceNames, testerServiceNames: compiled.testerServiceNames, allocatedEndpointKeys: [...compiled.allocations.keys()] });
3090
+ return runWithCleanup(() => runFiniteTester(compiled, root, adapters.finite), async () => {
3091
+ await (adapters.teardown ?? teardownCompose)(yaml, root, { removeVolumes: true });
3092
+ removeHostPortAllocations(root, [...compiled.allocations.keys()]);
3093
+ clearRunState(root);
3108
3094
  });
3109
- return status;
3110
3095
  }
3111
3096
 
3112
3097
  // src/core/mesh/runners/runMeshTest.ts
3113
- async function runMeshTest(options = {}) {
3114
- console.log(pc14.bold(pc14.blue("\n========================================\nMESH TEST PIPELINE\n========================================\n")));
3115
- console.log(pc14.bold(pc14.blue("[1/2] ROOT SERVICE TEST LIFECYCLES")));
3116
- const serviceStatus = await runMeshServiceTests(options);
3098
+ async function runMeshTest(options = {}, runtime = {}) {
3099
+ compileMeshComposition("e2e", resolveProjectDir(options.projectDir), { validationMode: true });
3100
+ console.log(pc9.bold(pc9.blue("\n========================================\nMESH TEST PIPELINE\n========================================\n")));
3101
+ console.log(pc9.bold(pc9.blue("[1/2] ROOT SERVICE TEST LIFECYCLES")));
3102
+ const serviceStatus = await runMeshServiceTests(options, runtime.source);
3117
3103
  if (serviceStatus !== 0) return serviceStatus;
3118
- console.log(pc14.bold(pc14.blue("[2/2] GLOBAL MESH E2E")));
3119
- return runMeshTestE2e(options);
3120
- }
3121
- async function runMeshTestUnit(options = {}) {
3122
- const meshDir = resolveProjectDir(options.projectDir), meshPath = path.join(meshDir, "mesh.json"), raw = getMeshJson(meshDir), effective = resolveMeshStage(raw, "test", meshPath), services = loadEffectiveMeshServices(meshDir, effective, "test"), validated = validateMeshTestStage(services, meshDir, meshPath, Boolean(options.dryRun));
3123
- console.log(pc14.bold(pc14.blue("\nEXPLICIT MESH TEST-STAGE (UNIT/ISOLATED)\n")));
3124
- for (const [name, svc] of Object.entries(services).sort(([a], [b]) => a.localeCompare(b))) {
3125
- console.log(pc14.cyan(`-> Running isolated unit tests for [${name}]`));
3126
- const compiled = compileServiceComposition("test", svc.absolutePath, { meshMode: true, full: false, externalAppEnv: {}, deferReferenceResolution: true, appServiceName: "app" });
3127
- const app = compiled.compose.services.app;
3128
- applyTestAppPublications(validated, name, app, compiled.endpoints.app);
3129
- const endpoints = { app: { [name]: compiled.endpoints.app }, dependencies: { [name]: compiled.endpoints.dependencies } };
3130
- const refCtx = { services: { [name]: svc }, bindings: /* @__PURE__ */ new Map(), endpoints, stage: "test", meshJsonPath: meshPath };
3131
- const env = svc.meshEnv;
3132
- 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" });
3133
- const resolvedBuild = resolveMeshAppEnvironmentLayers(name, compiled.appEnvironmentLayers, refCtx, new Set(Object.keys(svc.meshEnv)));
3134
- for (const [depName, depEnv] of Object.entries(compiled.dependencyEnvironments ?? {})) resolveServiceBuildEnvThroughMesh(name, depEnv, refCtx, `services.${name}.dependencies.${depName}.env`);
3135
- const resolved = resolveMeshEnvMap(env, refCtx, `services.${name}.env`);
3136
- app.environment = { ...resolvedBuild, ...resolved, ...compiled.builderInternalEnvironment ?? {} };
3137
- const projectName = `${deriveProjectName(raw.name ?? path.basename(meshDir), "dev")}-${name}-test`;
3138
- compiled.compose.name = projectName;
3139
- const yaml = stringify(compiled.compose);
3140
- if (options.debug) console.log(redactYamlSecrets(yaml));
3141
- if (options.dryRun) {
3142
- console.log(pc14.green(`[DRY-RUN] Unit tests for ${name} compiled.`));
3143
- continue;
3144
- }
3145
- await teardownCompose(yaml, svc.absolutePath, { removeVolumes: true, silent: true });
3146
- writeRunState(svc.absolutePath, { projectName, stage: "test-unit", projectDir: svc.absolutePath });
3147
- const status = await runWithCleanup(() => runCompose(["up", "--build", "--abort-on-container-exit", "--exit-code-from", "app"], yaml, svc.absolutePath, { removeVolumes: true }), async () => {
3148
- await teardownCompose(yaml, svc.absolutePath, { removeVolumes: true });
3149
- clearRunState(svc.absolutePath);
3150
- });
3151
- if (status !== 0) return status;
3152
- }
3153
- return 0;
3104
+ console.log(pc9.bold(pc9.blue("[2/2] GLOBAL MESH E2E")));
3105
+ return runMeshTestE2e(options, runtime.global);
3154
3106
  }
3155
3107
 
3156
3108
  // src/commands/mesh/commands/up/handler.ts
3157
3109
  async function handleMeshUp(rawStage = "dev", options = {}) {
3158
- const stage = (rawStage || "dev").toLowerCase();
3110
+ const stage2 = (rawStage || "dev").toLowerCase();
3111
+ if (["test-unit", "test-e2e", "e2e"].includes(stage2)) {
3112
+ throw new ScriptError(
3113
+ `mesh up ${stage2} is not a public target. Use builder service up test-unit -C <service> for isolated tests, or builder mesh up test for the complete test pipeline.`
3114
+ );
3115
+ }
3116
+ if (!MESH_COMMAND_STAGES.includes(stage2)) {
3117
+ throw new ScriptError(
3118
+ `Unknown mesh stage: "${rawStage}". Supported stages: ${MESH_COMMAND_STAGES.join(", ")}`
3119
+ );
3120
+ }
3159
3121
  const projectDir = resolveProjectDir(options.projectDir);
3160
- const runOptions = {
3161
- ...options,
3162
- projectDir
3163
- };
3164
- if (["dev", "prod", "test-unit", "test-e2e", "test"].includes(stage) && !options.skipChecks) {
3122
+ if (options.detach && stage2 === "test") throw new ScriptError("--detach applies only to mesh dev/prod; mesh test is finite");
3123
+ const runOptions = { ...options, projectDir };
3124
+ if (!options.skipChecks && !options.dryRun) {
3165
3125
  checkMesh(projectDir, {
3166
- requireTester: stage === "test-e2e" || stage === "test",
3167
- includeTestStage: stage === "test-unit"
3168
- });
3126
+ });
3169
3127
  }
3170
- switch (stage) {
3128
+ switch (stage2) {
3171
3129
  case "dev":
3172
- return await runMeshDev(runOptions);
3130
+ return runMeshDev(runOptions);
3173
3131
  case "prod":
3174
- return await runMeshProd(runOptions);
3175
- case "test-unit":
3176
- return await runMeshTestUnit(runOptions);
3177
- case "test-e2e":
3178
- return await runMeshTestE2e(runOptions);
3132
+ return runMeshProd(runOptions);
3179
3133
  case "test":
3180
- return await runMeshTest(runOptions);
3134
+ return runMeshTest(runOptions);
3181
3135
  default:
3182
- throw new ScriptError(
3183
- `Unknown mesh stage: "${rawStage}". Supported stages: dev, prod, test, test-unit, test-e2e`
3184
- );
3136
+ throw new ScriptError(`Unsupported mesh command: ${stage2}`);
3185
3137
  }
3186
3138
  }
3187
3139
 
3188
3140
  // src/commands/mesh/commands/up/command.ts
3189
3141
  var registerMeshUpCommand = (cmd) => {
3190
3142
  cmd.command("up [stage]").description(
3191
- "Start, build, or test the mesh environment (dev, prod, test, test-unit, test-e2e)"
3143
+ "Start or test the mesh environment (dev, prod, test)"
3192
3144
  ).option("--debug", "Output the merged Docker Compose YAML configuration").option("-d, --detach", "Run containers in the background").option(
3193
3145
  "--dry-run",
3194
3146
  "Compile configuration and validate checks without starting containers"
@@ -3208,15 +3160,12 @@ Examples:
3208
3160
  $ builder mesh up dev
3209
3161
  $ builder mesh up prod
3210
3162
  $ builder mesh up test
3211
- $ builder mesh up test-unit
3212
- $ builder mesh up test-e2e
3213
-
3214
- JSON overlays: test-unit uses mesh/build test; test-e2e uses mesh/build e2e.
3163
+ Mesh JSON overlays: dev, prod, e2e. The test workflow uses base -> prod -> e2e internally.
3215
3164
  The test command runs each root service test lifecycle (unit, then service E2E) before global E2E.
3216
- The explicit test-unit stage exercises mesh.json.test overlays only.`
3165
+ For a service\u2019s isolated tests: builder service up test-unit -C <service>.`
3217
3166
  ).action(
3218
- async (stage = "dev", options = {}) => {
3219
- const exitCode = await handleMeshUp(stage, {
3167
+ async (stage2 = "dev", options = {}) => {
3168
+ const exitCode = await handleMeshUp(stage2, {
3220
3169
  projectDir: options.projectDir,
3221
3170
  debug: options.debug,
3222
3171
  detach: options.detach,
@@ -3233,102 +3182,44 @@ The explicit test-unit stage exercises mesh.json.test overlays only.`
3233
3182
  // src/commands/mesh/command.ts
3234
3183
  var registerMeshCommand = (program) => {
3235
3184
  const meshCmd = program.command("mesh").description("Manage and orchestrate multi-service mesh environments");
3236
- meshCmd.hook("preAction", () => {
3185
+ meshCmd.hook("preAction", (_thisCommand, actionCommand) => {
3186
+ if (actionCommand.name() === "up") {
3187
+ const options = actionCommand.opts(), stage2 = actionCommand.args[0]?.toLowerCase();
3188
+ if (options.dryRun || stage2 && !["dev", "prod", "test"].includes(stage2)) return;
3189
+ }
3237
3190
  checkDependencies();
3238
3191
  });
3239
3192
  registerMeshUpCommand(meshCmd);
3240
3193
  registerMeshDownCommand(meshCmd);
3241
3194
  registerMeshCheckCommand(meshCmd);
3242
3195
  };
3243
- async function handlePrune(options = {}) {
3244
- console.log(pc14.cyan("\n\u{1F9F9} Pruning stopped Compose containers and unused networks..."));
3245
- const rmContainers = spawnSync("docker", ["container", "prune", "-f"], {
3246
- stdio: "inherit",
3247
- encoding: "utf-8"
3248
- });
3249
- if (rmContainers.error) {
3250
- throw new ScriptError(`Failed to prune containers: ${rmContainers.error.message}`, {
3251
- cause: rmContainers.error
3252
- });
3253
- }
3254
- const rmNetworks = spawnSync("docker", ["network", "prune", "-f"], {
3255
- stdio: "inherit",
3256
- encoding: "utf-8"
3257
- });
3258
- if (rmNetworks.error) {
3259
- throw new ScriptError(`Failed to prune networks: ${rmNetworks.error.message}`, {
3260
- cause: rmNetworks.error
3261
- });
3262
- }
3263
- if (options.volumes) {
3264
- console.log(pc14.cyan("\u{1F9F9} Pruning dangling volumes..."));
3265
- spawnSync("docker", ["volume", "prune", "-f"], {
3266
- stdio: "inherit",
3267
- encoding: "utf-8"
3268
- });
3196
+ async function handlePrune(options = {}, spawn3 = spawnSync) {
3197
+ const filter = `label=${BUILDER_OWNER_LABEL}=true`;
3198
+ for (const kind of ["container", "network", ...options.volumes ? ["volume"] : []]) {
3199
+ const args = [kind, "prune", "-f", "--filter", filter];
3200
+ if (options.dryRun) {
3201
+ console.log(`docker ${args.join(" ")}`);
3202
+ continue;
3203
+ }
3204
+ const result = spawn3("docker", args, { stdio: "inherit", encoding: "utf-8" });
3205
+ if (result.error || result.status !== 0) throw new ScriptError(`Failed to prune Builder ${kind}s: ${result.error?.message ?? result.stderr ?? `exit code ${result.status}`}`);
3269
3206
  }
3270
- console.log(pc14.green("\u2705 Docker environment pruned successfully.\n"));
3207
+ if (!options.dryRun) console.log(pc9.green("Builder-owned Docker resources pruned."));
3271
3208
  return 0;
3272
3209
  }
3273
3210
 
3274
3211
  // src/commands/prune/command.ts
3275
3212
  var registerPruneCommand = (cmd) => {
3276
- cmd.command("prune").description("Remove stopped containers, unused networks, and dangling resources").option("-v, --volumes", "Also prune dangling anonymous volumes").action(async (options = {}) => {
3213
+ cmd.command("prune").description("Remove stopped Builder-owned containers, networks, and dangling resources").option("-v, --volumes", "Also prune dangling anonymous volumes").option("--dry-run", "Print scoped prune commands without running Docker").action(async (options = {}) => {
3277
3214
  const exitCode = await handlePrune({
3278
- volumes: Boolean(options.volumes)
3215
+ volumes: Boolean(options.volumes),
3216
+ dryRun: Boolean(options.dryRun)
3279
3217
  });
3280
3218
  if (exitCode !== 0) {
3281
3219
  process.exit(exitCode);
3282
3220
  }
3283
3221
  });
3284
3222
  };
3285
- async function handleServiceDown(rawStage = "dev", options = {}) {
3286
- const projectDir = resolveProjectDir(options.projectDir);
3287
- const stage = (rawStage || "dev").toLowerCase();
3288
- const validStages = ["dev", "prod", "test", "test-unit", "test-e2e"];
3289
- if (!validStages.includes(stage)) {
3290
- throw new ScriptError(
3291
- `Unknown environment stage: "${rawStage}". Supported stages: dev, prod, test, test-unit, test-e2e`
3292
- );
3293
- }
3294
- console.log(
3295
- pc14.cyan(`
3296
- \u{1F9F9} Stopping and tearing down service environment [${stage}]...`)
3297
- );
3298
- if (options.debug) {
3299
- try {
3300
- let env = "dev";
3301
- if (stage === "prod") env = "prod";
3302
- else if (stage === "test" || stage === "test-unit") env = "test";
3303
- else if (stage === "test-e2e") env = "e2e";
3304
- const finalYamlConfig = compileEnvironment(env, projectDir);
3305
- console.log(
3306
- pc14.yellow("Final merged YAML configuration:\n"),
3307
- redactYamlSecrets(finalYamlConfig)
3308
- );
3309
- } catch {
3310
- }
3311
- }
3312
- const runState = readRunState(projectDir);
3313
- const candidateProjects = projectNamesForServiceStage(projectDir, stage);
3314
- if (runState?.projectName) {
3315
- candidateProjects.unshift(runState.projectName);
3316
- }
3317
- const uniqueProjects = Array.from(new Set(candidateProjects));
3318
- for (const proj of uniqueProjects) {
3319
- await teardownCompose("", projectDir, {
3320
- projectName: proj,
3321
- ...runState?.projectName === proj && runState.anonymousVolumeServices ? { anonymousVolumeServices: runState.anonymousVolumeServices } : {},
3322
- removeVolumes: Boolean(options.volumes)
3323
- });
3324
- }
3325
- clearRunState(projectDir);
3326
- console.log(
3327
- pc14.green(`\u2705 Service environment [${stage}] stopped and removed.
3328
- `)
3329
- );
3330
- return 0;
3331
- }
3332
3223
 
3333
3224
  // src/commands/service/commands/down/command.ts
3334
3225
  var registerDownCommand = (cmd) => {
@@ -3349,8 +3240,8 @@ Examples:
3349
3240
  $ builder service down prod
3350
3241
  $ builder service down -v`
3351
3242
  ).action(
3352
- async (stage = "dev", options = {}) => {
3353
- const exitCode = await handleServiceDown(stage, {
3243
+ async (stage2 = "dev", options = {}) => {
3244
+ const exitCode = await handleServiceDown(stage2, {
3354
3245
  projectDir: options.projectDir,
3355
3246
  volumes: options.volumes,
3356
3247
  debug: options.debug
@@ -3361,105 +3252,20 @@ Examples:
3361
3252
  }
3362
3253
  );
3363
3254
  };
3364
- var runDev = async (options) => {
3365
- console.log(
3366
- pc14.cyan(
3367
- options.full ? `\u{1F680} Starting DEV environment (full / integrated)...` : `\u{1F680} Starting DEV environment...`
3368
- )
3369
- );
3370
- const finalYamlConfig = compileEnvironment("dev", options.projectDir, {
3371
- silenceWarnings: options.silenceWarnings,
3372
- full: options.full
3373
- });
3374
- const parsed = parse(finalYamlConfig);
3375
- const projectName = parsed?.name || "dev";
3376
- if (options.debug) {
3377
- console.log(
3378
- pc14.yellow("Final merged YAML configuration:\n"),
3379
- redactYamlSecrets(finalYamlConfig)
3380
- );
3381
- }
3382
- if (options.dryRun) {
3383
- console.log(pc14.green("Dry run complete. Compose was not started."));
3384
- return 0;
3385
- }
3386
- const hostPorts = extractHostPorts(finalYamlConfig);
3387
- await checkHostPortCollisions(hostPorts);
3388
- writeRunState(options.projectDir, {
3389
- projectName,
3390
- anonymousVolumeServices: anonymousVolumeServices(parsed?.services ?? {}),
3391
- stage: "dev",
3392
- projectDir: options.projectDir
3393
- });
3394
- const upArgs = ["up", "--build"];
3395
- if (options.detach) {
3396
- upArgs.push("-d");
3397
- }
3398
- const status = await runWithCleanup(
3399
- () => runCompose(upArgs, finalYamlConfig, options.projectDir, {
3400
- removeVolumes: false
3401
- }),
3402
- async () => {
3403
- if (!options.detach) {
3404
- await teardownCompose(finalYamlConfig, options.projectDir, {
3405
- removeVolumes: false
3406
- });
3407
- clearRunState(options.projectDir);
3408
- }
3409
- }
3410
- );
3411
- return status;
3412
- };
3413
- var runProd = async (options) => {
3414
- console.log(pc14.cyan(`\u{1F3ED} Starting PROD environment...`));
3415
- const finalYamlConfig = compileEnvironment("prod", options.projectDir, {
3416
- silenceWarnings: options.silenceWarnings
3417
- });
3418
- const parsed = parse(finalYamlConfig);
3419
- const projectName = parsed?.name || "prod";
3420
- if (options.debug) {
3421
- console.log(
3422
- pc14.yellow("Final merged YAML configuration:\n"),
3423
- redactYamlSecrets(finalYamlConfig)
3424
- );
3425
- }
3426
- if (options.dryRun) {
3427
- console.log(pc14.green("Dry run complete. Compose was not started."));
3428
- return 0;
3429
- }
3430
- const hostPorts = extractHostPorts(finalYamlConfig);
3431
- await checkHostPortCollisions(hostPorts);
3432
- writeRunState(options.projectDir, {
3433
- projectName,
3434
- anonymousVolumeServices: anonymousVolumeServices(parsed?.services ?? {}),
3435
- stage: "prod",
3436
- projectDir: options.projectDir
3437
- });
3438
- const upArgs = ["up", "--build"];
3439
- if (options.detach) {
3440
- upArgs.push("-d");
3441
- }
3442
- const status = await runWithCleanup(
3443
- () => runCompose(upArgs, finalYamlConfig, options.projectDir, {
3444
- removeVolumes: false
3445
- }),
3446
- async () => {
3447
- if (!options.detach) {
3448
- await teardownCompose(finalYamlConfig, options.projectDir, {
3449
- removeVolumes: false
3450
- });
3451
- clearRunState(options.projectDir);
3452
- }
3453
- }
3454
- );
3455
- return status;
3456
- };
3255
+
3256
+ // src/core/runners/runDev.ts
3257
+ var runDev = (options) => runLongLived("dev", options.projectDir, options, (validationMode) => compileServiceComposition("dev", options.projectDir, { full: options.full, validationMode }), "service");
3258
+
3259
+ // src/core/runners/runProd.ts
3260
+ var runProd = (options) => runLongLived("prod", options.projectDir, options, (validationMode) => compileServiceComposition("prod", options.projectDir, { validationMode }), "service");
3457
3261
 
3458
3262
  // src/commands/service/commands/up/handler.ts
3459
3263
  async function handleServiceUp(rawStage, options = {}) {
3460
3264
  const projectDir = resolveProjectDir(options.projectDir);
3461
- const stage = (rawStage || "dev").toLowerCase();
3265
+ const stage2 = (rawStage || "dev").toLowerCase();
3462
3266
  const isFull = Boolean(options.full);
3267
+ if (isFull && stage2 !== "dev") throw new ScriptError("--full applies only to service dev");
3268
+ if (options.detach && !["dev", "prod"].includes(stage2)) throw new ScriptError("--detach applies only to dev/prod; tests are finite");
3463
3269
  const runOptions = {
3464
3270
  projectDir,
3465
3271
  debug: Boolean(options.debug),
@@ -3468,19 +3274,19 @@ async function handleServiceUp(rawStage, options = {}) {
3468
3274
  silenceWarnings: Boolean(options.silenceWarnings),
3469
3275
  full: isFull
3470
3276
  };
3471
- if (stage === "dev") {
3277
+ if (stage2 === "dev") {
3472
3278
  return await runDev(runOptions);
3473
3279
  }
3474
- if (stage === "prod") {
3280
+ if (stage2 === "prod") {
3475
3281
  return await runProd(runOptions);
3476
3282
  }
3477
- if (stage === "test-unit") {
3283
+ if (stage2 === "test-unit") {
3478
3284
  return await runTestUnit(runOptions);
3479
3285
  }
3480
- if (stage === "test-e2e") {
3286
+ if (stage2 === "test-e2e") {
3481
3287
  return await runTestE2e(runOptions);
3482
3288
  }
3483
- if (stage === "test") {
3289
+ if (stage2 === "test") {
3484
3290
  return await runTest(runOptions);
3485
3291
  }
3486
3292
  throw new ScriptError(
@@ -3503,7 +3309,7 @@ var registerUpCommand = (cmd) => {
3503
3309
  "Silence non-critical warnings like URL templating hints"
3504
3310
  ).option(
3505
3311
  "--full",
3506
- "Run dev with all declared local dependencies integrated"
3312
+ "Run dev with the full effective requisite graph"
3507
3313
  ).option(
3508
3314
  "-C, --project-dir <dir>",
3509
3315
  "Service project directory (defaults to cwd)"
@@ -3519,10 +3325,11 @@ Examples:
3519
3325
  $ builder service up test-e2e
3520
3326
 
3521
3327
  JSON overlays: test-unit uses build.json test; test-e2e uses build.json e2e.
3328
+ These convenience workflow names do not select Dockerfile targets. Main targets are dev, test, and prod.
3522
3329
  The test command runs unit tests before E2E.`
3523
3330
  ).action(
3524
- async (stage = "dev", options = {}) => {
3525
- const exitCode = await handleServiceUp(stage, {
3331
+ async (stage2 = "dev", options = {}) => {
3332
+ const exitCode = await handleServiceUp(stage2, {
3526
3333
  projectDir: options.projectDir,
3527
3334
  debug: options.debug,
3528
3335
  detach: options.detach,
@@ -3537,28 +3344,22 @@ The test command runs unit tests before E2E.`
3537
3344
  }
3538
3345
  );
3539
3346
  };
3540
- function compileApplicationEnv(stage, projectDir, options = {}) {
3347
+ function resolveComposeConfig(yaml, dir) {
3348
+ const result = spawnSync("docker", ["compose", "--project-directory", dir, "-f", "-", "config", "--format", "json"], { cwd: dir, encoding: "utf-8", input: yaml });
3349
+ if (result.error || result.status !== 0) throw new ScriptError(`Failed to resolve application environment: ${result.error?.message || result.stderr || result.stdout}`);
3350
+ return JSON.parse(result.stdout);
3351
+ }
3352
+ function compileApplicationEnv(stage2, projectDir, options = {}, resolver = resolveComposeConfig) {
3541
3353
  const dir = resolveProjectDir(projectDir);
3542
- const yaml = compileEnvironment(stage, dir, options);
3543
- const result = spawnSync("docker", [
3544
- "compose",
3545
- "--project-directory",
3546
- dir,
3547
- "-f",
3548
- "-",
3549
- "config",
3550
- "--format",
3551
- "json"
3552
- ], { cwd: dir, encoding: "utf-8", input: yaml });
3553
- if (result.error || result.status !== 0) {
3554
- throw new ScriptError(`Failed to resolve ${stage} application environment: ${result.error?.message || result.stderr || result.stdout}`);
3555
- }
3556
- const config = JSON.parse(result.stdout);
3557
- if (!config.services?.app) {
3558
- throw new ScriptError(`The ${stage} configuration has no application service ('app').`);
3354
+ const compiled = compileServiceComposition(stage2, dir, { validationMode: true, ...options });
3355
+ const main = compiled.mainServiceNames.get(nodeId(void 0, "main"));
3356
+ const yaml = stringify(compiled.compose);
3357
+ const config = resolver(yaml, dir);
3358
+ if (!main || !config.services?.[main]) {
3359
+ throw new ScriptError(`The ${stage2} configuration has no main service.`);
3559
3360
  }
3560
3361
  const environment = {};
3561
- for (const [key, value] of Object.entries(config.services.app.environment ?? {})) {
3362
+ for (const [key, value] of Object.entries(config.services[main].environment ?? {})) {
3562
3363
  if (value !== null && value !== void 0) {
3563
3364
  environment[key] = String(value).replace(/\$\$/g, "$");
3564
3365
  }
@@ -3580,8 +3381,8 @@ function serializeApplicationEnv(environment) {
3580
3381
  // src/commands/service/commands/export/handler.ts
3581
3382
  var STAGES = ["dev", "prod", "test", "e2e"];
3582
3383
  async function handleExportEnv(rawStage, options = {}) {
3583
- const stage = rawStage?.toLowerCase();
3584
- if (stage !== void 0 && !STAGES.includes(stage)) {
3384
+ const stage2 = rawStage?.toLowerCase();
3385
+ if (stage2 !== void 0 && !STAGES.includes(stage2)) {
3585
3386
  throw new ScriptError(`Unknown environment stage: "${rawStage}". Supported stages: ${STAGES.join(", ")}`);
3586
3387
  }
3587
3388
  const projectDir = resolveProjectDir(options.projectDir);
@@ -3595,10 +3396,10 @@ async function handleExportEnv(rawStage, options = {}) {
3595
3396
  );
3596
3397
  }
3597
3398
  };
3598
- const stages = stage === void 0 ? STAGES : [stage];
3599
- const snapshots = stages.map((stage2) => ({
3600
- stage: stage2,
3601
- content: serializeApplicationEnv(compileApplicationEnv(stage2, projectDir, options))
3399
+ const stages = stage2 === void 0 ? STAGES : [stage2];
3400
+ const snapshots = stages.map((stage3) => ({
3401
+ stage: stage3,
3402
+ content: serializeApplicationEnv(compileApplicationEnv(stage3, projectDir, options))
3602
3403
  }));
3603
3404
  let reader;
3604
3405
  const ask = async (question) => {
@@ -3635,7 +3436,7 @@ async function handleExportEnv(rawStage, options = {}) {
3635
3436
  throw error;
3636
3437
  }
3637
3438
  files.push(filename);
3638
- console.log(pc14.green(`Exported ${snapshot.stage} application environment to ${filename}`));
3439
+ console.log(pc9.green(`Exported ${snapshot.stage} application environment to ${filename}`));
3639
3440
  break;
3640
3441
  }
3641
3442
  }
@@ -3653,8 +3454,8 @@ Examples:
3653
3454
  $ builder service export env
3654
3455
  $ builder service export env dev
3655
3456
  $ builder service export env e2e -C ./services/backend
3656
- $ builder service export env dev --full`).action(async (stage, options) => {
3657
- await handleExportEnv(stage, {
3457
+ $ builder service export env dev --full`).action(async (stage2, options) => {
3458
+ await handleExportEnv(stage2, {
3658
3459
  projectDir: options.projectDir,
3659
3460
  full: Boolean(options.full),
3660
3461
  silenceWarnings: options.silenceWarnings
@@ -3666,6 +3467,10 @@ Examples:
3666
3467
  var registerServiceCommand = (cmd) => {
3667
3468
  const service = cmd.command("service").description("Manage and run services");
3668
3469
  service.hook("preAction", async (_thisCommand, actionCommand) => {
3470
+ if (actionCommand.name() === "up") {
3471
+ const options = actionCommand.opts(), stageArg = actionCommand.args[0]?.toLowerCase();
3472
+ if (options.dryRun || stageArg && !SERVICE_STAGES.includes(stageArg)) return;
3473
+ }
3669
3474
  if (actionCommand.name() === "env" && actionCommand.parent?.name() === "export") {
3670
3475
  checkComposeAvailability();
3671
3476
  return;
@@ -3673,10 +3478,7 @@ var registerServiceCommand = (cmd) => {
3673
3478
  checkDependencies();
3674
3479
  if (actionCommand.name() === "up") {
3675
3480
  const options = actionCommand.opts();
3676
- const stageArg = actionCommand.args[0]?.toLowerCase();
3677
- if (stageArg && !SERVICE_STAGES.includes(stageArg)) {
3678
- return;
3679
- }
3481
+ actionCommand.args[0]?.toLowerCase();
3680
3482
  const projectDir = resolveProjectDir(options.projectDir);
3681
3483
  if (!options.skipChecks) {
3682
3484
  checkInfra(projectDir);
@@ -3711,10 +3513,10 @@ async function runCli(argv = process.argv) {
3711
3513
  (arg) => arg === "-h" || arg === "--help" || arg === "-V" || arg === "--version"
3712
3514
  );
3713
3515
  if (!isHelpOrVersion && argv.length > 2) {
3714
- console.log(pc14.dim(`builder v${version}`));
3516
+ console.log(pc9.dim(`builder v${version}`));
3715
3517
  }
3716
3518
  if (argv.length <= 2) {
3717
- console.log(pc14.dim(`builder v${version}
3519
+ console.log(pc9.dim(`builder v${version}
3718
3520
  `));
3719
3521
  cli.outputHelp();
3720
3522
  return;
@@ -3737,20 +3539,20 @@ async function runCli(argv = process.argv) {
3737
3539
  if (err instanceof ScriptError) {
3738
3540
  exitCode = err.exitCode;
3739
3541
  const formatted = err.message.startsWith("\u274C") ? err.message : `\u274C ${err.message}`;
3740
- console.error(pc14.red(`
3542
+ console.error(pc9.red(`
3741
3543
  ${formatted}
3742
3544
  `));
3743
3545
  if (isVerbose && err.stack) {
3744
- console.error(pc14.dim(err.stack));
3546
+ console.error(pc9.dim(err.stack));
3745
3547
  }
3746
3548
  } else {
3747
3549
  const message = errorMessage(err);
3748
3550
  const formatted = message.startsWith("\u274C") ? message : `\u274C Error: ${message}`;
3749
- console.error(pc14.red(`
3551
+ console.error(pc9.red(`
3750
3552
  ${formatted}
3751
3553
  `));
3752
3554
  if (isVerbose && err instanceof Error && err.stack) {
3753
- console.error(pc14.dim(err.stack));
3555
+ console.error(pc9.dim(err.stack));
3754
3556
  }
3755
3557
  }
3756
3558
  if (process.env.VITEST) {
@@ -3760,6 +3562,6 @@ ${formatted}
3760
3562
  }
3761
3563
  }
3762
3564
 
3763
- export { ConfigError, NotFoundError, PortConflictError, SERVICE_STAGES, ScriptError, buildJsonSchema, compileApplicationEnv, compileEnvironment, compileMeshEnvironment, createCli, meshSchema, runCli, runCompose, serializeApplicationEnv, teardownCompose, version };
3565
+ export { ConfigError, NotFoundError, PortConflictError, SERVICE_STAGES, ScriptError, buildJsonSchema, compileApplicationEnv, compileEnvironment, compileMeshEnvironment, createCli, isMainEntry, isTesterEntry, meshSchema, runCli, runCompose, serializeApplicationEnv, teardownCompose, version };
3764
3566
  //# sourceMappingURL=index.js.map
3765
3567
  //# sourceMappingURL=index.js.map