@solid-stack/builder 2.0.3 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +580 -50
  2. package/dist/bin.js +1060 -767
  3. package/dist/bin.js.map +1 -1
  4. package/dist/commands/mesh/commands/down/handler.d.ts.map +1 -1
  5. package/dist/commands/mesh/commands/up/handler.d.ts.map +1 -1
  6. package/dist/commands/service/commands/export/handler.d.ts.map +1 -1
  7. package/dist/core/composeCleanup.d.ts.map +1 -1
  8. package/dist/core/composition/assertComposeLifecycleAcyclic.d.ts +7 -0
  9. package/dist/core/composition/assertComposeLifecycleAcyclic.d.ts.map +1 -0
  10. package/dist/core/composition/compileServiceComposition.d.ts.map +1 -1
  11. package/dist/core/composition/composeDependsOn.d.ts +3 -1
  12. package/dist/core/composition/composeDependsOn.d.ts.map +1 -1
  13. package/dist/core/composition/composePaths.d.ts +1 -0
  14. package/dist/core/composition/composePaths.d.ts.map +1 -1
  15. package/dist/core/composition/dependencyLifecycle.d.ts.map +1 -1
  16. package/dist/core/composition/mergeAppOverride.d.ts +3 -0
  17. package/dist/core/composition/mergeAppOverride.d.ts.map +1 -0
  18. package/dist/core/composition/namespaceDependencyCompose.d.ts.map +1 -1
  19. package/dist/core/composition/namespaceResourceDefinition.d.ts +3 -0
  20. package/dist/core/composition/namespaceResourceDefinition.d.ts.map +1 -0
  21. package/dist/core/composition/selectAppEnvironmentEntries.d.ts +3 -0
  22. package/dist/core/composition/selectAppEnvironmentEntries.d.ts.map +1 -0
  23. package/dist/core/composition/types.d.ts +16 -4
  24. package/dist/core/composition/types.d.ts.map +1 -1
  25. package/dist/core/composition/validateDependencyCompose.d.ts.map +1 -1
  26. package/dist/core/composition/validateMaterializedComposeBuildInputs.d.ts +4 -0
  27. package/dist/core/composition/validateMaterializedComposeBuildInputs.d.ts.map +1 -0
  28. package/dist/core/composition/validateMaterializedComposeFiles.d.ts +8 -0
  29. package/dist/core/composition/validateMaterializedComposeFiles.d.ts.map +1 -0
  30. package/dist/core/composition/validateOverrideCompose.d.ts.map +1 -1
  31. package/dist/core/config/builderEnvironment.d.ts +12 -0
  32. package/dist/core/config/builderEnvironment.d.ts.map +1 -0
  33. package/dist/core/config/endpointProperties.d.ts +5 -2
  34. package/dist/core/config/endpointProperties.d.ts.map +1 -1
  35. package/dist/core/config/hostPorts.d.ts +5 -1
  36. package/dist/core/config/hostPorts.d.ts.map +1 -1
  37. package/dist/core/config/meshStageContract.d.ts +6 -0
  38. package/dist/core/config/meshStageContract.d.ts.map +1 -0
  39. package/dist/core/config/references.d.ts +9 -3
  40. package/dist/core/config/references.d.ts.map +1 -1
  41. package/dist/core/config/resolveBuildStage.d.ts.map +1 -1
  42. package/dist/core/config/resolveMeshStage.d.ts.map +1 -1
  43. package/dist/core/config/stageMerge.d.ts +2 -0
  44. package/dist/core/config/stageMerge.d.ts.map +1 -1
  45. package/dist/core/config/types.d.ts +8 -3
  46. package/dist/core/config/types.d.ts.map +1 -1
  47. package/dist/core/mesh/checkers/checkMeshServices.d.ts +1 -1
  48. package/dist/core/mesh/checkers/checkMeshServices.d.ts.map +1 -1
  49. package/dist/core/mesh/getMeshJson.d.ts.map +1 -1
  50. package/dist/core/mesh/meshSchema.d.ts +13 -56
  51. package/dist/core/mesh/meshSchema.d.ts.map +1 -1
  52. package/dist/core/mesh/runners/runMeshDev.d.ts.map +1 -1
  53. package/dist/core/mesh/runners/runMeshProd.d.ts.map +1 -1
  54. package/dist/core/mesh/runners/runMeshServiceTests.d.ts +3 -0
  55. package/dist/core/mesh/runners/runMeshServiceTests.d.ts.map +1 -0
  56. package/dist/core/mesh/runners/runMeshTest.d.ts.map +1 -1
  57. package/dist/core/mesh/runners/runMeshTestE2e.d.ts.map +1 -1
  58. package/dist/core/mesh/types.d.ts +4 -4
  59. package/dist/core/mesh/types.d.ts.map +1 -1
  60. package/dist/core/mesh/v2/compileMeshComposition.d.ts.map +1 -1
  61. package/dist/core/mesh/v2/compileMeshTester.d.ts.map +1 -1
  62. package/dist/core/mesh/v2/meshReferences.d.ts +5 -3
  63. package/dist/core/mesh/v2/meshReferences.d.ts.map +1 -1
  64. package/dist/core/mesh/v2/resolveMeshAppEnvironment.d.ts +4 -0
  65. package/dist/core/mesh/v2/resolveMeshAppEnvironment.d.ts.map +1 -0
  66. package/dist/core/runWithCleanup.d.ts +3 -0
  67. package/dist/core/runWithCleanup.d.ts.map +1 -0
  68. package/dist/core/runners/runDev.d.ts.map +1 -1
  69. package/dist/core/runners/runFiniteTester.d.ts +3 -0
  70. package/dist/core/runners/runFiniteTester.d.ts.map +1 -0
  71. package/dist/core/runners/runProd.d.ts.map +1 -1
  72. package/dist/core/runners/runTestE2e.d.ts.map +1 -1
  73. package/dist/core/runners/runTestUnit.d.ts.map +1 -1
  74. package/dist/core/teardownCompose.d.ts.map +1 -1
  75. package/dist/errors/PortConflictError.d.ts +1 -1
  76. package/dist/errors/PortConflictError.d.ts.map +1 -1
  77. package/dist/index.js +1060 -767
  78. package/dist/index.js.map +1 -1
  79. package/dist/templates/policy/dockerfile/dockerfile.rego +7 -4
  80. package/dist/utils/runState.d.ts.map +1 -1
  81. package/package.json +1 -1
  82. package/schemas/mesh-schema.json +1 -106
  83. package/templates/policy/dockerfile/dockerfile.rego +7 -4
  84. package/dist/core/mesh/runners/runMeshTestUnit.d.ts +0 -3
  85. package/dist/core/mesh/runners/runMeshTestUnit.d.ts.map +0 -1
  86. package/dist/core/mesh/v2/validateMeshTestStage.d.ts +0 -22
  87. package/dist/core/mesh/v2/validateMeshTestStage.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Command, Argument } from 'commander';
2
- import pc22 from 'picocolors';
3
- import fs, { existsSync, readFileSync, mkdirSync, writeFileSync, renameSync, statSync, realpathSync, lstatSync, readlinkSync, unlinkSync } from 'fs';
2
+ import pc15 from 'picocolors';
3
+ import fs, { existsSync, readFileSync, statSync, mkdirSync, writeFileSync, renameSync, realpathSync, lstatSync, readlinkSync, unlinkSync } from 'fs';
4
4
  import path from 'path';
5
5
  import { z } from 'zod';
6
6
  import { spawnSync, spawn } from 'child_process';
@@ -174,7 +174,7 @@ function runStep(executable, args, projectDir, ctx) {
174
174
  if (stderr) process.stderr.write(stderr);
175
175
  if (result.error || result.status !== 0) {
176
176
  console.error("\n" + "=".repeat(60));
177
- console.error(pc22.red(`\u{1F6A8} INFRASTRUCTURE CHECK FAILED \u{1F6A8}`));
177
+ console.error(pc15.red(`\u{1F6A8} INFRASTRUCTURE CHECK FAILED \u{1F6A8}`));
178
178
  console.error("=".repeat(60));
179
179
  console.error(`Failed Step : ${ctx.stepName}`);
180
180
  if (ctx.targetFile) {
@@ -201,7 +201,7 @@ function checkDockerfile(buildJson, projectDir) {
201
201
  const dockerfileRel = buildJson.dockerfile || "Dockerfile";
202
202
  const dockerfilePath = resolveApplicationDockerfile(projectDir, dockerfileRel);
203
203
  const content = readFileSync(dockerfilePath, "utf-8");
204
- console.log(pc22.cyan(`
204
+ console.log(pc15.cyan(`
205
205
  \u{1F50D} Linting Dockerfile (${dockerfileRel})...`));
206
206
  runStep(
207
207
  "docker",
@@ -271,7 +271,7 @@ function checkDockerfileContract(build, projectDir) {
271
271
  const relative = build.dockerfile ?? "Dockerfile";
272
272
  resolveApplicationDockerfile(root, relative);
273
273
  const policyDir = getDockerfilePolicyDir();
274
- console.log(pc22.cyan(`
274
+ console.log(pc15.cyan(`
275
275
  \u{1F50D} Validating Builder Dockerfile contract (${relative})...`));
276
276
  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
277
  }
@@ -326,7 +326,7 @@ function getDeclaredYamlFiles(build, projectDir) {
326
326
  function checkYamlFiles(build, projectDir) {
327
327
  const root = resolveProjectDir(projectDir);
328
328
  const files = getDeclaredYamlFiles(build, root);
329
- if (files.length) console.log(pc22.cyan(`
329
+ if (files.length) console.log(pc15.cyan(`
330
330
  \u{1F50D} Validating ${files.length} declared V2 Compose file(s)...`));
331
331
  for (const file of files) {
332
332
  const absolutePath = resolveInsideProject(root, file.relativePath, { sourceFile: `${root}/build.json`, configPath: file.source, ...file.stage ? { stage: file.stage } : {} });
@@ -368,13 +368,24 @@ function normalizeNetworks(value) {
368
368
  return value && typeof value === "object" ? { ...value } : {};
369
369
  }
370
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
+
371
381
  // src/core/config/endpointProperties.ts
372
382
  function resolveEndpointProperty(endpoint, property, context) {
383
+ const reference = context.referencedObject ?? endpoint.logicalPath;
373
384
  const published = () => {
374
- if (!endpoint.effectivelyPublished || endpoint.publicHost === void 0 || endpoint.publicPort === void 0) throw new ConfigError({ ...context, configPath: context.configPath, referencedObject: endpoint.logicalPath, reason: `Endpoint property ${property} requires effective publication` });
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` });
375
386
  };
376
387
  const scheme = () => {
377
- if (!endpoint.scheme) throw new ConfigError({ ...context, referencedObject: endpoint.logicalPath, reason: `Endpoint property ${property} requires an endpoint scheme` });
388
+ if (!endpoint.scheme) throw new ConfigError({ ...context, referencedObject: reference, reason: `Endpoint property ${property} requires an endpoint scheme` });
378
389
  return endpoint.scheme;
379
390
  };
380
391
  switch (property) {
@@ -429,6 +440,18 @@ function assertAcyclicGraph(graph, context) {
429
440
  }
430
441
 
431
442
  // 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"];
453
+ }
454
+ }
432
455
  function unionStable(base = [], overlay = []) {
433
456
  return [.../* @__PURE__ */ new Set([...base, ...overlay])];
434
457
  }
@@ -438,32 +461,40 @@ function mergeStringMap(base, overlay) {
438
461
 
439
462
  // src/core/config/resolveBuildStage.ts
440
463
  function resolveBuildStage(build, stage, sourceFile) {
441
- const overlay = build[stage] ?? {};
464
+ const context = (configPath, value, reason, referencedObject) => new ConfigError({ sourceFile, configPath, stage, composition: "service", value, ...referencedObject ? { referencedObject } : {}, reason });
465
+ const appEnv = { ...build.app.env ?? {} };
442
466
  const appEndpoints = structuredClone(build.app.endpoints ?? {});
443
- for (const [name, endpoint] of Object.entries(overlay.app?.endpoints ?? {})) appEndpoints[name] = { ...appEndpoints[name] ?? {}, ...endpoint };
444
467
  const dependencies = {};
445
468
  for (const [name, dep] of Object.entries(build.dependencies ?? {})) dependencies[name] = { ...dep, env: { ...dep.env ?? {} }, endpoints: structuredClone(dep.endpoints ?? {}), dependsOn: [...dep.dependsOn ?? []] };
446
- for (const [name, patch] of Object.entries(overlay.dependencies ?? {})) {
447
- const prior = dependencies[name] ?? { compose: void 0, env: {}, endpoints: {}, dependsOn: [] };
448
- prior.compose = patch.compose ?? prior.compose;
449
- prior.env = mergeStringMap(prior.env, patch.env);
450
- for (const [ep, epPatch] of Object.entries(patch.endpoints ?? {})) prior.endpoints[ep] = { ...prior.endpoints[ep] ?? {}, ...epPatch };
451
- prior.dependsOn = unionStable(prior.dependsOn, patch.dependsOn);
452
- dependencies[name] = prior;
453
- }
454
- const effective = { ...build, app: { env: mergeStringMap(build.app.env, overlay.app?.env), endpoints: appEndpoints }, dependencies, tester: build.tester ? { env: { ...build.tester.env ?? {} } } : void 0, overrideCompose: overlay["override-compose"] };
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 };
455
488
  delete effective.dev;
456
489
  delete effective.prod;
457
490
  delete effective.test;
458
491
  delete effective.e2e;
459
- const context = (configPath, value, reason, referencedObject) => new ConfigError({ sourceFile, configPath, stage, composition: "service", value, ...referencedObject ? { referencedObject } : {}, reason });
460
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");
461
493
  assertPrimaryEndpointInvariant(appEndpoints, { sourceFile, configPath: "app.endpoints", stage });
462
494
  const graph = /* @__PURE__ */ new Map();
463
495
  for (const [name, dep] of Object.entries(dependencies)) {
464
496
  if (typeof dep.compose !== "string" || !dep.compose.trim()) throw context(`dependencies.${name}.compose`, dep.compose, "Effective dependency requires compose");
465
- const endpoints = Object.entries(dep.endpoints);
466
- for (const [epName, ep] of endpoints) if (!ep.service || !Number.isInteger(ep.port) || ep.port < 1 || ep.port > 65535) throw context(`dependencies.${name}.endpoints.${epName}`, ep, "Effective dependency endpoint requires service and port");
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");
467
498
  assertPrimaryEndpointInvariant(dep.endpoints, { sourceFile, configPath: `dependencies.${name}.endpoints`, stage });
468
499
  const node = `dependencies.${name}`;
469
500
  graph.set(node, /* @__PURE__ */ new Set());
@@ -487,29 +518,42 @@ var BUILD_APP = /^app\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
487
518
  var BUILD_DEP = /^dependencies\.([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
488
519
  var MESH_APP = /^([a-z][a-z0-9-]*)\.app\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
489
520
  var MESH_DEP = /^([a-z][a-z0-9-]*)\.dependencies\.([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
490
- function parse2(raw, scope, sourcePath) {
491
- let m;
492
- if (scope === "build" && (m = BUILD_APP.exec(raw))) return valid({ raw, scope, target: "app", endpoint: m[1], property: m[2] }, sourcePath);
493
- if (scope === "build" && (m = BUILD_DEP.exec(raw))) return valid({ raw, scope, target: "dependency", dependency: m[1], endpoint: m[2], property: m[3] }, sourcePath);
494
- if (scope === "mesh" && (m = MESH_APP.exec(raw))) return valid({ raw, scope, meshService: m[1], target: "app", endpoint: m[2], property: m[3] }, sourcePath);
495
- if (scope === "mesh" && (m = MESH_DEP.exec(raw))) return valid({ raw, scope, meshService: m[1], target: "dependency", dependency: m[2], endpoint: m[3], property: m[4] }, sourcePath);
496
- throw new ConfigError({ configPath: sourcePath, value: raw, reason: `Invalid ${scope} endpoint reference` });
497
- }
498
- function valid(ref, sourcePath) {
499
- if (!ENDPOINT_PROPERTIES.includes(ref.property)) throw new ConfigError({ configPath: sourcePath, value: ref.property, reason: "Unknown endpoint property" });
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` });
528
+ }
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" });
532
+ }
500
533
  return ref;
501
534
  }
502
- function collectBuilderReferences(value, scope, sourcePath) {
503
- const protectedValue = value.replace(/\$\$/g, "\0DOLLAR\0"), refs2 = [];
504
- for (const match of protectedValue.matchAll(/\$\{([^}]*)\}/g)) refs2.push(parse2(match[1], scope, sourcePath));
505
- return refs2;
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;
506
540
  }
507
- function interpolateBuilderReferences(value, scope, resolve) {
541
+ function interpolateBuilderReferences(value, scope, resolve, context) {
508
542
  const sentinel = "\0DOLLAR\0";
509
- return value.replace(/\$\$/g, sentinel).replace(/\$\{([^}]*)\}/g, (whole, body) => resolve(parse2(body, scope, "environment"))).replaceAll(sentinel, "$");
510
- }
511
- function assertTesterReferencesArePublic(env, scope, sourcePrefix) {
512
- for (const [key, value] of Object.entries(env)) for (const ref of collectBuilderReferences(value, scope, `${sourcePrefix}.${key}`)) if (!PUBLIC_ENDPOINT_PROPERTIES.has(ref.property)) throw new ConfigError({ configPath: `${sourcePrefix}.${key}`, value: ref.raw, reason: "Tester references may use only public endpoint properties" });
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
+ }
556
+ }
513
557
  }
514
558
 
515
559
  // src/errors/PortConflictError.ts
@@ -517,8 +561,8 @@ var PortConflictError = class extends ConfigError {
517
561
  port;
518
562
  firstOwner;
519
563
  secondOwner;
520
- constructor(port, firstOwner, secondOwner, stage) {
521
- super({ sourceFile: "Builder effective composition", configPath: "publicPort", value: port, stage, reason: `Host port ${port} is claimed by both ${firstOwner} and ${secondOwner}. Builder does not remap fixed public ports.` });
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.` });
522
566
  this.name = "PortConflictError";
523
567
  this.port = port;
524
568
  this.firstOwner = firstOwner;
@@ -532,11 +576,11 @@ function isHostPortAvailableSync(port) {
532
576
  const result = spawnSync(process.execPath, ["-e", script], { stdio: "ignore", timeout: 3e3 });
533
577
  return result.status === 0;
534
578
  }
535
- function allocateHostPorts(projectDir, stage, intentsInDeterministicOrder, validationMode = false) {
579
+ function allocateHostPorts(projectDir, stage, intentsInDeterministicOrder, validationMode = false, context) {
536
580
  const reserved = /* @__PURE__ */ new Map(), allocated = /* @__PURE__ */ new Map();
537
581
  for (const intent of intentsInDeterministicOrder) if (typeof intent.requested === "number") {
538
582
  const owner = reserved.get(intent.requested);
539
- if (owner) throw new PortConflictError(intent.requested, owner, intent.logicalPath, stage);
583
+ if (owner) throw new PortConflictError(intent.requested, owner, intent.logicalPath, stage, context?.sourceFile, context?.composition);
540
584
  reserved.set(intent.requested, intent.logicalPath);
541
585
  allocated.set(intent.logicalPath, intent.requested);
542
586
  }
@@ -544,7 +588,7 @@ function allocateHostPorts(projectDir, stage, intentsInDeterministicOrder, valid
544
588
  let placeholder = 6e4;
545
589
  for (const intent of intentsInDeterministicOrder) if (intent.requested === "AUTO") {
546
590
  while (reserved.has(placeholder)) placeholder--;
547
- if (placeholder < 1) throw new ConfigError({ configPath: intent.logicalPath, stage, reason: "No validation placeholder port is available" });
591
+ if (placeholder < 1) throw new ConfigError({ ...context ?? {}, configPath: intent.logicalPath, stage, value: intent.requested, reason: "No validation placeholder port is available" });
548
592
  reserved.set(placeholder, intent.logicalPath);
549
593
  allocated.set(intent.logicalPath, placeholder--);
550
594
  }
@@ -568,7 +612,7 @@ function allocateHostPorts(projectDir, stage, intentsInDeterministicOrder, valid
568
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));
569
613
  selected = scan.find((p) => !reserved.has(p) && isHostPortAvailableSync(p));
570
614
  }
571
- if (selected === void 0) throw new ConfigError({ sourceFile: "Builder effective composition", configPath: intent.logicalPath, stage, reason: "No available host port could be allocated" });
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" });
572
616
  reserved.set(selected, intent.logicalPath);
573
617
  allocated.set(intent.logicalPath, selected);
574
618
  nextCache[intent.logicalPath] = selected;
@@ -581,6 +625,26 @@ function allocateHostPorts(projectDir, stage, intentsInDeterministicOrder, valid
581
625
  }
582
626
  return allocated;
583
627
  }
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}"` });
635
+ }
636
+ }
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}"` });
646
+ }
647
+ }
584
648
  function normalizeProjectName(name, projectDir) {
585
649
  let normalized = name.toLowerCase().replace(/[^a-z0-9_-]/g, "-").replace(/^[-_]+/, "").replace(/[-_]+$/, "");
586
650
  if (!normalized || !/^[a-z0-9]/.test(normalized)) {
@@ -822,6 +886,20 @@ function assertNoServiceBuildContexts(service, configPath, sourceFile) {
822
886
  }
823
887
  }
824
888
 
889
+ // src/core/composition/namespaceResourceDefinition.ts
890
+ function namespaceResourceDefinition(originalKey, definition) {
891
+ if (definition === null || typeof definition !== "object" || Array.isArray(definition)) {
892
+ return definition;
893
+ }
894
+ const result = structuredClone(definition);
895
+ if (result.external === true) {
896
+ result.name ??= originalKey;
897
+ } else {
898
+ delete result.name;
899
+ }
900
+ return result;
901
+ }
902
+
825
903
  // src/core/composition/namespaceDependencyCompose.ts
826
904
  var entries = (obj) => obj && typeof obj === "object" && !Array.isArray(obj) ? Object.entries(obj) : [];
827
905
  function namespaceDependencyCompose(options) {
@@ -835,6 +913,7 @@ function namespaceDependencyCompose(options) {
835
913
  const serviceNameMap = make("service", Object.keys(doc.services ?? {}));
836
914
  const volumeNameMap = make("volume", Object.keys(doc.volumes ?? {})), networkNameMap = make("network", Object.keys(doc.networks ?? {})), configNameMap = make("config", Object.keys(doc.configs ?? {})), secretNameMap = make("secret", Object.keys(doc.secrets ?? {}));
837
915
  const rewriteKeys = (obj, map) => Object.fromEntries(entries(obj).map(([k, v]) => [map.get(k) ?? k, v]));
916
+ const rewriteResourceDefinitions = (obj, map) => Object.fromEntries(entries(obj).map(([key, definition]) => [map.get(key) ?? key, namespaceResourceDefinition(key, definition)]));
838
917
  const addOriginalNetworkAliases = (name, svc) => {
839
918
  if (svc.network_mode !== void 0 || svc.networks === void 0) return;
840
919
  const attached = Array.isArray(svc.networks) ? Object.fromEntries(svc.networks.filter((network) => typeof network === "string").map((network) => [network, null])) : svc.networks && typeof svc.networks === "object" ? { ...svc.networks } : {};
@@ -870,16 +949,15 @@ function namespaceDependencyCompose(options) {
870
949
  };
871
950
  for (const [name, svc] of Object.entries(originalServices)) rewriteResourceRefs(svc, name);
872
951
  doc.services = rewriteKeys(doc.services, serviceNameMap);
873
- if (doc.volumes) doc.volumes = rewriteKeys(doc.volumes, volumeNameMap);
874
- if (doc.networks) doc.networks = rewriteKeys(doc.networks, networkNameMap);
875
- if (doc.configs) doc.configs = rewriteKeys(doc.configs, configNameMap);
876
- if (doc.secrets) doc.secrets = rewriteKeys(doc.secrets, secretNameMap);
952
+ if (doc.volumes) doc.volumes = rewriteResourceDefinitions(doc.volumes, volumeNameMap);
953
+ if (doc.networks) doc.networks = rewriteResourceDefinitions(doc.networks, networkNameMap);
954
+ if (doc.configs) doc.configs = rewriteResourceDefinitions(doc.configs, configNameMap);
955
+ if (doc.secrets) doc.secrets = rewriteResourceDefinitions(doc.secrets, secretNameMap);
877
956
  return { document: doc, serviceNameMap, volumeNameMap, networkNameMap, configNameMap, secretNameMap };
878
957
  }
879
958
 
880
959
  // src/core/composition/validateComposeResourceReferences.ts
881
960
  function validateComposeResourceReferences(document, context, onlyServices) {
882
- const selected = onlyServices ? new Set(onlyServices) : void 0;
883
961
  const fail = (configPath, kind, name) => {
884
962
  throw new ConfigError({
885
963
  sourceFile: context.sourceFile,
@@ -894,12 +972,11 @@ function validateComposeResourceReferences(document, context, onlyServices) {
894
972
  const definitions = document[kind === "volume" ? "volumes" : kind === "network" ? "networks" : kind === "config" ? "configs" : "secrets"];
895
973
  return Boolean(definitions && Object.hasOwn(definitions, name));
896
974
  };
897
- const check = (path20, kind, name) => {
975
+ const check = (path24, kind, name) => {
898
976
  if (kind === "network" && name === "default") return;
899
- if (!exists(kind, name)) fail(path20, kind, name);
977
+ if (!exists(kind, name)) fail(path24, kind, name);
900
978
  };
901
979
  for (const [serviceName, service] of Object.entries(document.services ?? {})) {
902
- if (selected && !selected.has(serviceName)) continue;
903
980
  validateServiceResources(serviceName, service, check);
904
981
  }
905
982
  }
@@ -928,6 +1005,21 @@ function validateServiceResources(serviceName, service, check) {
928
1005
  }
929
1006
  }
930
1007
 
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
+
931
1023
  // src/core/composition/composeHealthcheck.ts
932
1024
  function isEnabledValidComposeHealthcheck(value) {
933
1025
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
@@ -976,6 +1068,11 @@ function validateDependencyCompose(dependencyKey, dependency, document, context)
976
1068
  for (const key of ["ipc", "pid"]) if (typeof svc[key] === "string" && svc[key].startsWith("service:")) internalRefs.push([key, svc[key].slice(8)]);
977
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);
978
1070
  }
1071
+ assertComposeLifecycleAcyclic(services, {
1072
+ sourceFile: context.composePath,
1073
+ stage: context.stage,
1074
+ composition: "service"
1075
+ });
979
1076
  if (!Object.keys(dependency.endpoints).length) return;
980
1077
  if (!Object.keys(services).length) fail("services", "endpoint-bearing dependency Compose must define services");
981
1078
  const owners = /* @__PURE__ */ new Set();
@@ -989,6 +1086,87 @@ function validateDependencyCompose(dependencyKey, dependency, document, context)
989
1086
  if (!isEnabledValidComposeHealthcheck(services[owner].healthcheck)) fail(`services.${owner}.healthcheck`, "endpoint owner requires a valid enabled Compose healthcheck");
990
1087
  }
991
1088
  }
1089
+ function validateMaterializedComposeFiles(document, sourceFile, stage, options = {}) {
1090
+ const baseDir = options.baseDir ?? path.dirname(sourceFile);
1091
+ for (const kind of ["configs", "secrets"]) {
1092
+ for (const [name, raw] of Object.entries(document[kind] ?? {})) {
1093
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) continue;
1094
+ const file = raw.file;
1095
+ if (typeof file !== "string") continue;
1096
+ const absolute = path.resolve(baseDir, file);
1097
+ let regular = false;
1098
+ try {
1099
+ regular = fs.statSync(absolute).isFile();
1100
+ } catch {
1101
+ }
1102
+ if (!regular) {
1103
+ throw new ConfigError({
1104
+ sourceFile,
1105
+ configPath: `${kind}.${name}.file`,
1106
+ stage,
1107
+ composition: options.composition ?? "service",
1108
+ value: file,
1109
+ reason: "Materialized Compose file resource is missing or not a regular file"
1110
+ });
1111
+ }
1112
+ }
1113
+ }
1114
+ }
1115
+ function validateMaterializedComposeBuildInputs(document, sourceFile, stage, composition) {
1116
+ const baseDir = path.dirname(sourceFile);
1117
+ for (const [name, service] of Object.entries(document.services ?? {})) {
1118
+ const build = service.build;
1119
+ if (build === void 0) continue;
1120
+ const objectBuild = build && typeof build === "object" && !Array.isArray(build) ? build : void 0;
1121
+ const context = typeof build === "string" ? build : objectBuild?.context ?? ".";
1122
+ const configPath = `services.${name}.build`;
1123
+ const fail = (field, value, reason) => {
1124
+ throw new ConfigError({
1125
+ sourceFile,
1126
+ configPath: `${configPath}.${field}`,
1127
+ stage,
1128
+ composition,
1129
+ value,
1130
+ reason
1131
+ });
1132
+ };
1133
+ if (typeof context !== "string" || context.trim() === "") {
1134
+ return fail("context", context, "Local build context must be a non-empty path");
1135
+ }
1136
+ if (isRemoteBuildContext(context)) continue;
1137
+ const absoluteContext = path.resolve(baseDir, context);
1138
+ let directory = false;
1139
+ try {
1140
+ directory = fs.statSync(absoluteContext).isDirectory();
1141
+ } catch {
1142
+ }
1143
+ if (!directory) {
1144
+ fail(
1145
+ "context",
1146
+ context,
1147
+ "Materialized local build context is missing or not a directory"
1148
+ );
1149
+ }
1150
+ if (objectBuild?.dockerfile_inline !== void 0) continue;
1151
+ const dockerfile = objectBuild?.dockerfile ?? "Dockerfile";
1152
+ if (typeof dockerfile !== "string" || dockerfile.trim() === "") {
1153
+ return fail("dockerfile", dockerfile, "Dockerfile path must be a non-empty string");
1154
+ }
1155
+ const absoluteDockerfile = path.resolve(absoluteContext, dockerfile);
1156
+ let regular = false;
1157
+ try {
1158
+ regular = fs.statSync(absoluteDockerfile).isFile();
1159
+ } catch {
1160
+ }
1161
+ if (!regular) {
1162
+ fail(
1163
+ "dockerfile",
1164
+ dockerfile,
1165
+ "Materialized local Dockerfile is missing or not a regular file"
1166
+ );
1167
+ }
1168
+ }
1169
+ }
992
1170
  function canonicalBuildContext(value, baseDir) {
993
1171
  return canonicalPath(path.resolve(baseDir, value));
994
1172
  }
@@ -996,18 +1174,40 @@ function isSameBuildContext(actual, expected, baseDir) {
996
1174
  return canonicalBuildContext(actual, baseDir) === canonicalBuildContext(expected, baseDir);
997
1175
  }
998
1176
  function validateAndPrepareAppOverride(document, context) {
999
- const fail = (path20, reason, value) => {
1000
- throw new ConfigError({ sourceFile: context.file, configPath: path20, stage: context.stage, composition: "service", ...value === void 0 ? {} : { value }, reason });
1177
+ const fail = (path24, reason, value) => {
1178
+ throw new ConfigError({ sourceFile: context.file, configPath: path24, stage: context.stage, composition: "service", ...value === void 0 ? {} : { value }, reason });
1001
1179
  };
1002
1180
  const allowedRootKeys = /* @__PURE__ */ new Set(["services", "volumes", "networks", "configs", "secrets"]);
1003
1181
  for (const key of Object.keys(document)) if (!key.startsWith("x-") && !allowedRootKeys.has(key)) fail(key, "unsupported override Compose top-level field");
1004
1182
  const keys = Object.keys(document.services ?? {});
1005
1183
  if (keys.length !== 1 || keys[0] !== "app") fail("services", "override must define exactly one service named app");
1184
+ validateComposeResourceReferences(document, { sourceFile: context.file, stage: context.stage, composition: "service" });
1006
1185
  const app = structuredClone(document.services.app);
1007
1186
  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");
1008
- if (app.healthcheck && typeof app.healthcheck === "object") {
1009
- const health = app.healthcheck;
1010
- for (const key of Object.keys(health)) if (!["interval", "timeout", "retries", "start_period", "start_interval"].includes(key)) fail(`services.app.healthcheck.${key}`, "override may set only healthcheck timing fields");
1187
+ if (Object.hasOwn(app, "healthcheck")) {
1188
+ const healthcheck = app.healthcheck;
1189
+ if (healthcheck === null || typeof healthcheck !== "object" || Array.isArray(healthcheck)) {
1190
+ fail(
1191
+ "services.app.healthcheck",
1192
+ "override healthcheck must be a mapping of timing fields",
1193
+ healthcheck
1194
+ );
1195
+ }
1196
+ const allowedTiming = /* @__PURE__ */ new Set([
1197
+ "interval",
1198
+ "timeout",
1199
+ "retries",
1200
+ "start_period",
1201
+ "start_interval"
1202
+ ]);
1203
+ for (const key of Object.keys(healthcheck)) {
1204
+ if (!allowedTiming.has(key)) {
1205
+ fail(
1206
+ `services.app.healthcheck.${key}`,
1207
+ "override may set only healthcheck timing fields"
1208
+ );
1209
+ }
1210
+ }
1011
1211
  }
1012
1212
  if (typeof app.build === "string") {
1013
1213
  fail("services.app.build", "override cannot replace Builder-owned app build context; use object-form build.args for build arguments", app.build);
@@ -1035,22 +1235,22 @@ function validateAndPrepareAppOverride(document, context) {
1035
1235
  const resourceKeys = ["volumes", "networks", "configs", "secrets"];
1036
1236
  const resources = {};
1037
1237
  for (const kind of resourceKeys) {
1038
- const defs = document[kind] ?? {}, refs2 = /* @__PURE__ */ new Set(), value = app[kind];
1238
+ const defs = document[kind] ?? {}, refs = /* @__PURE__ */ new Set(), value = app[kind];
1039
1239
  if (Array.isArray(value)) for (const ref of value) {
1040
1240
  if (kind === "volumes") {
1041
1241
  const volume = parseVolume(ref);
1042
- if (volume?.type === "volume" && volume.source) refs2.add(volume.source);
1043
- } else if (typeof ref === "string") refs2.add(ref);
1044
- else if (ref && typeof ref === "object" && typeof ref.source === "string") refs2.add(ref.source);
1242
+ if (volume?.type === "volume" && volume.source) refs.add(volume.source);
1243
+ } else if (typeof ref === "string") refs.add(ref);
1244
+ else if (ref && typeof ref === "object" && typeof ref.source === "string") refs.add(ref.source);
1045
1245
  }
1046
- else if (value && typeof value === "object") for (const name of Object.keys(value)) refs2.add(name);
1246
+ else if (value && typeof value === "object") for (const name of Object.keys(value)) refs.add(name);
1047
1247
  const names = /* @__PURE__ */ new Map(), mapped = {};
1048
1248
  for (const [name, definition] of Object.entries(defs)) {
1049
- if (!refs2.has(name)) fail(`${kind}.${name}`, "override resource must be consumed by app");
1249
+ if (!refs.has(name)) fail(`${kind}.${name}`, "override resource must be consumed by app");
1050
1250
  const prefix = context.resourceNamespace && context.resourceNamespace !== "app" ? `svc--${context.resourceNamespace}--app-override` : "app-override";
1051
1251
  const target = allocator.allocate(JSON.stringify(["service", context.resourceNamespace ?? "app", "override", context.stage, kind, name]), `${prefix}--${context.stage}--${kind.slice(0, -1)}--${name}`);
1052
1252
  names.set(name, target);
1053
- mapped[target] = definition;
1253
+ mapped[target] = namespaceResourceDefinition(name, definition);
1054
1254
  }
1055
1255
  if (names.size) resources[kind] = mapped;
1056
1256
  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);
@@ -1059,18 +1259,50 @@ function validateAndPrepareAppOverride(document, context) {
1059
1259
  return { app, resources };
1060
1260
  }
1061
1261
 
1062
- // src/core/composition/dependencyLifecycle.ts
1063
- function asMap(value) {
1064
- if (Array.isArray(value)) return Object.fromEntries(value.filter((v) => typeof v === "string").map((v) => [v, {}]));
1065
- if (value && typeof value === "object") return value;
1066
- return {};
1262
+ // src/core/composition/mergeAppOverride.ts
1263
+ function isMap(value) {
1264
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
1265
+ const prototype = Object.getPrototypeOf(value);
1266
+ return prototype === Object.prototype || prototype === null;
1267
+ }
1268
+ function mergeValue(inherited, overlay) {
1269
+ if (overlay === void 0) return structuredClone(inherited);
1270
+ if (!isMap(inherited) || !isMap(overlay)) return structuredClone(overlay);
1271
+ return Object.fromEntries(
1272
+ [.../* @__PURE__ */ new Set([...Object.keys(inherited), ...Object.keys(overlay)])].map((key) => [
1273
+ key,
1274
+ Object.hasOwn(overlay, key) ? mergeValue(inherited[key], overlay[key]) : structuredClone(inherited[key])
1275
+ ])
1276
+ );
1277
+ }
1278
+ function mergeAppOverride(inherited, overlay) {
1279
+ return mergeValue(inherited, overlay);
1280
+ }
1281
+
1282
+ // src/core/composition/composeDependsOn.ts
1283
+ function normalizeComposeDependsOn(value) {
1284
+ const entries2 = Array.isArray(value) ? value.filter((item) => typeof item === "string").map((name) => [name, {}]) : value && typeof value === "object" ? Object.entries(value) : [];
1285
+ return Object.fromEntries(entries2.map(([name, options]) => [
1286
+ name,
1287
+ {
1288
+ ...options && typeof options === "object" && !Array.isArray(options) ? options : {},
1289
+ condition: "service_healthy"
1290
+ }
1291
+ ]));
1292
+ }
1293
+ function enforceHealthyDependsOn(document) {
1294
+ for (const service of Object.values(document.services ?? {})) {
1295
+ if (service.depends_on === void 0) continue;
1296
+ service.depends_on = normalizeComposeDependsOn(service.depends_on);
1297
+ }
1067
1298
  }
1299
+
1300
+ // src/core/composition/dependencyLifecycle.ts
1068
1301
  function healthyMerge(target, owners) {
1069
- const current = asMap(target.depends_on);
1302
+ const current = normalizeComposeDependsOn(target.depends_on);
1070
1303
  for (const owner of owners) {
1071
1304
  const old = current[owner];
1072
- const cond = old && typeof old === "object" ? old.condition : void 0;
1073
- current[owner] = { ...old && typeof old === "object" ? old : {}, condition: cond === "service_healthy" ? cond : "service_healthy" };
1305
+ current[owner] = { ...old && typeof old === "object" ? old : {}, condition: "service_healthy" };
1074
1306
  }
1075
1307
  target.depends_on = current;
1076
1308
  }
@@ -1113,13 +1345,13 @@ function buildStandaloneDependencyEndpoints(key, build, serviceNames, materializ
1113
1345
  function getExecutionProfile(stage, full) {
1114
1346
  switch (stage) {
1115
1347
  case "dev":
1116
- return { configStage: "dev", appTarget: "dev", runtimeStage: "dev", integrated: full, attachTester: false };
1348
+ return { configStage: "dev", envStage: "dev", appTarget: "dev", execMode: "dev", infraMode: full ? "integrated" : "isolated", attachTester: false };
1117
1349
  case "prod":
1118
- return { configStage: "prod", appTarget: "prod", runtimeStage: "prod", integrated: true, attachTester: false };
1350
+ return { configStage: "prod", envStage: "prod", appTarget: "prod", execMode: "prod", infraMode: "integrated", attachTester: false };
1119
1351
  case "test":
1120
- return { configStage: "test", appTarget: "test", runtimeStage: "test", integrated: false, attachTester: false };
1352
+ return { configStage: "test", envStage: "test", appTarget: "test", execMode: "test", infraMode: "isolated", attachTester: false };
1121
1353
  case "e2e":
1122
- return { configStage: "e2e", appTarget: "prod", runtimeStage: "e2e", integrated: true, attachTester: true, testerTarget: "test-e2e" };
1354
+ return { configStage: "e2e", envStage: "e2e", appTarget: "prod", execMode: "prod", infraMode: "integrated", attachTester: true, testerTarget: "test-e2e" };
1123
1355
  }
1124
1356
  }
1125
1357
  function mergeDocument(target, source, context) {
@@ -1128,7 +1360,7 @@ function mergeDocument(target, source, context) {
1128
1360
  if (!src) continue;
1129
1361
  const dst = target[section] ??= {};
1130
1362
  for (const [key, value] of Object.entries(src)) {
1131
- if (key in dst) throw new ConfigError({ configPath: `${section}.${key}`, referencedObject: context, reason: "Internal Compose namespace collision" });
1363
+ if (key in dst) throw new ConfigError({ ...context, configPath: `${context.configPath}.${section}.${key}`, value: key, reason: "Internal Compose namespace collision" });
1132
1364
  dst[key] = value;
1133
1365
  }
1134
1366
  }
@@ -1142,24 +1374,22 @@ function getTemplateSeed(stage, meshMode) {
1142
1374
  if (meshMode) delete merged.services.tester;
1143
1375
  return merged;
1144
1376
  }
1145
- function ownEnv(build, stage) {
1146
- const env = { ...build.app.env };
1147
- const reserved = ["EXEC_MODE", "INFRA_MODE", ...getPrimaryEndpoint(build.app.endpoints) ? ["PORT"] : []];
1148
- for (const key of reserved) if (key in env) throw new ConfigError({ sourceFile: "build.json", configPath: "app.env", stage, composition: "service", value: key, reason: "Application env cannot set a Builder-owned key" });
1149
- return env;
1150
- }
1151
- function resolveEnv(input, registry, source) {
1377
+ function resolveEnv(input, registry, baseContext) {
1152
1378
  const out = {};
1153
1379
  for (const [key, value] of Object.entries(input)) {
1154
- collectBuilderReferences(value, "build", `${source}.${key}`);
1155
- out[key] = interpolateBuilderReferences(value, "build", registry).replace(/\$/g, "$$$$");
1380
+ if (value === null) {
1381
+ out[key] = null;
1382
+ continue;
1383
+ }
1384
+ const context = { ...baseContext, configPath: `${baseContext.configPath}.${key}` };
1385
+ out[key] = interpolateBuilderReferences(value, "build", registry, context).replace(/\$/g, "$$$$");
1156
1386
  }
1157
1387
  return out;
1158
1388
  }
1159
- function addPorts(service, endpointPairs) {
1389
+ function addPorts(service, endpointPairs, sourceFile, stage) {
1160
1390
  for (const [ep, hostPort] of endpointPairs) {
1161
1391
  const ports = Array.isArray(service.ports) ? service.ports : [];
1162
- if (ports.some((p) => p && typeof p === "object" && p.published === hostPort)) throw new ConfigError({ configPath: ep.logicalPath, stage: "service", value: hostPort, reason: "Duplicate host port publication" });
1392
+ 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" });
1163
1393
  ports.push({ target: ep.networkPort, published: hostPort, host_ip: PUBLIC_HOST, protocol: "tcp" });
1164
1394
  service.ports = ports;
1165
1395
  }
@@ -1174,21 +1404,24 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1174
1404
  const namespaced = {};
1175
1405
  for (const [key, dep] of Object.entries(effective.dependencies).sort(([a], [b]) => a.localeCompare(b))) {
1176
1406
  const sourcePath = resolveInsideProject(root, dep.compose, { sourceFile: buildPath, configPath: `dependencies.${key}.compose`, stage });
1177
- const document = rebaseComposePaths(loadComposeDocument(sourcePath, { sourceFile: buildPath, configPath: `dependencies.${key}.compose`, stage, composition: "service" }), sourcePath, options.composeOutputDir ?? root);
1407
+ const rawDocument = loadComposeDocument(sourcePath, { sourceFile: buildPath, configPath: `dependencies.${key}.compose`, stage, composition: "service" });
1408
+ const document = rebaseComposePaths(rawDocument, sourcePath, options.composeOutputDir ?? root);
1178
1409
  validateDependencyCompose(key, dep, document, { composePath: sourcePath, stage });
1179
1410
  if (Object.keys(dep.endpoints).length) {
1180
1411
  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]) });
1181
- namespaced[key] = { doc: ns.document, map: ns.serviceNameMap, source: sourcePath };
1412
+ namespaced[key] = { doc: ns.document, raw: rawDocument, map: ns.serviceNameMap, source: sourcePath };
1182
1413
  }
1183
1414
  }
1184
1415
  const materialized = {};
1185
1416
  const compose = { ...seed, ...options.meshMode ? {} : { name: projectName }, services: { ...seed.services } };
1186
1417
  let app = compose.services.app ?? (compose.services.app = { build: { context: "." } });
1187
- if (profile.integrated) for (const [key, entry] of Object.entries(namespaced)) {
1418
+ if (profile.infraMode === "integrated") for (const [key, entry] of Object.entries(namespaced)) {
1188
1419
  if (options.suppressDependencies?.has(key)) continue;
1420
+ validateMaterializedComposeFiles(entry.raw, entry.source, stage);
1421
+ validateMaterializedComposeBuildInputs(entry.raw, entry.source, stage, "service");
1189
1422
  const dep = effective.dependencies[key];
1190
1423
  const item = structuredClone(entry.doc);
1191
- mergeDocument(compose, item, `dependency ${key}`);
1424
+ mergeDocument(compose, item, { sourceFile: entry.source, configPath: `dependencies.${key}.compose`, stage, composition: "service" });
1192
1425
  const endpointOwnerMap = /* @__PURE__ */ new Map();
1193
1426
  for (const [epName, ep] of Object.entries(dep.endpoints)) endpointOwnerMap.set(epName, entry.map.get(ep.service));
1194
1427
  const endpointOwners = new Set(endpointOwnerMap.values());
@@ -1216,7 +1449,7 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1216
1449
  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 });
1217
1450
  }
1218
1451
  }
1219
- const allocation = allocateHostPorts(root, stage, intents, Boolean(options.validationMode));
1452
+ const allocation = allocateHostPorts(root, stage, intents, Boolean(options.validationMode), { sourceFile: buildPath, composition: "service" });
1220
1453
  for (const [name, ep] of Object.entries(appEndpoints)) if (allocation.has(ep.logicalPath)) {
1221
1454
  ep.publicHost = PUBLIC_HOST;
1222
1455
  ep.publicPort = allocation.get(ep.logicalPath);
@@ -1227,32 +1460,49 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1227
1460
  ep.publicPort = allocation.get(ep.logicalPath);
1228
1461
  ep.effectivelyPublished = true;
1229
1462
  }
1230
- const registry = (ref) => {
1463
+ const registry = (ref, context) => {
1231
1464
  if (ref.target === "app") {
1232
1465
  const ep2 = appEndpoints[ref.endpoint];
1233
- if (!ep2) throw new ConfigError({ sourceFile: buildPath, configPath: ref.raw, stage, composition: "service", referencedObject: ref.raw, reason: "Unknown app endpoint reference" });
1234
- return resolveEndpointProperty(ep2, ref.property, { sourceFile: buildPath, configPath: ref.raw, stage });
1466
+ if (!ep2) throw new ConfigError({ ...context, referencedObject: ref.raw, reason: "Unknown app endpoint reference" });
1467
+ return resolveEndpointProperty(ep2, ref.property, { ...context, referencedObject: ref.raw });
1235
1468
  }
1236
1469
  const ep = depEndpoints[ref.dependency]?.[ref.endpoint];
1237
- if (!ep) throw new ConfigError({ sourceFile: buildPath, configPath: ref.raw, stage, composition: "service", referencedObject: ref.raw, reason: "Unknown dependency endpoint reference" });
1238
- return resolveEndpointProperty(ep, ref.property, { sourceFile: buildPath, configPath: ref.raw, stage });
1470
+ if (!ep) throw new ConfigError({ ...context, referencedObject: ref.raw, reason: "Unknown dependency endpoint reference" });
1471
+ return resolveEndpointProperty(ep, ref.property, { ...context, referencedObject: ref.raw });
1239
1472
  };
1240
1473
  for (const [key, dep] of Object.entries(effective.dependencies)) {
1241
- const depEnv = options.deferReferenceResolution ? dep.env : resolveEnv(dep.env, registry, `dependencies.${key}.env`);
1474
+ const depEnv = options.deferReferenceResolution ? dep.env : resolveEnv(dep.env, registry, { sourceFile: buildPath, configPath: `dependencies.${key}.env`, stage, composition: "service" });
1242
1475
  for (const svc of Object.values(materialized[key]?.compose.services ?? {})) mergeComposeEnvironment(svc, depEnv);
1243
1476
  }
1244
- const buildJsonAppEnvironment = ownEnv(effective, stage);
1245
- const appEnv = options.deferReferenceResolution ? buildJsonAppEnvironment : resolveEnv(buildJsonAppEnvironment, registry, "app.env");
1246
- let overrideComposeAppEnvironment = {};
1247
- const runtimeDotenv = path.join(root, `.env.${profile.runtimeStage}`);
1248
- if (fs.existsSync(runtimeDotenv)) {
1249
- const text = fs.readFileSync(runtimeDotenv, "utf8");
1250
- for (const line of text.split(/\r?\n/)) {
1251
- const match = line.match(/^\s*(?:export\s+)?(EXEC_MODE|INFRA_MODE|PORT)\s*=/);
1252
- if (match && (match[1] !== "PORT" || getPrimaryEndpoint(effective.app.endpoints))) throw new ConfigError({ sourceFile: runtimeDotenv, configPath: match[1], stage, composition: "service", reason: "Dotenv file cannot define Builder-owned environment" });
1477
+ const appEnvironmentLayers = [];
1478
+ for (const layer of effective.layers) {
1479
+ if (Object.keys(layer.appEnv).length) {
1480
+ const configPath = layer.stage === "base" ? "app.env" : `${layer.stage}.app.env`;
1481
+ assertNoBuilderOwnedEnvKeys(layer.appEnv, [EXEC_MODE_KEY, INFRA_MODE_KEY, ...getPrimaryEndpoint(effective.app.endpoints) ? [PORT_KEY] : []], { sourceFile: buildPath, configPath, stage, composition: "service" });
1482
+ appEnvironmentLayers.push({ kind: "build-json", stage: layer.stage, configPath, values: { ...layer.appEnv } });
1483
+ }
1484
+ }
1485
+ const resolveAppLayers = () => {
1486
+ const result = {};
1487
+ const laterKeys = new Set(Object.keys(options.externalAppEnv ?? {}));
1488
+ for (const [key, layer] of selectAppEnvironmentEntries(appEnvironmentLayers, laterKeys)) {
1489
+ if (layer.kind === "build-json") {
1490
+ const context = {
1491
+ sourceFile: buildPath,
1492
+ configPath: layer.configPath,
1493
+ stage,
1494
+ composition: "service"
1495
+ };
1496
+ result[key] = resolveEnv({ [key]: layer.values[key] }, registry, context)[key];
1497
+ } else {
1498
+ result[key] = layer.values[key];
1499
+ }
1253
1500
  }
1254
- }
1255
- const internal = { EXEC_MODE: profile.runtimeStage, INFRA_MODE: profile.integrated ? "integrated" : "isolated", ...getPrimaryEndpoint(effective.app.endpoints) ? { PORT: String(getPrimaryEndpoint(effective.app.endpoints)[1].port) } : {} };
1501
+ return result;
1502
+ };
1503
+ const runtimeDotenv = path.join(root, `.env.${profile.envStage}`);
1504
+ assertDotenvDoesNotDefineKeys(runtimeDotenv, [EXEC_MODE_KEY, INFRA_MODE_KEY, ...getPrimaryEndpoint(effective.app.endpoints) ? [PORT_KEY] : []], { configPath: `.env.${profile.envStage}`, stage, composition: "service" });
1505
+ const internal = { EXEC_MODE: profile.execMode, INFRA_MODE: profile.infraMode, ...getPrimaryEndpoint(effective.app.endpoints) ? { PORT: String(getPrimaryEndpoint(effective.app.endpoints)[1].port) } : {} };
1256
1506
  const appBuild = app.build && typeof app.build === "object" ? app.build : { context: "." };
1257
1507
  const outputDir = options.composeOutputDir ? path.resolve(options.composeOutputDir) : root;
1258
1508
  const serviceContext = path.relative(outputDir, root).replace(/\\/g, "/") || ".";
@@ -1261,14 +1511,14 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1261
1511
  else delete appBuild.dockerfile;
1262
1512
  appBuild.target = profile.appTarget;
1263
1513
  app.build = appBuild;
1264
- app.env_file = [{ path: options.meshMode ? path.posix.join(serviceContext, `.env.${profile.runtimeStage}`) : `.env.${profile.runtimeStage}`, required: false }];
1265
- app.environment = { ...appEnv, ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
1514
+ app.env_file = [{ path: options.meshMode ? path.posix.join(serviceContext, `.env.${profile.envStage}`) : `.env.${profile.envStage}`, required: false }];
1515
+ app.environment = { ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
1266
1516
  if (stage === "dev") app.volumes = [`${options.meshMode && serviceContext !== "." ? `./${serviceContext}` : "."}:/app`, "/app/node_modules"];
1267
- for (const [name, ep] of Object.entries(appEndpoints)) if (!options.meshMode && ep.effectivelyPublished) addPorts(app, [[ep, ep.publicPort]]);
1517
+ for (const [name, ep] of Object.entries(appEndpoints)) if (!options.meshMode && ep.effectivelyPublished) addPorts(app, [[ep, ep.publicPort]], buildPath, stage);
1268
1518
  for (const [key, dependency] of Object.entries(materialized)) {
1269
1519
  for (const [epName, owner] of dependency.endpointOwnerMap.entries()) {
1270
1520
  const endpoint = depEndpoints[key][epName];
1271
- if (!options.meshMode && endpoint.effectivelyPublished) addPorts(compose.services[owner], [[endpoint, endpoint.publicPort]]);
1521
+ if (!options.meshMode && endpoint.effectivelyPublished) addPorts(compose.services[owner], [[endpoint, endpoint.publicPort]], dependency.composePath, stage);
1272
1522
  }
1273
1523
  for (const owner of dependency.endpointOwners) {
1274
1524
  const svc = compose.services[owner];
@@ -1281,36 +1531,51 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1281
1531
  }
1282
1532
  for (const [epName, ep] of Object.entries(depEndpoints[key])) dependency.endpoints[epName] = ep;
1283
1533
  }
1284
- if (effective.overrideCompose) {
1285
- const overridePath = resolveInsideProject(root, effective.overrideCompose, {
1534
+ for (const layer of effective.layers) {
1535
+ if (!layer.overrideCompose) continue;
1536
+ const overridePath = resolveInsideProject(root, layer.overrideCompose, {
1286
1537
  sourceFile: buildPath,
1287
- configPath: "override-compose",
1538
+ configPath: `${layer.stage}.override-compose`,
1288
1539
  stage
1289
1540
  });
1290
1541
  const loadedOverride = loadComposeDocument(overridePath, {
1291
1542
  sourceFile: buildPath,
1292
- configPath: "override-compose",
1543
+ configPath: `${layer.stage}.override-compose`,
1293
1544
  stage,
1294
1545
  composition: "service"
1295
1546
  });
1296
1547
  const overrideDocument = rebaseAppOverridePaths(loadedOverride, root, outputDir);
1297
1548
  const prepared = validateAndPrepareAppOverride(overrideDocument, {
1298
1549
  file: overridePath,
1299
- stage,
1550
+ stage: layer.stage === "base" ? stage : layer.stage,
1300
1551
  expectedBuildContext: String(appBuild.context),
1301
1552
  buildContextBaseDir: outputDir,
1302
1553
  allocator: nameAllocator,
1303
1554
  resourceNamespace: options.meshMode ? options.appServiceName ?? "app" : "app"
1304
1555
  });
1305
- for (const section of ["volumes", "networks", "configs", "secrets"]) if (prepared.resources[section]) mergeDocument(compose, { services: {}, [section]: prepared.resources[section] }, "app override");
1306
- const rawOverrideEnv = normalizeComposeEnvironment(prepared.app.environment, "override-compose.services.app.environment");
1556
+ validateMaterializedComposeFiles(loadedOverride, overridePath, stage, {
1557
+ baseDir: root,
1558
+ composition: "service"
1559
+ });
1560
+ 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" });
1561
+ const rawOverrideEnv = normalizeComposeEnvironment(prepared.app.environment, `${layer.stage}.override-compose.services.app.environment`);
1307
1562
  const overrideEnv = rawOverrideEnv;
1308
1563
  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" });
1309
- overrideComposeAppEnvironment = { ...overrideEnv };
1310
- const merged = { ...app, ...prepared.app };
1311
- merged.environment = { ...appEnv, ...overrideEnv, ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
1564
+ const overrideStage = layer.stage === "base" ? stage : layer.stage;
1565
+ const stageOrder = { base: 0, dev: 1, prod: 1, test: 1, e2e: 2 };
1566
+ let insertAt = appEnvironmentLayers.findIndex((item) => (stageOrder[item.stage] ?? 0) > (stageOrder[overrideStage] ?? 0));
1567
+ if (insertAt < 0) insertAt = appEnvironmentLayers.length;
1568
+ appEnvironmentLayers.splice(insertAt, 0, { kind: "override-compose", stage: overrideStage, sourceFile: overridePath, configPath: `${layer.stage}.override-compose.services.app.environment`, values: overrideEnv });
1569
+ const preparedApp = { ...prepared.app };
1570
+ delete preparedApp.environment;
1571
+ delete preparedApp.build;
1572
+ const merged = mergeAppOverride(app, preparedApp);
1573
+ merged.environment = { ...app.environment, ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
1312
1574
  const overrideBuild = prepared.app.build && typeof prepared.app.build === "object" ? prepared.app.build : {};
1313
- if (overrideBuild.args !== void 0) appBuild.args = overrideBuild.args;
1575
+ if (overrideBuild.args !== void 0) {
1576
+ const current = appBuild.args, incoming = overrideBuild.args;
1577
+ appBuild.args = current && incoming && typeof current === "object" && typeof incoming === "object" && !Array.isArray(current) && !Array.isArray(incoming) ? { ...current, ...incoming } : incoming;
1578
+ }
1314
1579
  merged.build = appBuild;
1315
1580
  merged.env_file = app.env_file;
1316
1581
  merged.depends_on = app.depends_on;
@@ -1318,19 +1583,28 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1318
1583
  compose.services.app = merged;
1319
1584
  app = merged;
1320
1585
  }
1586
+ if (!options.deferReferenceResolution) {
1587
+ const finalEnv = resolveAppLayers();
1588
+ app.environment = { ...finalEnv, ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
1589
+ }
1321
1590
  if (options.meshMode && options.appServiceName && options.appServiceName !== "app") {
1322
1591
  delete compose.services.app;
1323
1592
  compose.services[options.appServiceName] = app;
1324
1593
  }
1325
- if (profile.integrated) applyDependencyLifecycle(app, materialized, effective);
1594
+ if (profile.infraMode === "integrated") applyDependencyLifecycle(app, materialized, effective);
1326
1595
  if (profile.attachTester && !options.meshMode) {
1596
+ const testerDotenvPath = path.join(root, ".env.e2e-tester"), testerBuilderKeys = [EXEC_MODE_KEY, INFRA_MODE_KEY];
1597
+ assertDotenvDoesNotDefineKeys(testerDotenvPath, testerBuilderKeys, { configPath: ".env.e2e-tester", stage: "e2e", composition: "service" });
1327
1598
  const testerEnvRaw = effective.tester?.env ?? {};
1328
- assertTesterReferencesArePublic(testerEnvRaw, "build", "tester.env");
1329
- const testerEnv = options.deferReferenceResolution ? testerEnvRaw : resolveEnv(testerEnvRaw, registry, "tester.env");
1330
- compose.services.tester = { build: { context: ".", ...raw.dockerfile ? { dockerfile: raw.dockerfile } : {}, target: "test-e2e" }, network_mode: "host", environment: testerEnv, depends_on: { app: { condition: "service_healthy" } } };
1599
+ assertNoBuilderOwnedEnvKeys(testerEnvRaw, testerBuilderKeys, { sourceFile: buildPath, configPath: "tester.env", stage: "e2e", composition: "service" });
1600
+ const testerContext = { sourceFile: buildPath, configPath: "tester.env", stage: "e2e", composition: "service" };
1601
+ assertTesterReferencesArePublic(testerEnvRaw, "build", testerContext);
1602
+ const testerEnv = options.deferReferenceResolution ? testerEnvRaw : resolveEnv(testerEnvRaw, registry, testerContext);
1603
+ 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" } } };
1331
1604
  }
1605
+ enforceHealthyDependsOn(compose);
1332
1606
  nameAllocator.assertUnique();
1333
- return { compose, effectiveBuild: effective, endpoints: { app: appEndpoints, dependencies: depEndpoints }, projectName, ...profile.attachTester && !options.meshMode ? { testerServiceName: "tester" } : {}, buildJsonAppEnvironment, overrideComposeAppEnvironment, 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])) };
1607
+ 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])) };
1334
1608
  }
1335
1609
 
1336
1610
  // src/core/checkers/checkEffectiveServiceStages.ts
@@ -1350,7 +1624,7 @@ function checkInfra(projectDir = process.cwd()) {
1350
1624
  checkDockerfileContract(buildJson, absProjectDir);
1351
1625
  checkYamlFiles(buildJson, absProjectDir);
1352
1626
  checkAllEffectiveServiceStages(absProjectDir);
1353
- console.log(pc22.green("\n\u2705 All V2 service infrastructure and contract checks passed.\n"));
1627
+ console.log(pc15.green("\n\u2705 All V2 service infrastructure and contract checks passed.\n"));
1354
1628
  }
1355
1629
  function checkComposeAvailability() {
1356
1630
  const composeCheck = spawnSync(
@@ -1395,7 +1669,7 @@ function checkDependencies() {
1395
1669
  const count = (networkCheck.stdout || "").trim().split("\n").filter(Boolean).length;
1396
1670
  if (count > 25) {
1397
1671
  console.warn(
1398
- pc22.yellow(
1672
+ pc15.yellow(
1399
1673
  `
1400
1674
  \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.
1401
1675
  To resolve, run "builder prune" or "docker network prune -f", or configure default-address-pools in /etc/docker/daemon.json.
@@ -1434,13 +1708,44 @@ Examples:
1434
1708
  }
1435
1709
  });
1436
1710
  };
1711
+
1712
+ // src/core/mesh/types.ts
1713
+ var MESH_CONFIG_STAGES = ["dev", "prod", "e2e"];
1714
+ var MESH_COMMAND_STAGES = ["dev", "prod", "test", "test-e2e"];
1715
+
1716
+ // src/core/config/meshStageContract.ts
1717
+ 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.";
1718
+ function assertNoLegacyMeshTest(input, sourceFile) {
1719
+ if (input !== null && typeof input === "object" && !Array.isArray(input) && Object.prototype.hasOwnProperty.call(input, "test")) {
1720
+ throw new ConfigError({
1721
+ sourceFile,
1722
+ configPath: "test",
1723
+ composition: "mesh",
1724
+ reason: REMOVED_MESH_TEST_MESSAGE
1725
+ });
1726
+ }
1727
+ }
1728
+ function assertMeshConfigStage(stage, sourceFile) {
1729
+ if (typeof stage !== "string" || !MESH_CONFIG_STAGES.includes(stage)) {
1730
+ throw new ConfigError({
1731
+ sourceFile,
1732
+ configPath: "<stage>",
1733
+ composition: "mesh",
1734
+ reason: "Unsupported mesh configuration stage. Supported stages: dev, prod, e2e. test is a pipeline command, not a mesh configuration stage."
1735
+ });
1736
+ }
1737
+ }
1738
+ function meshStageOverlayChain(stage) {
1739
+ return stage === "e2e" ? ["prod", "e2e"] : [stage];
1740
+ }
1437
1741
  var identifierSchema2 = z.string().regex(BUILDER_IDENTIFIER_PATTERN, "must match ^[a-z][a-z0-9-]*$");
1438
1742
  var serviceNameSchema = identifierSchema2.refine((name) => !RESERVED_MESH_SERVICE_NAMES.has(name), { message: "is reserved and cannot be used as a mesh service name" });
1439
1743
  var envSchema2 = z.record(z.string(), z.string());
1440
1744
  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();
1441
1745
  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();
1442
1746
  var meshStageSchema = z.object({ services: z.record(serviceNameSchema, meshServiceStageOverlaySchema).optional() }).strict();
1443
- var meshSchema = z.object({ $schema: z.string().optional(), name: z.string().optional(), tester: z.object({ compose: z.string().min(1), service: z.string().min(1), env: envSchema2.optional() }).strict().optional(), services: z.record(serviceNameSchema, meshServiceSchema), dev: meshStageSchema.optional(), prod: meshStageSchema.optional(), test: meshStageSchema.optional(), e2e: meshStageSchema.optional() }).strict();
1747
+ var rootServicesSchema = z.record(serviceNameSchema, meshServiceSchema).refine((services) => Object.keys(services).length >= 1, { message: "must contain at least one root service" });
1748
+ 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(), e2e: meshStageSchema.optional() }).strict();
1444
1749
 
1445
1750
  // src/core/mesh/getMeshJson.ts
1446
1751
  function getMeshJson(projectDir = process.cwd()) {
@@ -1458,6 +1763,7 @@ function getMeshJson(projectDir = process.cwd()) {
1458
1763
  } catch (err) {
1459
1764
  throw new ScriptError(`Failed to parse mesh.json at ${meshPath}: ${errorMessage(err)}`);
1460
1765
  }
1766
+ assertNoLegacyMeshTest(parsed, meshPath);
1461
1767
  const result = meshSchema.safeParse(parsed);
1462
1768
  if (!result.success) {
1463
1769
  const reason = result.error.issues.map((issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`).join("; ");
@@ -1468,14 +1774,17 @@ function getMeshJson(projectDir = process.cwd()) {
1468
1774
 
1469
1775
  // src/core/config/resolveMeshStage.ts
1470
1776
  function resolveMeshStage(mesh, stage, sourceFile) {
1471
- const overlays = mesh[stage]?.services ?? {}, names = /* @__PURE__ */ new Set([...Object.keys(mesh.services), ...Object.keys(overlays)]), services = {};
1472
- for (const name of names) {
1473
- const base = mesh.services[name], patch = overlays[name];
1474
- const merged = { path: patch?.path ?? base?.path, env: mergeStringMap(base?.env, patch?.env), dependencies: { ...base?.dependencies ?? {}, ...patch?.dependencies ?? {} }, dependsOn: unionStable(base?.dependsOn, patch?.dependsOn), publish: unionStable(base?.publish, patch?.publish) };
1475
- if (!merged.path) throw new ConfigError({ sourceFile, configPath: `services.${name}.path`, stage, composition: "mesh", reason: "Effective mesh service requires path" });
1476
- services[name] = merged;
1777
+ assertNoLegacyMeshTest(mesh, sourceFile);
1778
+ assertMeshConfigStage(stage, sourceFile);
1779
+ 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" });
1780
+ const services = {};
1781
+ 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 ?? []] };
1782
+ for (const overlayStage of meshStageOverlayChain(stage)) for (const [name, patch] of Object.entries(mesh[overlayStage]?.services ?? {})) {
1783
+ const prior = services[name] ?? { path: void 0, env: {}, dependencies: {}, dependsOn: [], publish: [] };
1784
+ 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) };
1477
1785
  }
1478
1786
  if (!Object.keys(services).length) throw new ConfigError({ sourceFile, configPath: "services", stage, composition: "mesh", reason: "At least one effective mesh service is required" });
1787
+ 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" });
1479
1788
  const graph = /* @__PURE__ */ new Map();
1480
1789
  for (const [name, service] of Object.entries(services)) {
1481
1790
  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" });
@@ -1487,12 +1796,8 @@ function resolveMeshStage(mesh, stage, sourceFile) {
1487
1796
  }
1488
1797
  }
1489
1798
  assertAcyclicGraph(graph, { sourceFile, stage, composition: "mesh" });
1490
- const result = { ...mesh, services };
1491
- delete result.dev;
1492
- delete result.prod;
1493
- delete result.test;
1494
- delete result.e2e;
1495
- return result;
1799
+ const { dev: _dev, prod: _prod, e2e: _e2e, ...base } = mesh;
1800
+ return { ...base, services };
1496
1801
  }
1497
1802
  function loadEffectiveMeshServices(meshDir, effectiveMesh, stage) {
1498
1803
  const out = {};
@@ -1553,40 +1858,56 @@ function resolveMeshPublication(services, bindings, stage, meshJsonPath) {
1553
1858
  }
1554
1859
 
1555
1860
  // src/core/mesh/v2/meshReferences.ts
1556
- function resolveMesh(ref, ctx, source) {
1861
+ function resolveMesh(ref, ctx, context) {
1557
1862
  const name = ref.meshService;
1558
- if (!ctx.services[name]) throw new ConfigError({ sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage, composition: "mesh", referencedObject: ref.raw, reason: `Unknown mesh service reference "${name}"` });
1863
+ if (!ctx.services[name]) throw new ConfigError({ ...context, referencedObject: ref.raw, reason: `Unknown mesh service reference "${name}"` });
1559
1864
  const provider = ref.target === "dependency" ? ctx.bindings.get(bindingKey(name, ref.dependency)) : void 0;
1560
- const ep = ref.target === "app" ? ctx.endpoints.app[name]?.[ref.endpoint] : provider ? ctx.endpoints.app[provider]?.[ref.endpoint] : ctx.endpoints.dependencies[name]?.[ref.dependency]?.[ref.endpoint];
1561
- if (!ep) throw new ConfigError({ sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage, composition: "mesh", referencedObject: ref.raw, reason: "Referenced endpoint does not exist" });
1562
- return resolveEndpointProperty(ep, ref.property, { sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage });
1865
+ 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];
1866
+ if (!endpoint) throw new ConfigError({ ...context, referencedObject: ref.raw, reason: "Referenced endpoint does not exist" });
1867
+ return resolveEndpointProperty(endpoint, ref.property, { ...context, referencedObject: ref.raw });
1563
1868
  }
1564
- function resolveBuild(ref, consumer, ctx, source) {
1869
+ function resolveBuild(ref, consumer, ctx, context) {
1565
1870
  const provider = ref.target === "dependency" ? ctx.bindings.get(bindingKey(consumer, ref.dependency)) : void 0;
1566
- const ep = ref.target === "app" ? ctx.endpoints.app[consumer]?.[ref.endpoint] : provider ? ctx.endpoints.app[provider]?.[ref.endpoint] : ctx.endpoints.dependencies[consumer]?.[ref.dependency]?.[ref.endpoint];
1567
- if (!ep) throw new ConfigError({ sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage, composition: "mesh", referencedObject: ref.raw, reason: provider ? `Provider "${provider}" does not expose endpoint "${ref.endpoint}"` : "Referenced endpoint does not exist" });
1871
+ 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];
1872
+ if (!endpoint) {
1873
+ const reason = provider ? `Provider "${provider}" does not expose endpoint "${ref.endpoint}"` : "Referenced endpoint does not exist";
1874
+ throw new ConfigError({ ...context, referencedObject: ref.raw, reason });
1875
+ }
1568
1876
  try {
1569
- return resolveEndpointProperty(ep, ref.property, { sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage });
1877
+ return resolveEndpointProperty(endpoint, ref.property, { ...context, referencedObject: ref.raw });
1570
1878
  } catch (error) {
1571
- if (provider && error instanceof ConfigError) throw new ConfigError({ sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage, composition: "mesh", referencedObject: `${consumer}.dependencies.${ref.dependency}.endpoints.${ref.endpoint}.${ref.property} -> ${provider}.app.endpoints.${ref.endpoint}.${ref.property}`, reason: error.message });
1879
+ if (provider && error instanceof ConfigError) {
1880
+ throw new ConfigError({
1881
+ ...context,
1882
+ referencedObject: `${consumer}.dependencies.${ref.dependency}.endpoints.${ref.endpoint}.${ref.property} -> ${provider}.app.endpoints.${ref.endpoint}.${ref.property}`,
1883
+ reason: error.message
1884
+ });
1885
+ }
1572
1886
  throw error;
1573
1887
  }
1574
1888
  }
1575
- function interpolate(value, scope, resolve, source) {
1576
- const sentinel = "\0DOLLAR\0";
1577
- return value.replace(/\$\$/g, sentinel).replace(/\$\{([^}]*)\}/g, (_whole, body) => {
1578
- const ref = collectBuilderReferences(`\${${body}}`, scope, source)[0];
1579
- return resolve(ref);
1580
- }).replaceAll(sentinel, "$").replace(/\$/g, "$$$$");
1889
+ function interpolate(value, scope, ctx, configPath, consumer) {
1890
+ const context = {
1891
+ sourceFile: scope === "mesh" ? ctx.meshJsonPath : ctx.services[consumer]?.buildJsonPath ?? ctx.meshJsonPath,
1892
+ configPath,
1893
+ stage: ctx.stage,
1894
+ composition: scope === "mesh" ? "mesh" : "service"
1895
+ };
1896
+ return interpolateBuilderReferences(value, scope, (ref, refContext) => scope === "mesh" ? resolveMesh(ref, ctx, refContext) : resolveBuild(ref, consumer, ctx, refContext), context).replace(/\$/g, "$$$$");
1581
1897
  }
1582
1898
  function resolveMeshEnvMap(env, ctx, sourcePrefix) {
1583
- return Object.fromEntries(Object.entries(env).map(([key, value]) => [key, interpolate(value, "mesh", (ref) => resolveMesh(ref, ctx, `${sourcePrefix}.${key}`), `${sourcePrefix}.${key}`)]));
1899
+ return Object.fromEntries(Object.entries(env).map(([key, value]) => [key, interpolate(value, "mesh", ctx, `${sourcePrefix}.${key}`)]));
1584
1900
  }
1585
1901
  function resolveServiceBuildEnvThroughMesh(consumer, env, ctx, sourcePrefix) {
1586
- return Object.fromEntries(Object.entries(env).map(([key, value]) => [key, interpolate(value, "build", (ref) => resolveBuild(ref, consumer, ctx, `${sourcePrefix}.${key}`), `${sourcePrefix}.${key}`)]));
1587
- }
1588
- function assertMeshTesterEnvPublic(env, source) {
1589
- assertTesterReferencesArePublic(env, "mesh", source);
1902
+ return Object.fromEntries(Object.entries(env).map(([key, value]) => [key, interpolate(value, "build", ctx, `${sourcePrefix}.${key}`, consumer)]));
1903
+ }
1904
+ function assertMeshTesterEnvPublic(env, ctx, configPath = "tester.env") {
1905
+ assertTesterReferencesArePublic(env, "mesh", {
1906
+ sourceFile: ctx.meshJsonPath,
1907
+ configPath,
1908
+ stage: ctx.stage,
1909
+ composition: "mesh"
1910
+ });
1590
1911
  }
1591
1912
 
1592
1913
  // src/core/mesh/v2/lifecycle.ts
@@ -1615,98 +1936,101 @@ function applyMeshLifecycleEdges(services, edges) {
1615
1936
  consumer.depends_on = old;
1616
1937
  }
1617
1938
  }
1618
-
1619
- // src/core/composition/composeDependsOn.ts
1620
- function normalizeComposeDependsOn(value) {
1621
- if (Array.isArray(value)) {
1622
- return Object.fromEntries(value.filter((item) => typeof item === "string").map((name) => [name, {}]));
1623
- }
1624
- return value && typeof value === "object" ? { ...value } : {};
1939
+ function appendEnvFile(existing, next) {
1940
+ if (existing === void 0) return [next];
1941
+ return Array.isArray(existing) ? [...existing, next] : [existing, next];
1625
1942
  }
1626
-
1627
- // src/core/mesh/v2/compileMeshTester.ts
1628
- function refs(svc) {
1629
- const out = /* @__PURE__ */ new Set();
1630
- const add = (v) => {
1631
- if (typeof v === "string" && v) out.add(v);
1632
- };
1633
- if (Array.isArray(svc.depends_on)) svc.depends_on.forEach(add);
1634
- else if (svc.depends_on && typeof svc.depends_on === "object") Object.keys(svc.depends_on).forEach(add);
1635
- if (Array.isArray(svc.links)) svc.links.forEach((v) => add(typeof v === "string" ? v.split(":")[0] : v));
1636
- if (Array.isArray(svc.volumes_from)) svc.volumes_from.forEach((v) => add(typeof v === "string" ? v.split(":")[0] : v));
1637
- for (const property of ["network_mode", "ipc", "pid"]) {
1638
- const value = svc[property];
1639
- if (typeof value === "string" && value.startsWith("service:")) add(value.slice("service:".length));
1640
- }
1641
- return [...out];
1642
- }
1643
- function referencedResources(svc, doc) {
1644
- const sets = { volumes: /* @__PURE__ */ new Set(), networks: /* @__PURE__ */ new Set(), configs: /* @__PURE__ */ new Set(), secrets: /* @__PURE__ */ new Set() };
1645
- for (const v of Array.isArray(svc.volumes) ? svc.volumes : []) {
1646
- if (typeof v === "string") {
1647
- const source = v.split(":")[0];
1648
- if (doc.volumes?.[source]) sets.volumes.add(source);
1649
- } else if (v && typeof v === "object" && v.type === "volume" && doc.volumes?.[v.source]) sets.volumes.add(v.source);
1650
- }
1651
- const nets = svc.networks;
1652
- if (Array.isArray(nets)) nets.forEach((n) => {
1653
- if (typeof n === "string" && doc.networks?.[n]) sets.networks.add(n);
1654
- });
1655
- else if (nets && typeof nets === "object") Object.keys(nets).forEach((n) => {
1656
- if (doc.networks?.[n]) sets.networks.add(n);
1657
- });
1658
- for (const kind of ["configs", "secrets"]) {
1659
- const v = svc[kind];
1660
- if (Array.isArray(v)) for (const x of v) {
1661
- const n = typeof x === "string" ? x : x?.source;
1662
- if (typeof n === "string" && doc[kind]?.[n]) sets[kind].add(n);
1943
+ function envFilePaths(value) {
1944
+ const entries2 = Array.isArray(value) ? value : [value];
1945
+ return entries2.flatMap((entry) => typeof entry === "string" ? [entry] : entry && typeof entry === "object" && typeof entry.path === "string" ? [entry.path] : []);
1946
+ }
1947
+ function validateServiceReferences(document, sourceFile, stage) {
1948
+ for (const [name, service] of Object.entries(document.services)) {
1949
+ const refs = [];
1950
+ const add = (value) => {
1951
+ if (typeof value === "string" && value) refs.push(value);
1952
+ };
1953
+ if (Array.isArray(service.depends_on)) service.depends_on.forEach(add);
1954
+ else if (service.depends_on && typeof service.depends_on === "object") Object.keys(service.depends_on).forEach(add);
1955
+ if (Array.isArray(service.links)) service.links.forEach((value) => add(typeof value === "string" ? value.split(":")[0] : void 0));
1956
+ if (Array.isArray(service.volumes_from)) service.volumes_from.forEach((value) => add(typeof value === "string" ? value.split(":")[0] : void 0));
1957
+ for (const key of ["network_mode", "ipc", "pid"]) {
1958
+ const value = service[key];
1959
+ if (typeof value === "string" && value.startsWith("service:")) add(value.slice("service:".length));
1663
1960
  }
1961
+ 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" });
1664
1962
  }
1665
- for (const name of collectBuildSecretReferences(svc)) if (doc.secrets && name in doc.secrets) sets.secrets.add(name);
1666
- return sets;
1963
+ }
1964
+ function applyTesterBuildTarget(service) {
1965
+ if (service.build === void 0) return;
1966
+ if (typeof service.build === "string") {
1967
+ service.build = { context: service.build, target: "test-e2e" };
1968
+ return;
1969
+ }
1970
+ if (service.build && typeof service.build === "object" && !Array.isArray(service.build)) service.build = { ...service.build, target: "test-e2e" };
1667
1971
  }
1668
1972
  function compileMeshTester(meshDir, tester, endpointRegistry, effectiveTopLevelApps, stage, referenceContext, nameAllocator = new GeneratedComposeNameAllocator(effectiveTopLevelApps)) {
1669
- const meshPath = `${meshDir}/mesh.json`, file = resolveInsideProject(meshDir, tester.compose, { sourceFile: meshPath, configPath: "tester.compose", stage }), raw = rebaseComposePaths(loadComposeDocument(file, { sourceFile: meshPath, configPath: "tester.compose", stage, composition: "mesh" }), file, meshDir);
1973
+ const meshPath = path.join(meshDir, "mesh.json"), file = resolveInsideProject(meshDir, tester.compose, { sourceFile: meshPath, configPath: "tester.compose", stage });
1974
+ const sourceDocument = loadComposeDocument(file, { sourceFile: meshPath, configPath: "tester.compose", stage, composition: "mesh" });
1975
+ const raw = rebaseComposePaths(sourceDocument, file, meshDir);
1670
1976
  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" });
1671
- const included = /* @__PURE__ */ new Set(), visit = (name) => {
1672
- if (included.has(name)) return;
1673
- const service = raw.services[name];
1674
- if (!service) throw new ConfigError({ sourceFile: file, configPath: `services.${name}`, stage, composition: "mesh", reason: "Tester service dependency does not exist" });
1675
- if (service.extends !== void 0) throw new ConfigError({ sourceFile: file, configPath: `services.${name}.extends`, stage, composition: "mesh", reason: "Tester Compose extends is unsupported until effective Compose inheritance can be validated before host-network rewriting" });
1676
- included.add(name);
1677
- for (const ref of refs(service)) visit(ref);
1678
- };
1679
- visit(tester.service);
1680
- validateComposeResourceReferences(raw, { sourceFile: file, stage, composition: "mesh" }, included);
1681
- for (const name of included) {
1682
- const svc = raw.services[name];
1683
- assertNoServiceBuildContexts(svc, `services.${name}`, file);
1684
- if (name !== tester.service && svc.network_mode === "host") throw new ConfigError({ sourceFile: file, configPath: `services.${name}.network_mode`, stage, composition: "mesh", reason: "Only the selected tester runner may use host networking" });
1685
- if (name === tester.service && svc.network_mode !== void 0 && svc.network_mode !== "host") throw new ConfigError({ sourceFile: file, configPath: `services.${name}.network_mode`, stage, composition: "mesh", reason: "Selected tester runner must be compatible with host networking" });
1686
- if (name === tester.service && svc.networks !== void 0) throw new ConfigError({ sourceFile: file, configPath: `services.${name}.networks`, stage, composition: "mesh", reason: "Selected host-network tester runner cannot declare networks" });
1687
- }
1688
- const res = { volumes: /* @__PURE__ */ new Set(), networks: /* @__PURE__ */ new Set(), configs: /* @__PURE__ */ new Set(), secrets: /* @__PURE__ */ new Set() };
1689
- for (const name of included) {
1690
- const own = referencedResources(raw.services[name], raw);
1691
- for (const k of Object.keys(res)) for (const v of own[k]) res[k].add(v);
1692
- }
1693
- const selected = { services: Object.fromEntries([...included].map((k) => [k, raw.services[k]])) };
1694
- for (const k of Object.keys(res)) if (res[k].size) selected[k] = Object.fromEntries([...res[k]].map((n) => [n, raw[k]?.[n]]));
1695
- const ns = namespaceDependencyCompose({ dependencyKey: "mesh-tester", namespacePrefix: "mesh-tester", document: selected, allocator: nameAllocator, identityPrefix: JSON.stringify(["mesh-tester"]) });
1977
+ validateComposeResourceReferences(raw, { sourceFile: file, stage, composition: "mesh" });
1978
+ validateServiceReferences(raw, file, stage);
1979
+ assertComposeLifecycleAcyclic(raw.services, {
1980
+ sourceFile: file,
1981
+ stage,
1982
+ composition: "mesh"
1983
+ });
1984
+ for (const [serviceName, service] of Object.entries(raw.services)) {
1985
+ 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" });
1986
+ assertNoServiceBuildContexts(service, `services.${serviceName}`, file);
1987
+ }
1988
+ const selectedRaw = raw.services[tester.service];
1989
+ 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" });
1990
+ 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" });
1991
+ 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" });
1992
+ validateMaterializedComposeFiles(sourceDocument, file, stage, { composition: "mesh" });
1993
+ validateMaterializedComposeBuildInputs(sourceDocument, file, stage, "mesh");
1994
+ const meshCtx = referenceContext ?? { services: {}, bindings: /* @__PURE__ */ new Map(), endpoints: endpointRegistry, stage, meshJsonPath: meshPath };
1995
+ const testerBuilderKeys = [EXEC_MODE_KEY, INFRA_MODE_KEY], rawRunnerEnvironment = normalizeComposeEnvironment(selectedRaw.environment, "tester runner environment");
1996
+ assertNoBuilderOwnedEnvKeys(rawRunnerEnvironment, testerBuilderKeys, { sourceFile: file, configPath: `services.${tester.service}.environment`, stage, composition: "mesh" });
1997
+ for (const envFile of envFilePaths(selectedRaw.env_file)) assertDotenvDoesNotDefineKeys(path.resolve(meshDir, envFile), testerBuilderKeys, { configPath: `services.${tester.service}.env_file`, stage, composition: "mesh" });
1998
+ const meshTesterDotenv = path.join(meshDir, ".env.e2e-tester");
1999
+ assertDotenvDoesNotDefineKeys(meshTesterDotenv, testerBuilderKeys, { configPath: ".env.e2e-tester", stage, composition: "mesh" });
2000
+ const testerEnv = tester.env ?? {};
2001
+ assertNoBuilderOwnedEnvKeys(testerEnv, testerBuilderKeys, { sourceFile: meshPath, configPath: "tester.env", stage, composition: "mesh" });
2002
+ assertMeshTesterEnvPublic(testerEnv, meshCtx);
2003
+ const ns = namespaceDependencyCompose({ dependencyKey: "mesh-tester", namespacePrefix: "mesh-tester", document: raw, allocator: nameAllocator, identityPrefix: JSON.stringify(["mesh-tester"]) });
1696
2004
  const runner = ns.serviceNameMap.get(tester.service);
1697
2005
  const runnerSvc = ns.document.services[runner];
1698
- if (runnerSvc.ports !== void 0) throw new ConfigError({ sourceFile: file, configPath: `services.${tester.service}.ports`, stage, composition: "mesh", reason: "Selected host-network tester runner cannot define ports" });
2006
+ applyTesterBuildTarget(runnerSvc);
1699
2007
  runnerSvc.network_mode = "host";
1700
2008
  delete runnerSvc.networks;
1701
- const meshCtx = referenceContext ?? { services: {}, bindings: /* @__PURE__ */ new Map(), endpoints: endpointRegistry, stage, meshJsonPath: meshPath };
1702
- const env = tester.env ?? {};
1703
- assertMeshTesterEnvPublic(env, "tester.env");
1704
- runnerSvc.environment = { ...normalizeComposeEnvironment(runnerSvc.environment, "tester runner environment"), ...resolveMeshEnvMap(env, meshCtx, "tester.env") };
2009
+ runnerSvc.env_file = appendEnvFile(runnerSvc.env_file, { path: ".env.e2e-tester", required: false });
2010
+ runnerSvc.environment = { ...normalizeComposeEnvironment(runnerSvc.environment, "tester runner environment"), ...resolveMeshEnvMap(testerEnv, meshCtx, "tester.env"), EXEC_MODE: "e2e" };
1705
2011
  const depends = normalizeComposeDependsOn(runnerSvc.depends_on);
1706
2012
  for (const app of effectiveTopLevelApps) depends[app] = { condition: "service_healthy" };
1707
2013
  runnerSvc.depends_on = depends;
1708
2014
  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 };
1709
2015
  }
2016
+
2017
+ // src/core/mesh/v2/resolveMeshAppEnvironment.ts
2018
+ function resolveMeshAppEnvironmentLayers(serviceName, layers, context, laterKeys = /* @__PURE__ */ new Set()) {
2019
+ const result = {};
2020
+ for (const [key, layer] of selectAppEnvironmentEntries(layers, laterKeys)) {
2021
+ if (layer.kind === "build-json") {
2022
+ result[key] = resolveServiceBuildEnvThroughMesh(
2023
+ serviceName,
2024
+ { [key]: layer.values[key] },
2025
+ context,
2026
+ `services.${serviceName}.${layer.configPath}`
2027
+ )[key];
2028
+ } else {
2029
+ result[key] = layer.values[key];
2030
+ }
2031
+ }
2032
+ return result;
2033
+ }
1710
2034
  function validPort(value) {
1711
2035
  if (!/^\d+$/.test(value)) return void 0;
1712
2036
  const port = Number(value);
@@ -1830,7 +2154,10 @@ function compileMeshComposition(stage, meshDir, options = {}) {
1830
2154
  for (const ep of Object.values(fragment.endpoints.dependencies[dep] ?? {})) {
1831
2155
  const owner = ep.networkHost;
1832
2156
  const ownerService = compose.services[owner];
1833
- if (ownerService) attachNetworkIfCompatible(ownerService, privateName);
2157
+ if (ownerService) {
2158
+ attachNetworkIfCompatible(ownerService, privateName);
2159
+ attachNetworkIfCompatible(ownerService, "mesh");
2160
+ }
1834
2161
  }
1835
2162
  for (const generated of fragment.dependencyServiceNames?.[dep] ?? []) {
1836
2163
  const ownerService = compose.services[generated];
@@ -1840,7 +2167,7 @@ function compileMeshComposition(stage, meshDir, options = {}) {
1840
2167
  }
1841
2168
  app.networks = { ...normalizeNetworks(app.networks), ...networks };
1842
2169
  }
1843
- const publication = resolveMeshPublication(services, bindingMap, stage, meshPath), intents = buildMeshPortIntents(services, publication), ports = allocateHostPorts(meshDir, stage, intents, Boolean(options.validationMode));
2170
+ const publication = resolveMeshPublication(services, bindingMap, stage, meshPath), intents = buildMeshPortIntents(services, publication), ports = allocateHostPorts(meshDir, stage, intents, Boolean(options.validationMode), { sourceFile: meshPath, composition: "mesh" });
1844
2171
  const endpoints = { app: {}, dependencies: {} };
1845
2172
  for (const [name, svc] of Object.entries(services)) {
1846
2173
  endpoints.app[name] = {};
@@ -1877,9 +2204,9 @@ function compileMeshComposition(stage, meshDir, options = {}) {
1877
2204
  const refContext = { services, bindings: bindingMap, endpoints, stage, meshJsonPath: meshPath };
1878
2205
  for (const [name, fragment] of Object.entries(fragments)) {
1879
2206
  const app = compose.services[name];
1880
- const buildEnv = resolveServiceBuildEnvThroughMesh(name, fragment.buildJsonAppEnvironment ?? {}, refContext, `services.${name}.app.env`);
1881
2207
  const meshEnv = resolveMeshEnvMap(fragment.externalAppEnvironment ?? {}, refContext, `services.${name}.env`);
1882
- app.environment = { ...buildEnv, ...fragment.overrideComposeAppEnvironment ?? {}, ...meshEnv, ...fragment.builderInternalEnvironment ?? {} };
2208
+ const serviceEnv = resolveMeshAppEnvironmentLayers(name, fragment.appEnvironmentLayers, refContext, new Set(Object.keys(meshEnv)));
2209
+ app.environment = { ...serviceEnv, ...meshEnv, ...fragment.builderInternalEnvironment ?? {} };
1883
2210
  for (const [depName, depEnv] of Object.entries(fragment.dependencyEnvironments ?? {})) {
1884
2211
  const logicalBinding = bindingMap.get(bindingKey(name, depName));
1885
2212
  if (logicalBinding) continue;
@@ -1929,106 +2256,33 @@ function compileMeshComposition(stage, meshDir, options = {}) {
1929
2256
  testerServiceName = built.runnerServiceName;
1930
2257
  }
1931
2258
  }
2259
+ enforceHealthyDependsOn(compose);
1932
2260
  nameAllocator.assertUnique();
1933
2261
  const yaml = stringify(compose);
1934
2262
  assertUniqueHostPortMappings(yaml);
1935
2263
  return { compose, effectiveMesh: effective, loadedServices: services, endpoints, projectName, ...testerServiceName ? { testerServiceName } : {} };
1936
2264
  }
1937
2265
 
1938
- // src/core/mesh/v2/validateMeshTestStage.ts
1939
- function validateMeshTestStage(services, meshDir, meshPath, validationMode = false) {
1940
- const bindings = bindingsMap(buildDependencyBindings(services, "test", meshPath));
1941
- const publication = resolveMeshPublication(
1942
- services,
1943
- bindings,
1944
- "test",
1945
- meshPath
1946
- );
1947
- for (const pub of publication) {
1948
- if (pub.target === "dependency") {
1949
- throw new ConfigError({
1950
- sourceFile: meshPath,
1951
- configPath: `services.${pub.ownerMeshService}.publish`,
1952
- stage: "test",
1953
- composition: "mesh",
1954
- value: pub.logicalPath,
1955
- reason: "mesh.test is isolated; dependency endpoints are not materialized and cannot be published"
1956
- });
1957
- }
1958
- }
1959
- const appPublications = publication.filter((pub) => pub.target === "app").sort(
1960
- (a, b) => a.ownerMeshService.localeCompare(b.ownerMeshService) || a.endpoint.localeCompare(b.endpoint)
1961
- ).map((pub) => {
1962
- const endpoint = services[pub.ownerMeshService].effectiveBuild.app.endpoints[pub.endpoint];
1963
- return {
1964
- meshService: pub.ownerMeshService,
1965
- endpoint: pub.endpoint,
1966
- logicalPath: pub.logicalPath,
1967
- containerPort: endpoint.port,
1968
- requested: endpoint.publicPort
1969
- };
1970
- });
1971
- const intents = appPublications.map((pub) => ({
1972
- logicalPath: pub.logicalPath,
1973
- requested: pub.requested
1974
- }));
1975
- const allocatedPorts = allocateHostPorts(
1976
- meshDir,
1977
- "test",
1978
- intents,
1979
- validationMode
1980
- );
1981
- return { bindings, appPublications, allocatedPorts };
1982
- }
1983
- function applyTestAppPublications(validated, meshService, app, endpointRegistry) {
1984
- for (const publication of validated.appPublications) {
1985
- if (publication.meshService !== meshService) continue;
1986
- const published = validated.allocatedPorts.get(publication.logicalPath);
1987
- const ports = Array.isArray(app.ports) ? app.ports : [];
1988
- ports.push({
1989
- target: publication.containerPort,
1990
- published,
1991
- host_ip: PUBLIC_HOST,
1992
- protocol: "tcp"
1993
- });
1994
- app.ports = ports;
1995
- const endpoint = endpointRegistry[publication.endpoint];
1996
- if (endpoint) {
1997
- endpoint.publicHost = PUBLIC_HOST;
1998
- endpoint.publicPort = published;
1999
- endpoint.effectivelyPublished = true;
2000
- }
2001
- }
2002
- }
2003
-
2004
2266
  // src/core/mesh/checkers/checkMeshServices.ts
2005
2267
  function checkMeshServices(mesh, meshDir) {
2006
- const root = resolveProjectDir(meshDir), meshPath = path.join(root, "mesh.json");
2268
+ const root = resolveProjectDir(meshDir);
2269
+ const meshPath = path.join(root, "mesh.json");
2007
2270
  const checked = /* @__PURE__ */ new Set();
2008
- for (const stage of ["dev", "prod", "test", "e2e"]) {
2271
+ for (const stage of MESH_CONFIG_STAGES) {
2009
2272
  const effective = resolveMeshStage(mesh, stage, meshPath);
2010
2273
  const services = loadEffectiveMeshServices(root, effective, stage);
2011
- if (stage === "test") validateMeshTestStage(services, root, meshPath, true);
2012
2274
  for (const [name, svc] of Object.entries(services)) {
2013
2275
  if (!checked.has(svc.absolutePath)) {
2014
- console.log(pc22.cyan(`
2276
+ console.log(pc15.cyan(`
2015
2277
  \u{1F50D} Checking mesh service ${name}...`));
2016
2278
  checkInfra(svc.absolutePath);
2017
2279
  checked.add(svc.absolutePath);
2018
2280
  }
2019
- if (stage === "test") {
2020
- const fragment = compileServiceComposition("test", svc.absolutePath, { validationMode: true, meshMode: true, deferReferenceResolution: true });
2021
- const endpoints = { app: { [name]: fragment.endpoints.app }, dependencies: { [name]: fragment.endpoints.dependencies } };
2022
- const ctx = { services: { [name]: svc }, bindings: /* @__PURE__ */ new Map(), endpoints, stage: "test", meshJsonPath: meshPath };
2023
- for (const key of ["EXEC_MODE", "INFRA_MODE", ...Object.values(svc.effectiveBuild.app.endpoints).some((ep) => ep.primary) ? ["PORT"] : []]) {
2024
- 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" });
2025
- }
2026
- resolveServiceBuildEnvThroughMesh(name, fragment.buildJsonAppEnvironment ?? {}, ctx, `services.${name}.app.env`);
2027
- for (const [depName, depEnv] of Object.entries(fragment.dependencyEnvironments ?? {})) resolveServiceBuildEnvThroughMesh(name, depEnv, ctx, `services.${name}.dependencies.${depName}.env`);
2028
- resolveMeshEnvMap(svc.meshEnv, ctx, `services.${name}.env`);
2029
- }
2030
2281
  }
2031
- if (stage !== "test") compileMeshComposition(stage, root, { validationMode: true, allowMissingTester: true });
2282
+ compileMeshComposition(stage, root, {
2283
+ validationMode: true,
2284
+ allowMissingTester: true
2285
+ });
2032
2286
  }
2033
2287
  }
2034
2288
  function checkMeshTester(mesh, meshDir, options = {}) {
@@ -2049,8 +2303,8 @@ function checkMesh(meshDir = process.cwd(), options = {}) {
2049
2303
  checkMeshServices(mesh, absMeshDir);
2050
2304
  checkMeshTester(mesh, absMeshDir, { required: Boolean(options.requireTester) });
2051
2305
  console.log(
2052
- pc22.bold(
2053
- pc22.green("\n\u{1F389} All V2 mesh infrastructure, services, and contract checks passed!\n")
2306
+ pc15.bold(
2307
+ pc15.green("\n\u{1F389} All V2 mesh infrastructure, services, and contract checks passed!\n")
2054
2308
  )
2055
2309
  );
2056
2310
  }
@@ -2089,14 +2343,7 @@ Examples:
2089
2343
  }
2090
2344
  });
2091
2345
  };
2092
- function compileMeshEnvironment(stage, rawMeshDir = process.cwd(), options = {}) {
2093
- const meshDir = resolveProjectDir(rawMeshDir), compiled = compileMeshComposition(stage, meshDir), yaml = stringify(compiled.compose);
2094
- if (options.validateWithDocker !== false) {
2095
- const result = spawnSync("docker", ["compose", "--project-directory", meshDir, "-f", "-", "config", "--quiet"], { cwd: meshDir, encoding: "utf-8", input: yaml });
2096
- 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 });
2097
- }
2098
- return { yaml, ...compiled.testerServiceName ? { testerServiceName: compiled.testerServiceName } : {} };
2099
- }
2346
+ var compileEnvironment = (stage, projectDir = process.cwd(), options = {}) => stringify(compileServiceComposition(stage, projectDir, { full: Boolean(options.full), silenceWarnings: options.silenceWarnings }).compose);
2100
2347
  var activeComposeSet = /* @__PURE__ */ new Set();
2101
2348
  var signalHandlersRegistered = false;
2102
2349
  var activeChildProcess = null;
@@ -2170,18 +2417,19 @@ function ensureSignalHandlers() {
2170
2417
  }
2171
2418
  if (isShuttingDown) return;
2172
2419
  isShuttingDown = true;
2173
- for (const item of activeComposeSet) {
2174
- try {
2175
- teardownCompose(item.yamlConfig, item.projectDir, {
2176
- removeVolumes: item.removeVolumes ?? false
2177
- }).catch(() => {
2178
- });
2179
- } catch {
2180
- }
2181
- }
2182
- activeComposeSet.clear();
2183
2420
  const signalNumber = os.constants.signals[signal] ?? 0;
2184
- process.exit(128 + signalNumber);
2421
+ void (async () => {
2422
+ for (const item of activeComposeSet) {
2423
+ try {
2424
+ await teardownCompose(item.yamlConfig, item.projectDir, {
2425
+ removeVolumes: item.removeVolumes ?? false
2426
+ });
2427
+ activeComposeSet.delete(item);
2428
+ } catch (error) {
2429
+ console.error("Compose cleanup failed during signal shutdown:", error);
2430
+ }
2431
+ }
2432
+ })().finally(() => process.exit(128 + signalNumber));
2185
2433
  };
2186
2434
  const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
2187
2435
  for (const sig of SIGNALS) {
@@ -2277,17 +2525,11 @@ async function teardownCompose(yamlConfig, projectDir, options = {}) {
2277
2525
  6e4
2278
2526
  );
2279
2527
  }
2280
- if (result.error) {
2281
- if (!silent) {
2282
- console.error(
2283
- pc22.red(`Failed to run docker compose down: ${result.error.message}`)
2284
- );
2285
- }
2286
- } else if (result.status !== 0 && !silent) {
2287
- console.error(
2288
- pc22.red(
2289
- `Docker compose down exited with non-zero status code: ${result.status}`
2290
- )
2528
+ if (result.error || result.status !== 0) {
2529
+ const detail = result.error?.message ?? `exit code ${result.status ?? "unknown"}`;
2530
+ throw new ScriptError(
2531
+ `Failed to tear down Compose project in ${absProjectDir} after two attempts: ${detail}`,
2532
+ result.error ? { cause: result.error } : void 0
2291
2533
  );
2292
2534
  }
2293
2535
  } finally {
@@ -2380,111 +2622,208 @@ function projectNamesForServiceStage(projectDir, stage) {
2380
2622
  }
2381
2623
  function projectNamesForMeshStage(meshDir, stage) {
2382
2624
  const absDir = resolveProjectDir(meshDir);
2383
- let rawMeshName;
2384
- let serviceNames = [];
2625
+ let rawMeshName = path.basename(absDir);
2385
2626
  try {
2386
- const mesh = getMeshJson(absDir);
2387
- rawMeshName = mesh.name || path.basename(absDir);
2388
- serviceNames = Object.keys(resolveMeshStage(mesh, "test", path.join(absDir, "mesh.json")).services);
2627
+ rawMeshName = getMeshJson(absDir).name || rawMeshName;
2389
2628
  } catch {
2390
- rawMeshName = path.basename(absDir);
2391
2629
  }
2392
2630
  const s = stage.toLowerCase();
2393
- if (s === "dev") {
2394
- return [deriveProjectName(rawMeshName, "dev")];
2395
- }
2396
- if (s === "prod") {
2397
- return [deriveProjectName(rawMeshName, "prod")];
2398
- }
2399
- if (s === "test-e2e") {
2631
+ if (s === "test" || s === "test-e2e") {
2400
2632
  return [deriveProjectName(rawMeshName, "e2e")];
2401
2633
  }
2402
- if (s === "test-unit") {
2403
- return serviceNames.map((name) => `${deriveProjectName(rawMeshName, "dev")}-${name}-test`);
2404
- }
2405
- if (s === "test") {
2406
- return [...serviceNames.map((name) => `${deriveProjectName(rawMeshName, "dev")}-${name}-test`), deriveProjectName(rawMeshName, "e2e")];
2407
- }
2408
2634
  return [deriveProjectName(rawMeshName, s)];
2409
2635
  }
2410
2636
 
2411
- // src/commands/mesh/commands/down/handler.ts
2412
- async function handleMeshDown(rawStage = "dev", options = {}) {
2637
+ // src/commands/service/commands/down/handler.ts
2638
+ async function handleServiceDown(rawStage = "dev", options = {}) {
2639
+ const projectDir = resolveProjectDir(options.projectDir);
2413
2640
  const stage = (rawStage || "dev").toLowerCase();
2414
- const meshDir = resolveProjectDir(options.projectDir);
2415
2641
  const validStages = ["dev", "prod", "test", "test-unit", "test-e2e"];
2416
2642
  if (!validStages.includes(stage)) {
2417
2643
  throw new ScriptError(
2418
- `Unknown mesh stage: "${rawStage}". Supported stages: dev, prod, test, test-unit, test-e2e`
2644
+ `Unknown environment stage: "${rawStage}". Supported stages: dev, prod, test, test-unit, test-e2e`
2419
2645
  );
2420
2646
  }
2421
2647
  console.log(
2422
- pc22.cyan(`
2423
- \u{1F9F9} Stopping and tearing down global mesh environment [${stage}]...`)
2648
+ pc15.cyan(`
2649
+ \u{1F9F9} Stopping and tearing down service environment [${stage}]...`)
2424
2650
  );
2425
2651
  if (options.debug) {
2426
2652
  try {
2427
- const mode = stage === "dev" ? "dev" : stage === "test-e2e" ? "e2e" : "prod";
2428
- const { yaml } = compileMeshEnvironment(mode, meshDir, { validateWithDocker: false });
2653
+ let env = "dev";
2654
+ if (stage === "prod") env = "prod";
2655
+ else if (stage === "test" || stage === "test-unit") env = "test";
2656
+ else if (stage === "test-e2e") env = "e2e";
2657
+ const finalYamlConfig = compileEnvironment(env, projectDir);
2429
2658
  console.log(
2430
- pc22.yellow("\nFinal merged Mesh YAML configuration:\n"),
2431
- redactYamlSecrets(yaml)
2659
+ pc15.yellow("Final merged YAML configuration:\n"),
2660
+ redactYamlSecrets(finalYamlConfig)
2432
2661
  );
2433
2662
  } catch {
2434
2663
  }
2435
2664
  }
2436
- const runState = readRunState(meshDir);
2437
- const candidateProjects = projectNamesForMeshStage(meshDir, stage);
2665
+ const runState = readRunState(projectDir);
2666
+ const candidateProjects = projectNamesForServiceStage(projectDir, stage);
2438
2667
  if (runState?.projectName) {
2439
2668
  candidateProjects.unshift(runState.projectName);
2440
2669
  }
2441
2670
  const uniqueProjects = Array.from(new Set(candidateProjects));
2442
2671
  for (const proj of uniqueProjects) {
2443
- await teardownCompose("", meshDir, {
2672
+ await teardownCompose("", projectDir, {
2444
2673
  projectName: proj,
2445
2674
  ...runState?.projectName === proj && runState.anonymousVolumeServices ? { anonymousVolumeServices: runState.anonymousVolumeServices } : {},
2446
2675
  removeVolumes: Boolean(options.volumes)
2447
2676
  });
2448
2677
  }
2449
- clearRunState(meshDir);
2678
+ clearRunState(projectDir);
2450
2679
  console.log(
2451
- pc22.green(`\u2705 Global mesh environment [${stage}] stopped and removed.
2680
+ pc15.green(`\u2705 Service environment [${stage}] stopped and removed.
2452
2681
  `)
2453
2682
  );
2454
2683
  return 0;
2455
2684
  }
2685
+ function compileMeshEnvironment(stage, rawMeshDir = process.cwd(), options = {}) {
2686
+ const meshDir = resolveProjectDir(rawMeshDir), compiled = compileMeshComposition(stage, meshDir), yaml = stringify(compiled.compose);
2687
+ if (options.validateWithDocker !== false) {
2688
+ const result = spawnSync("docker", ["compose", "--project-directory", meshDir, "-f", "-", "config", "--quiet"], { cwd: meshDir, encoding: "utf-8", input: yaml });
2689
+ 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 });
2690
+ }
2691
+ return { yaml, ...compiled.testerServiceName ? { testerServiceName: compiled.testerServiceName } : {} };
2692
+ }
2456
2693
 
2457
- // src/commands/mesh/commands/down/command.ts
2458
- var registerMeshDownCommand = (cmd) => {
2459
- cmd.command("down [stage]").description(
2460
- "Stop and remove containers and networks for the global mesh environment (dev, prod, test, test-e2e)"
2461
- ).option(
2462
- "-v, --volumes",
2463
- "Remove named volumes declared in the mesh configuration"
2464
- ).option(
2465
- "-C, --project-dir <dir>",
2466
- "Mesh project directory containing mesh.json (defaults to cwd)"
2467
- ).option("--debug", "Output the merged Docker Compose YAML configuration").addHelpText(
2468
- "after",
2469
- `
2470
- Examples:
2471
- $ builder mesh down
2472
- $ builder mesh down dev
2473
- $ builder mesh down prod
2474
- $ builder mesh down -v`
2475
- ).action(
2476
- async (stage = "dev", options = {}) => {
2477
- const exitCode = await handleMeshDown(stage, {
2478
- projectDir: options.projectDir,
2479
- volumes: options.volumes,
2480
- debug: options.debug
2481
- });
2482
- if (exitCode !== 0) {
2483
- process.exit(exitCode);
2694
+ // src/commands/mesh/commands/down/handler.ts
2695
+ function rootServiceDirsForCleanup(meshDir) {
2696
+ try {
2697
+ const mesh = getMeshJson(meshDir);
2698
+ const dirs = Object.entries(mesh.services).sort(([a], [b]) => a.localeCompare(b)).map(([name, service]) => resolveInsideProject(meshDir, service.path, {
2699
+ sourceFile: path.join(meshDir, "mesh.json"),
2700
+ configPath: `services.${name}.path`
2701
+ }));
2702
+ return [...new Set(dirs)];
2703
+ } catch {
2704
+ return [];
2705
+ }
2706
+ }
2707
+ async function handleMeshDown(rawStage = "dev", options = {}) {
2708
+ const stage = (rawStage || "dev").toLowerCase();
2709
+ const meshDir = resolveProjectDir(options.projectDir);
2710
+ if (stage === "test-unit") {
2711
+ throw new ScriptError(
2712
+ "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."
2713
+ );
2714
+ }
2715
+ if (!MESH_COMMAND_STAGES.includes(stage)) {
2716
+ throw new ScriptError(
2717
+ `Unknown mesh stage: "${rawStage}". Supported stages: ${MESH_COMMAND_STAGES.join(", ")}`
2718
+ );
2719
+ }
2720
+ console.log(
2721
+ pc15.cyan(`
2722
+ \u{1F9F9} Stopping and tearing down global mesh environment [${stage}]...`)
2723
+ );
2724
+ if (options.debug) {
2725
+ try {
2726
+ const mode = stage === "dev" ? "dev" : stage === "test" || stage === "test-e2e" ? "e2e" : "prod";
2727
+ const { yaml } = compileMeshEnvironment(mode, meshDir, { validateWithDocker: false });
2728
+ console.log(
2729
+ pc15.yellow("\nFinal merged Mesh YAML configuration:\n"),
2730
+ redactYamlSecrets(yaml)
2731
+ );
2732
+ } catch {
2733
+ }
2734
+ }
2735
+ if (stage === "test") {
2736
+ for (const serviceDir of rootServiceDirsForCleanup(meshDir)) {
2737
+ const status = await handleServiceDown("test", {
2738
+ projectDir: serviceDir,
2739
+ volumes: Boolean(options.volumes),
2740
+ debug: Boolean(options.debug)
2741
+ });
2742
+ if (status !== 0) return status;
2743
+ }
2744
+ }
2745
+ const runState = readRunState(meshDir);
2746
+ const candidateProjects = projectNamesForMeshStage(meshDir, stage);
2747
+ if (runState?.projectName) {
2748
+ candidateProjects.unshift(runState.projectName);
2749
+ }
2750
+ const uniqueProjects = Array.from(new Set(candidateProjects));
2751
+ for (const proj of uniqueProjects) {
2752
+ await teardownCompose("", meshDir, {
2753
+ projectName: proj,
2754
+ ...runState?.projectName === proj && runState.anonymousVolumeServices ? { anonymousVolumeServices: runState.anonymousVolumeServices } : {},
2755
+ removeVolumes: Boolean(options.volumes)
2756
+ });
2757
+ }
2758
+ clearRunState(meshDir);
2759
+ console.log(
2760
+ pc15.green(`\u2705 Global mesh environment [${stage}] stopped and removed.
2761
+ `)
2762
+ );
2763
+ return 0;
2764
+ }
2765
+
2766
+ // src/commands/mesh/commands/down/command.ts
2767
+ var registerMeshDownCommand = (cmd) => {
2768
+ cmd.command("down [stage]").description(
2769
+ "Stop and remove containers and networks for the global mesh environment (dev, prod, test, test-e2e)"
2770
+ ).option(
2771
+ "-v, --volumes",
2772
+ "Remove named volumes declared in the mesh configuration"
2773
+ ).option(
2774
+ "-C, --project-dir <dir>",
2775
+ "Mesh project directory containing mesh.json (defaults to cwd)"
2776
+ ).option("--debug", "Output the merged Docker Compose YAML configuration").addHelpText(
2777
+ "after",
2778
+ `
2779
+ Examples:
2780
+ $ builder mesh down
2781
+ $ builder mesh down dev
2782
+ $ builder mesh down prod
2783
+ $ builder mesh down -v`
2784
+ ).action(
2785
+ async (stage = "dev", options = {}) => {
2786
+ const exitCode = await handleMeshDown(stage, {
2787
+ projectDir: options.projectDir,
2788
+ volumes: options.volumes,
2789
+ debug: options.debug
2790
+ });
2791
+ if (exitCode !== 0) {
2792
+ process.exit(exitCode);
2484
2793
  }
2485
2794
  }
2486
2795
  );
2487
2796
  };
2797
+
2798
+ // src/core/runWithCleanup.ts
2799
+ async function runWithCleanup(run, cleanup) {
2800
+ let executionFailed = false;
2801
+ let executionError;
2802
+ try {
2803
+ const status = await run();
2804
+ if (status !== 0) {
2805
+ executionFailed = true;
2806
+ executionError = new ScriptError(`Compose execution exited with code ${status}`, { exitCode: status });
2807
+ }
2808
+ return status;
2809
+ } catch (error) {
2810
+ executionFailed = true;
2811
+ executionError = error;
2812
+ throw error;
2813
+ } finally {
2814
+ try {
2815
+ await cleanup();
2816
+ } catch (cleanupError) {
2817
+ if (executionFailed) {
2818
+ throw new AggregateError(
2819
+ [executionError, cleanupError],
2820
+ `Compose execution failed (${errorMessage(executionError)}); cleanup also failed (${errorMessage(cleanupError)}). Saved run state was retained`
2821
+ );
2822
+ }
2823
+ throw cleanupError;
2824
+ }
2825
+ }
2826
+ }
2488
2827
  function extractHostPorts(yamlConfig) {
2489
2828
  const ports = [];
2490
2829
  try {
@@ -2585,19 +2924,19 @@ async function runCompose(args, yamlConfig, projectDir, options = {}) {
2585
2924
  // src/core/mesh/runners/runMeshDev.ts
2586
2925
  async function runMeshDev(options = {}) {
2587
2926
  const meshDir = resolveProjectDir(options.projectDir);
2588
- console.log(pc22.cyan(`
2927
+ console.log(pc15.cyan(`
2589
2928
  \u{1F680} Starting Global DEV Mesh Environment...`));
2590
2929
  const { yaml } = compileMeshEnvironment("dev", meshDir);
2591
2930
  const parsed = parse(yaml);
2592
2931
  const projectName = parsed?.name || "mesh-dev";
2593
2932
  if (options.debug) {
2594
2933
  console.log(
2595
- pc22.yellow("\nFinal merged Mesh Dev YAML configuration:\n"),
2934
+ pc15.yellow("\nFinal merged Mesh Dev YAML configuration:\n"),
2596
2935
  redactYamlSecrets(yaml)
2597
2936
  );
2598
2937
  }
2599
2938
  if (options.dryRun) {
2600
- console.log(pc22.green("Dry run complete. Compose was not started."));
2939
+ console.log(pc15.green("Dry run complete. Compose was not started."));
2601
2940
  return 0;
2602
2941
  }
2603
2942
  const hostPorts = extractHostPorts(yaml);
@@ -2612,34 +2951,34 @@ async function runMeshDev(options = {}) {
2612
2951
  if (options.detach) {
2613
2952
  upArgs.push("-d");
2614
2953
  }
2615
- let status = 0;
2616
- try {
2617
- status = await runCompose(upArgs, yaml, meshDir, {
2954
+ const status = await runWithCleanup(
2955
+ () => runCompose(upArgs, yaml, meshDir, {
2618
2956
  removeVolumes: false
2619
- });
2620
- } finally {
2621
- if (!options.detach) {
2622
- await teardownCompose(yaml, meshDir, { removeVolumes: false });
2623
- clearRunState(meshDir);
2957
+ }),
2958
+ async () => {
2959
+ if (!options.detach) {
2960
+ await teardownCompose(yaml, meshDir, { removeVolumes: false });
2961
+ clearRunState(meshDir);
2962
+ }
2624
2963
  }
2625
- }
2964
+ );
2626
2965
  return status;
2627
2966
  }
2628
2967
  async function runMeshProd(options = {}) {
2629
2968
  const meshDir = resolveProjectDir(options.projectDir);
2630
- console.log(pc22.cyan(`
2969
+ console.log(pc15.cyan(`
2631
2970
  \u{1F3ED} Starting Global PROD Mesh Environment...`));
2632
2971
  const { yaml } = compileMeshEnvironment("prod", meshDir);
2633
2972
  const parsed = parse(yaml);
2634
2973
  const projectName = parsed?.name || "mesh-prod";
2635
2974
  if (options.debug) {
2636
2975
  console.log(
2637
- pc22.yellow("\nFinal merged Mesh Prod YAML configuration:\n"),
2976
+ pc15.yellow("\nFinal merged Mesh Prod YAML configuration:\n"),
2638
2977
  redactYamlSecrets(yaml)
2639
2978
  );
2640
2979
  }
2641
2980
  if (options.dryRun) {
2642
- console.log(pc22.green("Dry run complete. Compose was not started."));
2981
+ console.log(pc15.green("Dry run complete. Compose was not started."));
2643
2982
  return 0;
2644
2983
  }
2645
2984
  const hostPorts = extractHostPorts(yaml);
@@ -2654,52 +2993,208 @@ async function runMeshProd(options = {}) {
2654
2993
  if (options.detach) {
2655
2994
  upArgs.push("-d");
2656
2995
  }
2657
- let status = 0;
2658
- try {
2659
- status = await runCompose(upArgs, yaml, meshDir, {
2996
+ const status = await runWithCleanup(
2997
+ () => runCompose(upArgs, yaml, meshDir, {
2660
2998
  removeVolumes: false
2661
- });
2662
- } finally {
2663
- if (!options.detach) {
2664
- await teardownCompose(yaml, meshDir, { removeVolumes: false });
2665
- clearRunState(meshDir);
2999
+ }),
3000
+ async () => {
3001
+ if (!options.detach) {
3002
+ await teardownCompose(yaml, meshDir, { removeVolumes: false });
3003
+ clearRunState(meshDir);
3004
+ }
2666
3005
  }
2667
- }
3006
+ );
2668
3007
  return status;
2669
3008
  }
2670
- async function runMeshTestUnit(options = {}) {
2671
- 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));
2672
- console.log(pc22.bold(pc22.blue("\n[1/2] MESH SERVICE UNIT/ISOLATED TESTS\n")));
2673
- for (const [name, svc] of Object.entries(services).sort(([a], [b]) => a.localeCompare(b))) {
2674
- console.log(pc22.cyan(`-> Running isolated unit tests for [${name}]`));
2675
- const compiled = compileServiceComposition("test", svc.absolutePath, { meshMode: true, full: false, externalAppEnv: {}, deferReferenceResolution: true, appServiceName: "app" });
2676
- const endpoints = { app: { [name]: compiled.endpoints.app }, dependencies: { [name]: compiled.endpoints.dependencies } };
2677
- const refCtx = { services: { [name]: svc }, bindings: /* @__PURE__ */ new Map(), endpoints, stage: "test", meshJsonPath: meshPath };
2678
- const env = svc.meshEnv;
2679
- 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" });
2680
- const resolvedBuild = resolveServiceBuildEnvThroughMesh(name, compiled.buildJsonAppEnvironment ?? {}, refCtx, `services.${name}.app.env`);
2681
- for (const [depName, depEnv] of Object.entries(compiled.dependencyEnvironments ?? {})) resolveServiceBuildEnvThroughMesh(name, depEnv, refCtx, `services.${name}.dependencies.${depName}.env`);
2682
- const resolved = resolveMeshEnvMap(env, refCtx, `services.${name}.env`);
2683
- const app = compiled.compose.services.app;
2684
- app.environment = { ...resolvedBuild, ...compiled.overrideComposeAppEnvironment ?? {}, ...resolved, ...compiled.builderInternalEnvironment ?? {} };
2685
- applyTestAppPublications(validated, name, app, compiled.endpoints.app);
2686
- const projectName = `${deriveProjectName(raw.name ?? path.basename(meshDir), "dev")}-${name}-test`;
2687
- compiled.compose.name = projectName;
2688
- const yaml = stringify(compiled.compose);
2689
- if (options.debug) console.log(yaml);
2690
- if (options.dryRun) {
2691
- console.log(pc22.green(`[DRY-RUN] Unit tests for ${name} compiled.`));
2692
- continue;
3009
+ var runTestUnit = async (options) => {
3010
+ if (!options.skipBanner) {
3011
+ console.log(pc15.bold(pc15.blue(`
3012
+ ========================================`)));
3013
+ console.log(pc15.bold(pc15.blue(`\u{1F9EA} STAGE: UNIT & ISOLATED TESTS`)));
3014
+ console.log(pc15.bold(pc15.blue(`========================================
3015
+ `)));
3016
+ }
3017
+ const finalYamlConfig = compileEnvironment("test", options.projectDir, {
3018
+ silenceWarnings: options.silenceWarnings
3019
+ });
3020
+ const parsed = parse(finalYamlConfig);
3021
+ const projectName = parsed?.name || "test";
3022
+ if (options.debug) {
3023
+ console.log(
3024
+ pc15.yellow("Final merged YAML configuration:\n"),
3025
+ redactYamlSecrets(finalYamlConfig)
3026
+ );
3027
+ }
3028
+ if (options.dryRun) {
3029
+ console.log(pc15.green("[DRY-RUN] Unit tests simulated. Compose was not started."));
3030
+ return 0;
3031
+ }
3032
+ await checkHostPortCollisions(extractHostPorts(finalYamlConfig));
3033
+ await teardownCompose(finalYamlConfig, options.projectDir, {
3034
+ removeVolumes: true,
3035
+ silent: true
3036
+ });
3037
+ writeRunState(options.projectDir, {
3038
+ projectName,
3039
+ stage: "test-unit",
3040
+ projectDir: options.projectDir
3041
+ });
3042
+ const status = await runWithCleanup(
3043
+ () => runCompose(
3044
+ ["up", "--build", "--abort-on-container-exit", "--exit-code-from", "app"],
3045
+ finalYamlConfig,
3046
+ options.projectDir,
3047
+ { removeVolumes: true }
3048
+ ),
3049
+ async () => {
3050
+ await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
3051
+ clearRunState(options.projectDir);
2693
3052
  }
2694
- await teardownCompose(yaml, svc.absolutePath, { removeVolumes: true, silent: true });
2695
- writeRunState(svc.absolutePath, { projectName, stage: "test-unit", projectDir: svc.absolutePath });
2696
- let status;
2697
- try {
2698
- status = await runCompose(["up", "--build", "--abort-on-container-exit", "--exit-code-from", "app"], yaml, svc.absolutePath, { removeVolumes: true });
2699
- } finally {
2700
- await teardownCompose(yaml, svc.absolutePath, { removeVolumes: true });
2701
- clearRunState(svc.absolutePath);
3053
+ );
3054
+ if (status === 0) {
3055
+ console.log(pc15.bold(pc15.green(`
3056
+ \u2705 Unit tests passed successfully.
3057
+ `)));
3058
+ } else {
3059
+ console.error(pc15.red(`
3060
+ \u274C Unit tests failed with exit code ${status}.
3061
+ `));
3062
+ }
3063
+ return status;
3064
+ };
3065
+
3066
+ // src/core/runners/runFiniteTester.ts
3067
+ async function runFiniteTester(yaml, projectDir, testerServiceName) {
3068
+ const startStatus = await runCompose(
3069
+ ["up", "--build", "--detach"],
3070
+ yaml,
3071
+ projectDir,
3072
+ { removeVolumes: true }
3073
+ );
3074
+ if (startStatus !== 0) return startStatus;
3075
+ const testerStatus = await runCompose(
3076
+ ["wait", testerServiceName],
3077
+ yaml,
3078
+ projectDir,
3079
+ { removeVolumes: true }
3080
+ );
3081
+ await runCompose(["logs", "--no-color"], yaml, projectDir, {
3082
+ removeVolumes: true
3083
+ });
3084
+ return testerStatus;
3085
+ }
3086
+
3087
+ // src/core/runners/runTestE2e.ts
3088
+ var runTestE2e = async (options) => {
3089
+ if (!options.skipBanner) {
3090
+ console.log(pc15.bold(pc15.blue(`
3091
+ ========================================`)));
3092
+ console.log(pc15.bold(pc15.blue(`\u{1F6A6} STAGE: INTEGRATED E2E TESTS`)));
3093
+ console.log(pc15.bold(pc15.blue(`========================================
3094
+ `)));
3095
+ }
3096
+ const finalYamlConfig = compileEnvironment("e2e", options.projectDir, {
3097
+ silenceWarnings: options.silenceWarnings
3098
+ });
3099
+ const parsed = parse(finalYamlConfig);
3100
+ const projectName = parsed?.name || "e2e";
3101
+ if (options.debug) {
3102
+ console.log(
3103
+ pc15.yellow("Final merged YAML configuration:\n"),
3104
+ redactYamlSecrets(finalYamlConfig)
3105
+ );
3106
+ }
3107
+ if (options.dryRun) {
3108
+ console.log(pc15.green("[DRY-RUN] E2E tests simulated. Compose was not started."));
3109
+ return 0;
3110
+ }
3111
+ await checkHostPortCollisions(extractHostPorts(finalYamlConfig));
3112
+ await teardownCompose(finalYamlConfig, options.projectDir, {
3113
+ removeVolumes: true,
3114
+ silent: true
3115
+ });
3116
+ writeRunState(options.projectDir, {
3117
+ projectName,
3118
+ stage: "test-e2e",
3119
+ projectDir: options.projectDir
3120
+ });
3121
+ const status = await runWithCleanup(
3122
+ () => runFiniteTester(finalYamlConfig, options.projectDir, "tester"),
3123
+ async () => {
3124
+ await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
3125
+ clearRunState(options.projectDir);
2702
3126
  }
3127
+ );
3128
+ if (status === 0) {
3129
+ console.log(pc15.bold(pc15.green(`
3130
+ \u2705 E2E tests passed successfully.
3131
+ `)));
3132
+ } else {
3133
+ console.error(pc15.red(`
3134
+ \u274C E2E tests failed with exit code ${status}.
3135
+ `));
3136
+ }
3137
+ return status;
3138
+ };
3139
+
3140
+ // src/core/runners/runTest.ts
3141
+ var runTest = async (options) => {
3142
+ console.log(pc15.bold(pc15.blue(`
3143
+ ========================================`)));
3144
+ console.log(pc15.bold(pc15.blue(`\u{1F9EA} [1/2] STAGE: UNIT & ISOLATED TESTS`)));
3145
+ console.log(pc15.bold(pc15.blue(`========================================
3146
+ `)));
3147
+ const unitStatus = await runTestUnit({ ...options, skipBanner: true });
3148
+ if (unitStatus !== 0) {
3149
+ console.error(
3150
+ pc15.red(
3151
+ `
3152
+ \u274C [1/2] Unit tests failed with exit code ${unitStatus}. Aborting E2E tests.
3153
+ `
3154
+ )
3155
+ );
3156
+ return unitStatus;
3157
+ }
3158
+ console.log(
3159
+ pc15.bold(pc15.green(`
3160
+ \u2705 [1/2] Unit tests passed successfully.
3161
+ `))
3162
+ );
3163
+ console.log(pc15.bold(pc15.blue(`========================================`)));
3164
+ console.log(pc15.bold(pc15.blue(`\u{1F6A6} [2/2] STAGE: INTEGRATED E2E TESTS`)));
3165
+ console.log(pc15.bold(pc15.blue(`========================================
3166
+ `)));
3167
+ const e2eStatus = await runTestE2e({ ...options, skipBanner: true });
3168
+ if (e2eStatus !== 0) {
3169
+ console.error(
3170
+ pc15.red(`
3171
+ \u274C [2/2] E2E tests failed with exit code ${e2eStatus}.
3172
+ `)
3173
+ );
3174
+ return e2eStatus;
3175
+ }
3176
+ console.log(pc15.bold(pc15.green(`
3177
+ \u2705 [2/2] E2E tests passed successfully.
3178
+ `)));
3179
+ console.log(
3180
+ pc15.bold(
3181
+ pc15.green(`\u{1F389} All test stages (unit + e2e) completed successfully!
3182
+ `)
3183
+ )
3184
+ );
3185
+ return 0;
3186
+ };
3187
+
3188
+ // src/core/mesh/runners/runMeshServiceTests.ts
3189
+ async function runMeshServiceTests(options = {}) {
3190
+ const meshDir = resolveProjectDir(options.projectDir), meshPath = path.join(meshDir, "mesh.json"), mesh = getMeshJson(meshDir);
3191
+ const rootServices = Object.entries(mesh.services).sort(([left], [right]) => left.localeCompare(right));
3192
+ for (const [serviceName, service] of rootServices) {
3193
+ const serviceDir = resolveInsideProject(meshDir, service.path, { sourceFile: meshPath, configPath: `services.${serviceName}.path`, stage: "test" });
3194
+ console.log(pc15.bold(pc15.cyan(`
3195
+ -> Running full standalone test lifecycle for [${serviceName}]
3196
+ `)));
3197
+ const status = await runTest({ projectDir: serviceDir, debug: Boolean(options.debug), detach: false, skipBanner: true, silenceWarnings: false, ...options.dryRun !== void 0 ? { dryRun: options.dryRun } : {} });
2703
3198
  if (status !== 0) return status;
2704
3199
  }
2705
3200
  return 0;
@@ -2709,68 +3204,70 @@ async function runMeshTestE2e(options = {}) {
2709
3204
  if (!mesh.tester) throw new ScriptError("Global mesh E2E requires root mesh.json.tester { compose, service, env? }");
2710
3205
  const { yaml, testerServiceName } = compileMeshEnvironment("e2e", meshDir);
2711
3206
  if (!testerServiceName) throw new ScriptError("Global mesh E2E tester runner could not be compiled.");
2712
- if (options.debug) console.log(pc22.yellow("\nFinal global mesh E2E YAML configuration:\n"), redactYamlSecrets(yaml));
3207
+ if (options.debug) console.log(pc15.yellow("\nFinal global mesh E2E YAML configuration:\n"), redactYamlSecrets(yaml));
2713
3208
  if (options.dryRun) {
2714
- console.log(pc22.green("[DRY-RUN] Global mesh E2E compiled; Compose was not started."));
3209
+ console.log(pc15.green("[DRY-RUN] Global mesh E2E compiled; Compose was not started."));
2715
3210
  return 0;
2716
3211
  }
2717
3212
  await checkHostPortCollisions(extractHostPorts(yaml));
2718
3213
  const projectName = parse(yaml)?.name || "mesh-e2e";
2719
3214
  await teardownCompose(yaml, meshDir, { removeVolumes: true, silent: true });
2720
3215
  writeRunState(meshDir, { projectName, stage: "test-e2e", projectDir: meshDir });
2721
- let status = 0;
2722
- try {
2723
- status = await runCompose(["up", "--build", "--abort-on-container-exit", "--exit-code-from", testerServiceName], yaml, meshDir, { removeVolumes: true });
2724
- } finally {
3216
+ const status = await runWithCleanup(() => runFiniteTester(yaml, meshDir, testerServiceName), async () => {
2725
3217
  await teardownCompose(yaml, meshDir, { removeVolumes: true });
2726
3218
  clearRunState(meshDir);
2727
- }
3219
+ });
2728
3220
  return status;
2729
3221
  }
2730
3222
 
2731
3223
  // src/core/mesh/runners/runMeshTest.ts
2732
3224
  async function runMeshTest(options = {}) {
2733
- console.log(pc22.bold(pc22.blue("\n========================================\nMESH TEST PIPELINE\n========================================\n")));
2734
- console.log(pc22.bold(pc22.blue("[1/2] MESH SERVICE UNIT/ISOLATED TESTS")));
2735
- const unitStatus = await runMeshTestUnit(options);
2736
- if (unitStatus !== 0) return unitStatus;
2737
- console.log(pc22.bold(pc22.blue("[2/2] GLOBAL MESH E2E")));
3225
+ console.log(pc15.bold(pc15.blue("\n========================================\nMESH TEST PIPELINE\n========================================\n")));
3226
+ console.log(pc15.bold(pc15.blue("[1/2] ROOT SERVICE TEST LIFECYCLES")));
3227
+ const serviceStatus = await runMeshServiceTests(options);
3228
+ if (serviceStatus !== 0) return serviceStatus;
3229
+ console.log(pc15.bold(pc15.blue("[2/2] GLOBAL MESH E2E")));
2738
3230
  return runMeshTestE2e(options);
2739
3231
  }
2740
3232
 
2741
3233
  // src/commands/mesh/commands/up/handler.ts
2742
3234
  async function handleMeshUp(rawStage = "dev", options = {}) {
2743
3235
  const stage = (rawStage || "dev").toLowerCase();
3236
+ if (stage === "test-unit") {
3237
+ throw new ScriptError(
3238
+ "mesh up test-unit is no longer supported because meshes have no test topology. Use builder service up test-unit -C <service> for isolated tests, or builder mesh up test for the complete test pipeline."
3239
+ );
3240
+ }
3241
+ if (!MESH_COMMAND_STAGES.includes(stage)) {
3242
+ throw new ScriptError(
3243
+ `Unknown mesh stage: "${rawStage}". Supported stages: ${MESH_COMMAND_STAGES.join(", ")}`
3244
+ );
3245
+ }
2744
3246
  const projectDir = resolveProjectDir(options.projectDir);
2745
- const runOptions = {
2746
- ...options,
2747
- projectDir
2748
- };
2749
- if (["dev", "prod", "test-unit", "test-e2e", "test"].includes(stage) && !options.skipChecks) {
2750
- checkMesh(projectDir, { requireTester: stage === "test-e2e" || stage === "test" });
3247
+ const runOptions = { ...options, projectDir };
3248
+ if (!options.skipChecks) {
3249
+ checkMesh(projectDir, {
3250
+ requireTester: stage === "test" || stage === "test-e2e"
3251
+ });
2751
3252
  }
2752
3253
  switch (stage) {
2753
3254
  case "dev":
2754
- return await runMeshDev(runOptions);
3255
+ return runMeshDev(runOptions);
2755
3256
  case "prod":
2756
- return await runMeshProd(runOptions);
2757
- case "test-unit":
2758
- return await runMeshTestUnit(runOptions);
2759
- case "test-e2e":
2760
- return await runMeshTestE2e(runOptions);
3257
+ return runMeshProd(runOptions);
2761
3258
  case "test":
2762
- return await runMeshTest(runOptions);
3259
+ return runMeshTest(runOptions);
3260
+ case "test-e2e":
3261
+ return runMeshTestE2e(runOptions);
2763
3262
  default:
2764
- throw new ScriptError(
2765
- `Unknown mesh stage: "${rawStage}". Supported stages: dev, prod, test, test-unit, test-e2e`
2766
- );
3263
+ throw new ScriptError(`Unsupported mesh command: ${stage}`);
2767
3264
  }
2768
3265
  }
2769
3266
 
2770
3267
  // src/commands/mesh/commands/up/command.ts
2771
3268
  var registerMeshUpCommand = (cmd) => {
2772
3269
  cmd.command("up [stage]").description(
2773
- "Start, build, or test the mesh environment (dev, prod, test, test-unit, test-e2e)"
3270
+ "Start, build, or test the mesh environment (dev, prod, test, test-e2e)"
2774
3271
  ).option("--debug", "Output the merged Docker Compose YAML configuration").option("-d, --detach", "Run containers in the background").option(
2775
3272
  "--dry-run",
2776
3273
  "Compile configuration and validate checks without starting containers"
@@ -2790,11 +3287,11 @@ Examples:
2790
3287
  $ builder mesh up dev
2791
3288
  $ builder mesh up prod
2792
3289
  $ builder mesh up test
2793
- $ builder mesh up test-unit
2794
3290
  $ builder mesh up test-e2e
2795
3291
 
2796
- JSON overlays: test-unit uses mesh/build test; test-e2e uses mesh/build e2e.
2797
- The test command runs per-service unit tests before global E2E.`
3292
+ Mesh JSON overlays: dev, prod, e2e. test-e2e uses base -> prod -> e2e.
3293
+ The test command runs each root service test lifecycle (unit, then service E2E) before global E2E.
3294
+ For a service\u2019s isolated tests: builder service up test-unit -C <service>.`
2798
3295
  ).action(
2799
3296
  async (stage = "dev", options = {}) => {
2800
3297
  const exitCode = await handleMeshUp(stage, {
@@ -2822,7 +3319,7 @@ var registerMeshCommand = (program) => {
2822
3319
  registerMeshCheckCommand(meshCmd);
2823
3320
  };
2824
3321
  async function handlePrune(options = {}) {
2825
- console.log(pc22.cyan("\n\u{1F9F9} Pruning stopped Compose containers and unused networks..."));
3322
+ console.log(pc15.cyan("\n\u{1F9F9} Pruning stopped Compose containers and unused networks..."));
2826
3323
  const rmContainers = spawnSync("docker", ["container", "prune", "-f"], {
2827
3324
  stdio: "inherit",
2828
3325
  encoding: "utf-8"
@@ -2842,13 +3339,13 @@ async function handlePrune(options = {}) {
2842
3339
  });
2843
3340
  }
2844
3341
  if (options.volumes) {
2845
- console.log(pc22.cyan("\u{1F9F9} Pruning dangling volumes..."));
3342
+ console.log(pc15.cyan("\u{1F9F9} Pruning dangling volumes..."));
2846
3343
  spawnSync("docker", ["volume", "prune", "-f"], {
2847
3344
  stdio: "inherit",
2848
3345
  encoding: "utf-8"
2849
3346
  });
2850
3347
  }
2851
- console.log(pc22.green("\u2705 Docker environment pruned successfully.\n"));
3348
+ console.log(pc15.green("\u2705 Docker environment pruned successfully.\n"));
2852
3349
  return 0;
2853
3350
  }
2854
3351
 
@@ -2863,56 +3360,6 @@ var registerPruneCommand = (cmd) => {
2863
3360
  }
2864
3361
  });
2865
3362
  };
2866
- var compileEnvironment = (stage, projectDir = process.cwd(), options = {}) => stringify(compileServiceComposition(stage, projectDir, { full: Boolean(options.full), silenceWarnings: options.silenceWarnings }).compose);
2867
-
2868
- // src/commands/service/commands/down/handler.ts
2869
- async function handleServiceDown(rawStage = "dev", options = {}) {
2870
- const projectDir = resolveProjectDir(options.projectDir);
2871
- const stage = (rawStage || "dev").toLowerCase();
2872
- const validStages = ["dev", "prod", "test", "test-unit", "test-e2e"];
2873
- if (!validStages.includes(stage)) {
2874
- throw new ScriptError(
2875
- `Unknown environment stage: "${rawStage}". Supported stages: dev, prod, test, test-unit, test-e2e`
2876
- );
2877
- }
2878
- console.log(
2879
- pc22.cyan(`
2880
- \u{1F9F9} Stopping and tearing down service environment [${stage}]...`)
2881
- );
2882
- if (options.debug) {
2883
- try {
2884
- let env = "dev";
2885
- if (stage === "prod") env = "prod";
2886
- else if (stage === "test" || stage === "test-unit") env = "test";
2887
- else if (stage === "test-e2e") env = "e2e";
2888
- const finalYamlConfig = compileEnvironment(env, projectDir);
2889
- console.log(
2890
- pc22.yellow("Final merged YAML configuration:\n"),
2891
- redactYamlSecrets(finalYamlConfig)
2892
- );
2893
- } catch {
2894
- }
2895
- }
2896
- const runState = readRunState(projectDir);
2897
- const candidateProjects = projectNamesForServiceStage(projectDir, stage);
2898
- if (runState?.projectName) {
2899
- candidateProjects.unshift(runState.projectName);
2900
- }
2901
- const uniqueProjects = Array.from(new Set(candidateProjects));
2902
- for (const proj of uniqueProjects) {
2903
- await teardownCompose("", projectDir, {
2904
- projectName: proj,
2905
- ...runState?.projectName === proj && runState.anonymousVolumeServices ? { anonymousVolumeServices: runState.anonymousVolumeServices } : {},
2906
- removeVolumes: Boolean(options.volumes)
2907
- });
2908
- }
2909
- clearRunState(projectDir);
2910
- console.log(
2911
- pc22.green(`\u2705 Service environment [${stage}] stopped and removed.
2912
- `)
2913
- );
2914
- return 0;
2915
- }
2916
3363
 
2917
3364
  // src/commands/service/commands/down/command.ts
2918
3365
  var registerDownCommand = (cmd) => {
@@ -2947,7 +3394,7 @@ Examples:
2947
3394
  };
2948
3395
  var runDev = async (options) => {
2949
3396
  console.log(
2950
- pc22.cyan(
3397
+ pc15.cyan(
2951
3398
  options.full ? `\u{1F680} Starting DEV environment (full / integrated)...` : `\u{1F680} Starting DEV environment...`
2952
3399
  )
2953
3400
  );
@@ -2959,12 +3406,12 @@ var runDev = async (options) => {
2959
3406
  const projectName = parsed?.name || "dev";
2960
3407
  if (options.debug) {
2961
3408
  console.log(
2962
- pc22.yellow("Final merged YAML configuration:\n"),
3409
+ pc15.yellow("Final merged YAML configuration:\n"),
2963
3410
  redactYamlSecrets(finalYamlConfig)
2964
3411
  );
2965
3412
  }
2966
3413
  if (options.dryRun) {
2967
- console.log(pc22.green("Dry run complete. Compose was not started."));
3414
+ console.log(pc15.green("Dry run complete. Compose was not started."));
2968
3415
  return 0;
2969
3416
  }
2970
3417
  const hostPorts = extractHostPorts(finalYamlConfig);
@@ -2979,23 +3426,23 @@ var runDev = async (options) => {
2979
3426
  if (options.detach) {
2980
3427
  upArgs.push("-d");
2981
3428
  }
2982
- let status = 0;
2983
- try {
2984
- status = await runCompose(upArgs, finalYamlConfig, options.projectDir, {
3429
+ const status = await runWithCleanup(
3430
+ () => runCompose(upArgs, finalYamlConfig, options.projectDir, {
2985
3431
  removeVolumes: false
2986
- });
2987
- } finally {
2988
- if (!options.detach) {
2989
- await teardownCompose(finalYamlConfig, options.projectDir, {
2990
- removeVolumes: false
2991
- });
2992
- clearRunState(options.projectDir);
3432
+ }),
3433
+ async () => {
3434
+ if (!options.detach) {
3435
+ await teardownCompose(finalYamlConfig, options.projectDir, {
3436
+ removeVolumes: false
3437
+ });
3438
+ clearRunState(options.projectDir);
3439
+ }
2993
3440
  }
2994
- }
3441
+ );
2995
3442
  return status;
2996
3443
  };
2997
3444
  var runProd = async (options) => {
2998
- console.log(pc22.cyan(`\u{1F3ED} Starting PROD environment...`));
3445
+ console.log(pc15.cyan(`\u{1F3ED} Starting PROD environment...`));
2999
3446
  const finalYamlConfig = compileEnvironment("prod", options.projectDir, {
3000
3447
  silenceWarnings: options.silenceWarnings
3001
3448
  });
@@ -3003,12 +3450,12 @@ var runProd = async (options) => {
3003
3450
  const projectName = parsed?.name || "prod";
3004
3451
  if (options.debug) {
3005
3452
  console.log(
3006
- pc22.yellow("Final merged YAML configuration:\n"),
3453
+ pc15.yellow("Final merged YAML configuration:\n"),
3007
3454
  redactYamlSecrets(finalYamlConfig)
3008
3455
  );
3009
3456
  }
3010
3457
  if (options.dryRun) {
3011
- console.log(pc22.green("Dry run complete. Compose was not started."));
3458
+ console.log(pc15.green("Dry run complete. Compose was not started."));
3012
3459
  return 0;
3013
3460
  }
3014
3461
  const hostPorts = extractHostPorts(finalYamlConfig);
@@ -3023,186 +3470,20 @@ var runProd = async (options) => {
3023
3470
  if (options.detach) {
3024
3471
  upArgs.push("-d");
3025
3472
  }
3026
- let status = 0;
3027
- try {
3028
- status = await runCompose(upArgs, finalYamlConfig, options.projectDir, {
3473
+ const status = await runWithCleanup(
3474
+ () => runCompose(upArgs, finalYamlConfig, options.projectDir, {
3029
3475
  removeVolumes: false
3030
- });
3031
- } finally {
3032
- if (!options.detach) {
3033
- await teardownCompose(finalYamlConfig, options.projectDir, {
3034
- removeVolumes: false
3035
- });
3036
- clearRunState(options.projectDir);
3476
+ }),
3477
+ async () => {
3478
+ if (!options.detach) {
3479
+ await teardownCompose(finalYamlConfig, options.projectDir, {
3480
+ removeVolumes: false
3481
+ });
3482
+ clearRunState(options.projectDir);
3483
+ }
3037
3484
  }
3038
- }
3039
- return status;
3040
- };
3041
- var runTestUnit = async (options) => {
3042
- if (!options.skipBanner) {
3043
- console.log(pc22.bold(pc22.blue(`
3044
- ========================================`)));
3045
- console.log(pc22.bold(pc22.blue(`\u{1F9EA} STAGE: UNIT & ISOLATED TESTS`)));
3046
- console.log(pc22.bold(pc22.blue(`========================================
3047
- `)));
3048
- }
3049
- const finalYamlConfig = compileEnvironment("test", options.projectDir, {
3050
- silenceWarnings: options.silenceWarnings
3051
- });
3052
- const parsed = parse(finalYamlConfig);
3053
- const projectName = parsed?.name || "test";
3054
- if (options.debug) {
3055
- console.log(
3056
- pc22.yellow("Final merged YAML configuration:\n"),
3057
- redactYamlSecrets(finalYamlConfig)
3058
- );
3059
- }
3060
- if (options.dryRun) {
3061
- console.log(pc22.green("[DRY-RUN] Unit tests simulated. Compose was not started."));
3062
- return 0;
3063
- }
3064
- await checkHostPortCollisions(extractHostPorts(finalYamlConfig));
3065
- await teardownCompose(finalYamlConfig, options.projectDir, {
3066
- removeVolumes: true,
3067
- silent: true
3068
- });
3069
- writeRunState(options.projectDir, {
3070
- projectName,
3071
- stage: "test-unit",
3072
- projectDir: options.projectDir
3073
- });
3074
- let status = 0;
3075
- try {
3076
- status = await runCompose(
3077
- ["up", "--build", "--abort-on-container-exit", "--exit-code-from", "app"],
3078
- finalYamlConfig,
3079
- options.projectDir,
3080
- { removeVolumes: true }
3081
- );
3082
- } finally {
3083
- await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
3084
- clearRunState(options.projectDir);
3085
- }
3086
- if (status === 0) {
3087
- console.log(pc22.bold(pc22.green(`
3088
- \u2705 Unit tests passed successfully.
3089
- `)));
3090
- } else {
3091
- console.error(pc22.red(`
3092
- \u274C Unit tests failed with exit code ${status}.
3093
- `));
3094
- }
3095
- return status;
3096
- };
3097
- var runTestE2e = async (options) => {
3098
- if (!options.skipBanner) {
3099
- console.log(pc22.bold(pc22.blue(`
3100
- ========================================`)));
3101
- console.log(pc22.bold(pc22.blue(`\u{1F6A6} STAGE: INTEGRATED E2E TESTS`)));
3102
- console.log(pc22.bold(pc22.blue(`========================================
3103
- `)));
3104
- }
3105
- const finalYamlConfig = compileEnvironment("e2e", options.projectDir, {
3106
- silenceWarnings: options.silenceWarnings
3107
- });
3108
- const parsed = parse(finalYamlConfig);
3109
- const projectName = parsed?.name || "e2e";
3110
- if (options.debug) {
3111
- console.log(
3112
- pc22.yellow("Final merged YAML configuration:\n"),
3113
- redactYamlSecrets(finalYamlConfig)
3114
- );
3115
- }
3116
- if (options.dryRun) {
3117
- console.log(pc22.green("[DRY-RUN] E2E tests simulated. Compose was not started."));
3118
- return 0;
3119
- }
3120
- await checkHostPortCollisions(extractHostPorts(finalYamlConfig));
3121
- await teardownCompose(finalYamlConfig, options.projectDir, {
3122
- removeVolumes: true,
3123
- silent: true
3124
- });
3125
- writeRunState(options.projectDir, {
3126
- projectName,
3127
- stage: "test-e2e",
3128
- projectDir: options.projectDir
3129
- });
3130
- let status = 0;
3131
- try {
3132
- status = await runCompose(
3133
- [
3134
- "up",
3135
- "--build",
3136
- "--abort-on-container-exit",
3137
- "--exit-code-from",
3138
- "tester"
3139
- ],
3140
- finalYamlConfig,
3141
- options.projectDir,
3142
- { removeVolumes: true }
3143
- );
3144
- } finally {
3145
- await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
3146
- clearRunState(options.projectDir);
3147
- }
3148
- if (status === 0) {
3149
- console.log(pc22.bold(pc22.green(`
3150
- \u2705 E2E tests passed successfully.
3151
- `)));
3152
- } else {
3153
- console.error(pc22.red(`
3154
- \u274C E2E tests failed with exit code ${status}.
3155
- `));
3156
- }
3157
- return status;
3158
- };
3159
-
3160
- // src/core/runners/runTest.ts
3161
- var runTest = async (options) => {
3162
- console.log(pc22.bold(pc22.blue(`
3163
- ========================================`)));
3164
- console.log(pc22.bold(pc22.blue(`\u{1F9EA} [1/2] STAGE: UNIT & ISOLATED TESTS`)));
3165
- console.log(pc22.bold(pc22.blue(`========================================
3166
- `)));
3167
- const unitStatus = await runTestUnit({ ...options, skipBanner: true });
3168
- if (unitStatus !== 0) {
3169
- console.error(
3170
- pc22.red(
3171
- `
3172
- \u274C [1/2] Unit tests failed with exit code ${unitStatus}. Aborting E2E tests.
3173
- `
3174
- )
3175
- );
3176
- return unitStatus;
3177
- }
3178
- console.log(
3179
- pc22.bold(pc22.green(`
3180
- \u2705 [1/2] Unit tests passed successfully.
3181
- `))
3182
3485
  );
3183
- console.log(pc22.bold(pc22.blue(`========================================`)));
3184
- console.log(pc22.bold(pc22.blue(`\u{1F6A6} [2/2] STAGE: INTEGRATED E2E TESTS`)));
3185
- console.log(pc22.bold(pc22.blue(`========================================
3186
- `)));
3187
- const e2eStatus = await runTestE2e({ ...options, skipBanner: true });
3188
- if (e2eStatus !== 0) {
3189
- console.error(
3190
- pc22.red(`
3191
- \u274C [2/2] E2E tests failed with exit code ${e2eStatus}.
3192
- `)
3193
- );
3194
- return e2eStatus;
3195
- }
3196
- console.log(pc22.bold(pc22.green(`
3197
- \u2705 [2/2] E2E tests passed successfully.
3198
- `)));
3199
- console.log(
3200
- pc22.bold(
3201
- pc22.green(`\u{1F389} All test stages (unit + e2e) completed successfully!
3202
- `)
3203
- )
3204
- );
3205
- return 0;
3486
+ return status;
3206
3487
  };
3207
3488
 
3208
3489
  // src/commands/service/commands/up/handler.ts
@@ -3335,6 +3616,16 @@ async function handleExportEnv(rawStage, options = {}) {
3335
3616
  throw new ScriptError(`Unknown environment stage: "${rawStage}". Supported stages: ${STAGES.join(", ")}`);
3336
3617
  }
3337
3618
  const projectDir = resolveProjectDir(options.projectDir);
3619
+ const runtimeInputs = new Set(
3620
+ STAGES.map((s) => canonicalPath(path.join(projectDir, `.env.${s}`)))
3621
+ );
3622
+ const assertSafeDestination = (candidate) => {
3623
+ if (runtimeInputs.has(canonicalPath(candidate))) {
3624
+ throw new ScriptError(
3625
+ `Resolved env export cannot overwrite a runtime .env.<stage> input: ${candidate}`
3626
+ );
3627
+ }
3628
+ };
3338
3629
  const stages = stage === void 0 ? STAGES : [stage];
3339
3630
  const snapshots = stages.map((stage2) => ({
3340
3631
  stage: stage2,
@@ -3352,7 +3643,7 @@ async function handleExportEnv(rawStage, options = {}) {
3352
3643
  const files = [];
3353
3644
  try {
3354
3645
  for (const snapshot of snapshots) {
3355
- let filename = path.join(projectDir, `.env.${snapshot.stage}`);
3646
+ let filename = path.join(projectDir, `.env.${snapshot.stage}.resolved`);
3356
3647
  while (true) {
3357
3648
  let overwrite = false;
3358
3649
  if (existsSync(filename)) {
@@ -3362,9 +3653,11 @@ async function handleExportEnv(rawStage, options = {}) {
3362
3653
  const name = (await ask(`New filename for ${snapshot.stage} (relative to the service directory): `)).trim();
3363
3654
  if (!name) continue;
3364
3655
  filename = path.resolve(projectDir, name);
3656
+ assertSafeDestination(filename);
3365
3657
  continue;
3366
3658
  }
3367
3659
  }
3660
+ assertSafeDestination(filename);
3368
3661
  mkdirSync(path.dirname(filename), { recursive: true });
3369
3662
  try {
3370
3663
  writeFileSync(filename, snapshot.content, { encoding: "utf-8", flag: overwrite ? "w" : "wx", mode: 384 });
@@ -3373,7 +3666,7 @@ async function handleExportEnv(rawStage, options = {}) {
3373
3666
  throw error;
3374
3667
  }
3375
3668
  files.push(filename);
3376
- console.log(pc22.green(`Exported ${snapshot.stage} application environment to ${filename}`));
3669
+ console.log(pc15.green(`Exported ${snapshot.stage} application environment to ${filename}`));
3377
3670
  break;
3378
3671
  }
3379
3672
  }
@@ -3449,10 +3742,10 @@ async function runCli(argv = process.argv) {
3449
3742
  (arg) => arg === "-h" || arg === "--help" || arg === "-V" || arg === "--version"
3450
3743
  );
3451
3744
  if (!isHelpOrVersion && argv.length > 2) {
3452
- console.log(pc22.dim(`builder v${version}`));
3745
+ console.log(pc15.dim(`builder v${version}`));
3453
3746
  }
3454
3747
  if (argv.length <= 2) {
3455
- console.log(pc22.dim(`builder v${version}
3748
+ console.log(pc15.dim(`builder v${version}
3456
3749
  `));
3457
3750
  cli.outputHelp();
3458
3751
  return;
@@ -3475,20 +3768,20 @@ async function runCli(argv = process.argv) {
3475
3768
  if (err instanceof ScriptError) {
3476
3769
  exitCode = err.exitCode;
3477
3770
  const formatted = err.message.startsWith("\u274C") ? err.message : `\u274C ${err.message}`;
3478
- console.error(pc22.red(`
3771
+ console.error(pc15.red(`
3479
3772
  ${formatted}
3480
3773
  `));
3481
3774
  if (isVerbose && err.stack) {
3482
- console.error(pc22.dim(err.stack));
3775
+ console.error(pc15.dim(err.stack));
3483
3776
  }
3484
3777
  } else {
3485
3778
  const message = errorMessage(err);
3486
3779
  const formatted = message.startsWith("\u274C") ? message : `\u274C Error: ${message}`;
3487
- console.error(pc22.red(`
3780
+ console.error(pc15.red(`
3488
3781
  ${formatted}
3489
3782
  `));
3490
3783
  if (isVerbose && err instanceof Error && err.stack) {
3491
- console.error(pc22.dim(err.stack));
3784
+ console.error(pc15.dim(err.stack));
3492
3785
  }
3493
3786
  }
3494
3787
  if (process.env.VITEST) {