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