@solid-stack/builder 2.0.2 → 2.1.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 (93) hide show
  1. package/README.md +581 -50
  2. package/dist/bin.js +1160 -610
  3. package/dist/bin.js.map +1 -1
  4. package/dist/commands/mesh/commands/up/command.d.ts.map +1 -1
  5. package/dist/commands/mesh/commands/up/handler.d.ts.map +1 -1
  6. package/dist/commands/service/commands/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 +2 -0
  11. package/dist/core/composition/compileServiceComposition.d.ts.map +1 -1
  12. package/dist/core/composition/composeBuildResources.d.ts +6 -0
  13. package/dist/core/composition/composeBuildResources.d.ts.map +1 -0
  14. package/dist/core/composition/composeDependsOn.d.ts +3 -0
  15. package/dist/core/composition/composeDependsOn.d.ts.map +1 -0
  16. package/dist/core/composition/composeEnvironment.d.ts +2 -2
  17. package/dist/core/composition/composeEnvironment.d.ts.map +1 -1
  18. package/dist/core/composition/composeHealthcheck.d.ts +3 -0
  19. package/dist/core/composition/composeHealthcheck.d.ts.map +1 -0
  20. package/dist/core/composition/composePaths.d.ts.map +1 -1
  21. package/dist/core/composition/generatedNames.d.ts +9 -0
  22. package/dist/core/composition/generatedNames.d.ts.map +1 -0
  23. package/dist/core/composition/mergeAppOverride.d.ts +3 -0
  24. package/dist/core/composition/mergeAppOverride.d.ts.map +1 -0
  25. package/dist/core/composition/namespaceDependencyCompose.d.ts +3 -0
  26. package/dist/core/composition/namespaceDependencyCompose.d.ts.map +1 -1
  27. package/dist/core/composition/namespaceResourceDefinition.d.ts +3 -0
  28. package/dist/core/composition/namespaceResourceDefinition.d.ts.map +1 -0
  29. package/dist/core/composition/selectAppEnvironmentEntries.d.ts +3 -0
  30. package/dist/core/composition/selectAppEnvironmentEntries.d.ts.map +1 -0
  31. package/dist/core/composition/types.d.ts +22 -5
  32. package/dist/core/composition/types.d.ts.map +1 -1
  33. package/dist/core/composition/validateComposeResourceReferences.d.ts +7 -0
  34. package/dist/core/composition/validateComposeResourceReferences.d.ts.map +1 -0
  35. package/dist/core/composition/validateDependencyCompose.d.ts.map +1 -1
  36. package/dist/core/composition/validateOverrideCompose.d.ts +3 -0
  37. package/dist/core/composition/validateOverrideCompose.d.ts.map +1 -1
  38. package/dist/core/config/builderEnvironment.d.ts +12 -0
  39. package/dist/core/config/builderEnvironment.d.ts.map +1 -0
  40. package/dist/core/config/endpointProperties.d.ts +5 -2
  41. package/dist/core/config/endpointProperties.d.ts.map +1 -1
  42. package/dist/core/config/hostPorts.d.ts +5 -1
  43. package/dist/core/config/hostPorts.d.ts.map +1 -1
  44. package/dist/core/config/pathSafety.d.ts.map +1 -1
  45. package/dist/core/config/references.d.ts +9 -3
  46. package/dist/core/config/references.d.ts.map +1 -1
  47. package/dist/core/config/resolveBuildStage.d.ts.map +1 -1
  48. package/dist/core/config/resolveMeshStage.d.ts.map +1 -1
  49. package/dist/core/config/stageMerge.d.ts +2 -0
  50. package/dist/core/config/stageMerge.d.ts.map +1 -1
  51. package/dist/core/config/types.d.ts +7 -2
  52. package/dist/core/config/types.d.ts.map +1 -1
  53. package/dist/core/mesh/checkers/checkMesh.d.ts +1 -0
  54. package/dist/core/mesh/checkers/checkMesh.d.ts.map +1 -1
  55. package/dist/core/mesh/checkers/checkMeshServices.d.ts +4 -1
  56. package/dist/core/mesh/checkers/checkMeshServices.d.ts.map +1 -1
  57. package/dist/core/mesh/meshSchema.d.ts +13 -1
  58. package/dist/core/mesh/meshSchema.d.ts.map +1 -1
  59. package/dist/core/mesh/runners/runMeshDev.d.ts.map +1 -1
  60. package/dist/core/mesh/runners/runMeshProd.d.ts.map +1 -1
  61. package/dist/core/mesh/runners/runMeshServiceTests.d.ts +3 -0
  62. package/dist/core/mesh/runners/runMeshServiceTests.d.ts.map +1 -0
  63. package/dist/core/mesh/runners/runMeshTest.d.ts.map +1 -1
  64. package/dist/core/mesh/runners/runMeshTestE2e.d.ts.map +1 -1
  65. package/dist/core/mesh/runners/runMeshTestUnit.d.ts.map +1 -1
  66. package/dist/core/mesh/v2/compileMeshComposition.d.ts.map +1 -1
  67. package/dist/core/mesh/v2/compileMeshTester.d.ts +2 -1
  68. package/dist/core/mesh/v2/compileMeshTester.d.ts.map +1 -1
  69. package/dist/core/mesh/v2/meshReferences.d.ts +5 -3
  70. package/dist/core/mesh/v2/meshReferences.d.ts.map +1 -1
  71. package/dist/core/mesh/v2/resolveMeshAppEnvironment.d.ts +4 -0
  72. package/dist/core/mesh/v2/resolveMeshAppEnvironment.d.ts.map +1 -0
  73. package/dist/core/mesh/v2/validateMeshTestStage.d.ts +22 -0
  74. package/dist/core/mesh/v2/validateMeshTestStage.d.ts.map +1 -0
  75. package/dist/core/runWithCleanup.d.ts +3 -0
  76. package/dist/core/runWithCleanup.d.ts.map +1 -0
  77. package/dist/core/runners/runDev.d.ts.map +1 -1
  78. package/dist/core/runners/runProd.d.ts.map +1 -1
  79. package/dist/core/runners/runTestE2e.d.ts.map +1 -1
  80. package/dist/core/runners/runTestUnit.d.ts.map +1 -1
  81. package/dist/core/teardownCompose.d.ts.map +1 -1
  82. package/dist/errors/PortConflictError.d.ts +1 -1
  83. package/dist/errors/PortConflictError.d.ts.map +1 -1
  84. package/dist/index.js +1159 -609
  85. package/dist/index.js.map +1 -1
  86. package/dist/templates/policy/dockerfile/dockerfile.rego +13 -13
  87. package/dist/utils/assertUniqueHostPortMappings.d.ts.map +1 -1
  88. package/dist/utils/checkPortCollision.d.ts.map +1 -1
  89. package/dist/utils/composePublishedPort.d.ts +3 -0
  90. package/dist/utils/composePublishedPort.d.ts.map +1 -0
  91. package/package.json +1 -1
  92. package/schemas/mesh-schema.json +311 -20
  93. package/templates/policy/dockerfile/dockerfile.rego +13 -13
package/dist/index.js CHANGED
@@ -1,14 +1,14 @@
1
1
  import { Command, Argument } from 'commander';
2
- import pc22 from 'picocolors';
2
+ import pc14 from 'picocolors';
3
3
  import fs, { existsSync, readFileSync, mkdirSync, writeFileSync, renameSync, statSync, realpathSync, lstatSync, readlinkSync, unlinkSync } from 'fs';
4
4
  import path from 'path';
5
5
  import { z } from 'zod';
6
6
  import { spawnSync, spawn } from 'child_process';
7
7
  import { fileURLToPath } from 'url';
8
8
  import { stringify, parse, parseAllDocuments } from 'yaml';
9
- import crypto from 'crypto';
9
+ import crypto, { createHash } from 'crypto';
10
+ import net, { isIP } from 'net';
10
11
  import os from 'os';
11
- import net from 'net';
12
12
  import { createInterface } from 'readline/promises';
13
13
  import { createRequire } from 'module';
14
14
 
@@ -139,8 +139,12 @@ var getBuildJson = (projectDir = process.cwd()) => {
139
139
  }
140
140
  return result.data;
141
141
  };
142
+ function isAbsoluteManagedPath(value) {
143
+ return path.isAbsolute(value) || /^[A-Za-z]:[\\/]/.test(value) || /^\\\\/.test(value) || /^\/\//.test(value);
144
+ }
142
145
  function resolveInsideProject(projectDir, relativePath, context) {
143
146
  if (!relativePath.trim()) throw new ConfigError({ ...context, value: relativePath, reason: "Path must not be empty" });
147
+ if (isAbsoluteManagedPath(relativePath)) throw new ConfigError({ ...context, value: relativePath, reason: "Builder-managed path must be relative to its project root" });
144
148
  const resolved = path.resolve(projectDir, relativePath);
145
149
  if (!isPathInside(projectDir, relativePath)) throw new ConfigError({ ...context, value: relativePath, reason: "Path escapes the project directory" });
146
150
  return resolved;
@@ -170,7 +174,7 @@ function runStep(executable, args, projectDir, ctx) {
170
174
  if (stderr) process.stderr.write(stderr);
171
175
  if (result.error || result.status !== 0) {
172
176
  console.error("\n" + "=".repeat(60));
173
- console.error(pc22.red(`\u{1F6A8} INFRASTRUCTURE CHECK FAILED \u{1F6A8}`));
177
+ console.error(pc14.red(`\u{1F6A8} INFRASTRUCTURE CHECK FAILED \u{1F6A8}`));
174
178
  console.error("=".repeat(60));
175
179
  console.error(`Failed Step : ${ctx.stepName}`);
176
180
  if (ctx.targetFile) {
@@ -197,7 +201,7 @@ function checkDockerfile(buildJson, projectDir) {
197
201
  const dockerfileRel = buildJson.dockerfile || "Dockerfile";
198
202
  const dockerfilePath = resolveApplicationDockerfile(projectDir, dockerfileRel);
199
203
  const content = readFileSync(dockerfilePath, "utf-8");
200
- console.log(pc22.cyan(`
204
+ console.log(pc14.cyan(`
201
205
  \u{1F50D} Linting Dockerfile (${dockerfileRel})...`));
202
206
  runStep(
203
207
  "docker",
@@ -267,7 +271,7 @@ function checkDockerfileContract(build, projectDir) {
267
271
  const relative = build.dockerfile ?? "Dockerfile";
268
272
  resolveApplicationDockerfile(root, relative);
269
273
  const policyDir = getDockerfilePolicyDir();
270
- console.log(pc22.cyan(`
274
+ console.log(pc14.cyan(`
271
275
  \u{1F50D} Validating Builder Dockerfile contract (${relative})...`));
272
276
  runStep("docker", ["run", "--rm", "--network", "none", "--mount", `type=bind,src=${root},dst=/project,readonly`, "--mount", `type=bind,src=${policyDir},dst=/builder-policy,readonly`, "-w", "/project", CONFTEST_IMAGE, "test", relative, "-p", "/builder-policy"], root, { stepName: "Dockerfile Contract", targetFile: relative });
273
277
  }
@@ -322,13 +326,41 @@ function getDeclaredYamlFiles(build, projectDir) {
322
326
  function checkYamlFiles(build, projectDir) {
323
327
  const root = resolveProjectDir(projectDir);
324
328
  const files = getDeclaredYamlFiles(build, root);
325
- if (files.length) console.log(pc22.cyan(`
329
+ if (files.length) console.log(pc14.cyan(`
326
330
  \u{1F50D} Validating ${files.length} declared V2 Compose file(s)...`));
327
331
  for (const file of files) {
328
332
  const absolutePath = resolveInsideProject(root, file.relativePath, { sourceFile: `${root}/build.json`, configPath: file.source, ...file.stage ? { stage: file.stage } : {} });
329
333
  loadComposeDocument(absolutePath, { sourceFile: `${root}/build.json`, configPath: file.source, stage: file.stage ?? "base", composition: "service" });
330
334
  }
331
335
  }
336
+ var GeneratedComposeNameAllocator = class {
337
+ occupied;
338
+ allocated = /* @__PURE__ */ new Map();
339
+ constructor(initialNames = []) {
340
+ this.occupied = new Set(initialNames);
341
+ }
342
+ allocate(identity, hint) {
343
+ const existing = this.allocated.get(identity);
344
+ if (existing) return existing;
345
+ const hash = createHash("sha256").update(identity).digest("hex");
346
+ const safeHint = hint.replace(/[^a-zA-Z0-9_-]/g, "-") || "item";
347
+ for (const candidate of [
348
+ safeHint,
349
+ ...[12, 16, 24, 32, 64].map((length) => `${safeHint}-${hash.slice(0, length)}`)
350
+ ]) {
351
+ if (this.occupied.has(candidate)) continue;
352
+ this.occupied.add(candidate);
353
+ this.allocated.set(identity, candidate);
354
+ return candidate;
355
+ }
356
+ throw new Error(`Unable to allocate unique Compose name for ${identity}`);
357
+ }
358
+ assertUnique() {
359
+ if (new Set(this.allocated.values()).size !== this.allocated.size) {
360
+ throw new Error("Internal generated Compose name collision");
361
+ }
362
+ }
363
+ };
332
364
 
333
365
  // src/core/composition/composeNetworks.ts
334
366
  function normalizeNetworks(value) {
@@ -336,13 +368,24 @@ function normalizeNetworks(value) {
336
368
  return value && typeof value === "object" ? { ...value } : {};
337
369
  }
338
370
 
371
+ // src/core/composition/selectAppEnvironmentEntries.ts
372
+ function selectAppEnvironmentEntries(layers, laterKeys = /* @__PURE__ */ new Set()) {
373
+ const winners = /* @__PURE__ */ new Map();
374
+ for (const layer of layers) {
375
+ for (const key of Object.keys(layer.values)) winners.set(key, layer);
376
+ }
377
+ for (const key of laterKeys) winners.delete(key);
378
+ return winners;
379
+ }
380
+
339
381
  // src/core/config/endpointProperties.ts
340
382
  function resolveEndpointProperty(endpoint, property, context) {
383
+ const reference = context.referencedObject ?? endpoint.logicalPath;
341
384
  const published = () => {
342
- if (!endpoint.effectivelyPublished || endpoint.publicHost === void 0 || endpoint.publicPort === void 0) throw new ConfigError({ ...context, configPath: context.configPath, referencedObject: endpoint.logicalPath, reason: `Endpoint property ${property} requires effective publication` });
385
+ if (!endpoint.effectivelyPublished || endpoint.publicHost === void 0 || endpoint.publicPort === void 0) throw new ConfigError({ ...context, referencedObject: reference, reason: `Endpoint property ${property} requires effective publication` });
343
386
  };
344
387
  const scheme = () => {
345
- if (!endpoint.scheme) throw new ConfigError({ ...context, referencedObject: endpoint.logicalPath, reason: `Endpoint property ${property} requires an endpoint scheme` });
388
+ if (!endpoint.scheme) throw new ConfigError({ ...context, referencedObject: reference, reason: `Endpoint property ${property} requires an endpoint scheme` });
346
389
  return endpoint.scheme;
347
390
  };
348
391
  switch (property) {
@@ -397,6 +440,18 @@ function assertAcyclicGraph(graph, context) {
397
440
  }
398
441
 
399
442
  // src/core/config/stageMerge.ts
443
+ function stageOverlayChain(stage) {
444
+ switch (stage) {
445
+ case "dev":
446
+ return ["dev"];
447
+ case "prod":
448
+ return ["prod"];
449
+ case "test":
450
+ return ["test"];
451
+ case "e2e":
452
+ return ["prod", "e2e"];
453
+ }
454
+ }
400
455
  function unionStable(base = [], overlay = []) {
401
456
  return [.../* @__PURE__ */ new Set([...base, ...overlay])];
402
457
  }
@@ -406,32 +461,40 @@ function mergeStringMap(base, overlay) {
406
461
 
407
462
  // src/core/config/resolveBuildStage.ts
408
463
  function resolveBuildStage(build, stage, sourceFile) {
409
- const overlay = build[stage] ?? {};
464
+ const context = (configPath, value, reason, referencedObject) => new ConfigError({ sourceFile, configPath, stage, composition: "service", value, ...referencedObject ? { referencedObject } : {}, reason });
465
+ const appEnv = { ...build.app.env ?? {} };
410
466
  const appEndpoints = structuredClone(build.app.endpoints ?? {});
411
- for (const [name, endpoint] of Object.entries(overlay.app?.endpoints ?? {})) appEndpoints[name] = { ...appEndpoints[name] ?? {}, ...endpoint };
412
467
  const dependencies = {};
413
468
  for (const [name, dep] of Object.entries(build.dependencies ?? {})) dependencies[name] = { ...dep, env: { ...dep.env ?? {} }, endpoints: structuredClone(dep.endpoints ?? {}), dependsOn: [...dep.dependsOn ?? []] };
414
- for (const [name, patch] of Object.entries(overlay.dependencies ?? {})) {
415
- const prior = dependencies[name] ?? { compose: void 0, env: {}, endpoints: {}, dependsOn: [] };
416
- prior.compose = patch.compose ?? prior.compose;
417
- prior.env = mergeStringMap(prior.env, patch.env);
418
- for (const [ep, epPatch] of Object.entries(patch.endpoints ?? {})) prior.endpoints[ep] = { ...prior.endpoints[ep] ?? {}, ...epPatch };
419
- prior.dependsOn = unionStable(prior.dependsOn, patch.dependsOn);
420
- dependencies[name] = prior;
421
- }
422
- const effective = { ...build, app: { env: mergeStringMap(build.app.env, overlay.app?.env), endpoints: appEndpoints }, dependencies, tester: build.tester ? { env: { ...build.tester.env ?? {} } } : void 0, overrideCompose: overlay["override-compose"] };
469
+ const layers = [{ stage: "base", appEnv: { ...build.app.env ?? {} } }];
470
+ for (const overlayStage of stageOverlayChain(stage)) {
471
+ const overlay = build[overlayStage];
472
+ if (!overlay) continue;
473
+ Object.assign(appEnv, overlay.app?.env ?? {});
474
+ for (const [name, endpoint] of Object.entries(overlay.app?.endpoints ?? {})) appEndpoints[name] = { ...appEndpoints[name] ?? {}, ...endpoint };
475
+ for (const [name, patch] of Object.entries(overlay.dependencies ?? {})) {
476
+ const inherited = dependencies[name];
477
+ if (inherited && patch.compose !== void 0) throw context(`${overlayStage}.dependencies.${name}.compose`, patch.compose, "A stage cannot replace the Compose implementation of an inherited dependency", `dependencies.${name}`);
478
+ const next = inherited ?? { compose: void 0, env: {}, endpoints: {}, dependsOn: [] };
479
+ if (!inherited && patch.compose !== void 0) next.compose = patch.compose;
480
+ next.env = mergeStringMap(next.env, patch.env);
481
+ for (const [endpointName, endpointPatch] of Object.entries(patch.endpoints ?? {})) next.endpoints[endpointName] = { ...next.endpoints[endpointName] ?? {}, ...endpointPatch };
482
+ next.dependsOn = unionStable(next.dependsOn, patch.dependsOn);
483
+ dependencies[name] = next;
484
+ }
485
+ layers.push({ stage: overlayStage, appEnv: { ...overlay.app?.env ?? {} }, ...overlay["override-compose"] ? { overrideCompose: overlay["override-compose"] } : {} });
486
+ }
487
+ const effective = { ...build, app: { env: appEnv, endpoints: appEndpoints }, dependencies, tester: build.tester ? { env: { ...build.tester.env ?? {} } } : void 0, layers };
423
488
  delete effective.dev;
424
489
  delete effective.prod;
425
490
  delete effective.test;
426
491
  delete effective.e2e;
427
- const context = (configPath, value, reason, referencedObject) => new ConfigError({ sourceFile, configPath, stage, composition: "service", value, ...referencedObject ? { referencedObject } : {}, reason });
428
492
  for (const [name, ep] of Object.entries(appEndpoints)) if (!Number.isInteger(ep.port) || ep.port < 1 || ep.port > 65535) throw context(`app.endpoints.${name}.port`, ep.port, "Effective endpoint requires a port in 1..65535");
429
493
  assertPrimaryEndpointInvariant(appEndpoints, { sourceFile, configPath: "app.endpoints", stage });
430
494
  const graph = /* @__PURE__ */ new Map();
431
495
  for (const [name, dep] of Object.entries(dependencies)) {
432
496
  if (typeof dep.compose !== "string" || !dep.compose.trim()) throw context(`dependencies.${name}.compose`, dep.compose, "Effective dependency requires compose");
433
- const endpoints = Object.entries(dep.endpoints);
434
- for (const [epName, ep] of endpoints) if (!ep.service || !Number.isInteger(ep.port) || ep.port < 1 || ep.port > 65535) throw context(`dependencies.${name}.endpoints.${epName}`, ep, "Effective dependency endpoint requires service and port");
497
+ for (const [epName, ep] of Object.entries(dep.endpoints)) if (!ep.service || !Number.isInteger(ep.port) || ep.port < 1 || ep.port > 65535) throw context(`dependencies.${name}.endpoints.${epName}`, ep, "Effective dependency endpoint requires service and port");
435
498
  assertPrimaryEndpointInvariant(dep.endpoints, { sourceFile, configPath: `dependencies.${name}.endpoints`, stage });
436
499
  const node = `dependencies.${name}`;
437
500
  graph.set(node, /* @__PURE__ */ new Set());
@@ -455,29 +518,42 @@ var BUILD_APP = /^app\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
455
518
  var BUILD_DEP = /^dependencies\.([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
456
519
  var MESH_APP = /^([a-z][a-z0-9-]*)\.app\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
457
520
  var MESH_DEP = /^([a-z][a-z0-9-]*)\.dependencies\.([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
458
- function parse2(raw, scope, sourcePath) {
459
- let m;
460
- if (scope === "build" && (m = BUILD_APP.exec(raw))) return valid({ raw, scope, target: "app", endpoint: m[1], property: m[2] }, sourcePath);
461
- if (scope === "build" && (m = BUILD_DEP.exec(raw))) return valid({ raw, scope, target: "dependency", dependency: m[1], endpoint: m[2], property: m[3] }, sourcePath);
462
- if (scope === "mesh" && (m = MESH_APP.exec(raw))) return valid({ raw, scope, meshService: m[1], target: "app", endpoint: m[2], property: m[3] }, sourcePath);
463
- if (scope === "mesh" && (m = MESH_DEP.exec(raw))) return valid({ raw, scope, meshService: m[1], target: "dependency", dependency: m[2], endpoint: m[3], property: m[4] }, sourcePath);
464
- throw new ConfigError({ configPath: sourcePath, value: raw, reason: `Invalid ${scope} endpoint reference` });
465
- }
466
- function valid(ref, sourcePath) {
467
- if (!ENDPOINT_PROPERTIES.includes(ref.property)) throw new ConfigError({ configPath: sourcePath, value: ref.property, reason: "Unknown endpoint property" });
521
+ function parse2(raw, scope, context) {
522
+ let match;
523
+ if (scope === "build" && (match = BUILD_APP.exec(raw))) return valid({ raw, scope, target: "app", endpoint: match[1], property: match[2] }, context);
524
+ if (scope === "build" && (match = BUILD_DEP.exec(raw))) return valid({ raw, scope, target: "dependency", dependency: match[1], endpoint: match[2], property: match[3] }, context);
525
+ if (scope === "mesh" && (match = MESH_APP.exec(raw))) return valid({ raw, scope, meshService: match[1], target: "app", endpoint: match[2], property: match[3] }, context);
526
+ if (scope === "mesh" && (match = MESH_DEP.exec(raw))) return valid({ raw, scope, meshService: match[1], target: "dependency", dependency: match[2], endpoint: match[3], property: match[4] }, context);
527
+ throw new ConfigError({ ...context, referencedObject: raw, value: raw, reason: `Invalid ${scope} endpoint reference` });
528
+ }
529
+ function valid(ref, context) {
530
+ if (!ENDPOINT_PROPERTIES.includes(ref.property)) {
531
+ throw new ConfigError({ ...context, referencedObject: ref.raw, value: ref.property, reason: "Unknown endpoint property" });
532
+ }
468
533
  return ref;
469
534
  }
470
- function collectBuilderReferences(value, scope, sourcePath) {
471
- const protectedValue = value.replace(/\$\$/g, "\0DOLLAR\0"), refs2 = [];
472
- for (const match of protectedValue.matchAll(/\$\{([^}]*)\}/g)) refs2.push(parse2(match[1], scope, sourcePath));
473
- return refs2;
535
+ function collectBuilderReferences(value, scope, context) {
536
+ const protectedValue = value.replace(/\$\$/g, "\0DOLLAR\0");
537
+ const refs = [];
538
+ for (const match of protectedValue.matchAll(/\$\{([^}]*)\}/g)) refs.push(parse2(match[1], scope, context));
539
+ return refs;
474
540
  }
475
- function interpolateBuilderReferences(value, scope, resolve) {
541
+ function interpolateBuilderReferences(value, scope, resolve, context) {
476
542
  const sentinel = "\0DOLLAR\0";
477
- return value.replace(/\$\$/g, sentinel).replace(/\$\{([^}]*)\}/g, (whole, body) => resolve(parse2(body, scope, "environment"))).replaceAll(sentinel, "$");
478
- }
479
- function assertTesterReferencesArePublic(env, scope, sourcePrefix) {
480
- for (const [key, value] of Object.entries(env)) for (const ref of collectBuilderReferences(value, scope, `${sourcePrefix}.${key}`)) if (!PUBLIC_ENDPOINT_PROPERTIES.has(ref.property)) throw new ConfigError({ configPath: `${sourcePrefix}.${key}`, value: ref.raw, reason: "Tester references may use only public endpoint properties" });
543
+ return value.replace(/\$\$/g, sentinel).replace(/\$\{([^}]*)\}/g, (_whole, body) => {
544
+ const ref = parse2(body, scope, context);
545
+ return resolve(ref, context);
546
+ }).replaceAll(sentinel, "$");
547
+ }
548
+ function assertTesterReferencesArePublic(env, scope, baseContext) {
549
+ for (const [key, value] of Object.entries(env)) {
550
+ const context = { ...baseContext, configPath: `${baseContext.configPath}.${key}` };
551
+ for (const ref of collectBuilderReferences(value, scope, context)) {
552
+ if (!PUBLIC_ENDPOINT_PROPERTIES.has(ref.property)) {
553
+ throw new ConfigError({ ...context, referencedObject: ref.raw, value: ref.raw, reason: "Tester references may use only public endpoint properties" });
554
+ }
555
+ }
556
+ }
481
557
  }
482
558
 
483
559
  // src/errors/PortConflictError.ts
@@ -485,8 +561,8 @@ var PortConflictError = class extends ConfigError {
485
561
  port;
486
562
  firstOwner;
487
563
  secondOwner;
488
- constructor(port, firstOwner, secondOwner, stage) {
489
- super({ sourceFile: "Builder effective composition", configPath: "publicPort", value: port, stage, reason: `Host port ${port} is claimed by both ${firstOwner} and ${secondOwner}. Builder does not remap fixed public ports.` });
564
+ constructor(port, firstOwner, secondOwner, stage, sourceFile = "Builder effective composition", composition) {
565
+ super({ sourceFile, configPath: secondOwner, value: port, stage, ...composition ? { composition } : {}, referencedObject: firstOwner, reason: `Host port ${port} is claimed by both ${firstOwner} and ${secondOwner}. Builder does not remap fixed public ports.` });
490
566
  this.name = "PortConflictError";
491
567
  this.port = port;
492
568
  this.firstOwner = firstOwner;
@@ -500,11 +576,11 @@ function isHostPortAvailableSync(port) {
500
576
  const result = spawnSync(process.execPath, ["-e", script], { stdio: "ignore", timeout: 3e3 });
501
577
  return result.status === 0;
502
578
  }
503
- function allocateHostPorts(projectDir, stage, intentsInDeterministicOrder, validationMode = false) {
579
+ function allocateHostPorts(projectDir, stage, intentsInDeterministicOrder, validationMode = false, context) {
504
580
  const reserved = /* @__PURE__ */ new Map(), allocated = /* @__PURE__ */ new Map();
505
581
  for (const intent of intentsInDeterministicOrder) if (typeof intent.requested === "number") {
506
582
  const owner = reserved.get(intent.requested);
507
- if (owner) throw new PortConflictError(intent.requested, owner, intent.logicalPath, stage);
583
+ if (owner) throw new PortConflictError(intent.requested, owner, intent.logicalPath, stage, context?.sourceFile, context?.composition);
508
584
  reserved.set(intent.requested, intent.logicalPath);
509
585
  allocated.set(intent.logicalPath, intent.requested);
510
586
  }
@@ -512,7 +588,7 @@ function allocateHostPorts(projectDir, stage, intentsInDeterministicOrder, valid
512
588
  let placeholder = 6e4;
513
589
  for (const intent of intentsInDeterministicOrder) if (intent.requested === "AUTO") {
514
590
  while (reserved.has(placeholder)) placeholder--;
515
- if (placeholder < 1) throw new ConfigError({ configPath: intent.logicalPath, stage, reason: "No validation placeholder port is available" });
591
+ if (placeholder < 1) throw new ConfigError({ ...context ?? {}, configPath: intent.logicalPath, stage, value: intent.requested, reason: "No validation placeholder port is available" });
516
592
  reserved.set(placeholder, intent.logicalPath);
517
593
  allocated.set(intent.logicalPath, placeholder--);
518
594
  }
@@ -536,7 +612,7 @@ function allocateHostPorts(projectDir, stage, intentsInDeterministicOrder, valid
536
612
  const scan = [...Array(65536 - AUTO_PORT_SCAN_START).keys()].map((i) => i + AUTO_PORT_SCAN_START).concat([...Array(19999 - 1024 + 1).keys()].map((i) => i + 1024));
537
613
  selected = scan.find((p) => !reserved.has(p) && isHostPortAvailableSync(p));
538
614
  }
539
- if (selected === void 0) throw new ConfigError({ sourceFile: "Builder effective composition", configPath: intent.logicalPath, stage, reason: "No available host port could be allocated" });
615
+ if (selected === void 0) throw new ConfigError({ sourceFile: context?.sourceFile ?? "Builder effective composition", ...context?.composition ? { composition: context.composition } : {}, configPath: intent.logicalPath, stage, value: intent.requested, reason: "No available host port could be allocated" });
540
616
  reserved.set(selected, intent.logicalPath);
541
617
  allocated.set(intent.logicalPath, selected);
542
618
  nextCache[intent.logicalPath] = selected;
@@ -549,6 +625,26 @@ function allocateHostPorts(projectDir, stage, intentsInDeterministicOrder, valid
549
625
  }
550
626
  return allocated;
551
627
  }
628
+ var EXEC_MODE_KEY = "EXEC_MODE";
629
+ var INFRA_MODE_KEY = "INFRA_MODE";
630
+ var PORT_KEY = "PORT";
631
+ function assertNoBuilderOwnedEnvKeys(env, keys, context) {
632
+ for (const key of keys) {
633
+ if (!(key in env)) continue;
634
+ throw new ConfigError({ sourceFile: context.sourceFile, configPath: `${context.configPath}.${key}`, stage: context.stage, composition: context.composition, value: env[key], reason: `User-controlled environment cannot set Builder-owned key "${key}"` });
635
+ }
636
+ }
637
+ function assertDotenvDoesNotDefineKeys(filePath, keys, context) {
638
+ if (!fs.existsSync(filePath)) return;
639
+ const forbidden = new Set(keys), lines = fs.readFileSync(filePath, "utf8").split(/\r?\n/);
640
+ for (let index = 0; index < lines.length; index += 1) {
641
+ const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(lines[index]);
642
+ if (!match) continue;
643
+ const key = match[1];
644
+ if (!forbidden.has(key)) continue;
645
+ throw new ConfigError({ sourceFile: filePath, configPath: `${context.configPath}.${key}`, stage: context.stage, composition: context.composition, value: `line ${index + 1}`, reason: `Environment file cannot set Builder-owned key "${key}"` });
646
+ }
647
+ }
552
648
  function normalizeProjectName(name, projectDir) {
553
649
  let normalized = name.toLowerCase().replace(/[^a-z0-9_-]/g, "-").replace(/^[-_]+/, "").replace(/[-_]+$/, "");
554
650
  if (!normalized || !/^[a-z0-9]/.test(normalized)) {
@@ -642,14 +738,33 @@ function volumeShort(v, base, out) {
642
738
  if (mount?.type !== "bind" || !mount.source || /^(?:[\\/]|~|[a-z]:)/i.test(mount.source)) return v;
643
739
  return rewriteVolumeSource(v, rebase(mount.source, base, out));
644
740
  }
741
+ function isRemoteBuildContext(value) {
742
+ return /^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(value) || /^[^/@\s]+@[^:\s]+:.+/.test(value);
743
+ }
744
+ function rebaseAdditionalContext(value, base, out) {
745
+ if (value.startsWith("service:") || isRemoteBuildContext(value)) return value;
746
+ return rebase(value, base, out);
747
+ }
748
+ function rebaseAdditionalContexts(value, base, out) {
749
+ if (Array.isArray(value)) return value.map((entry) => {
750
+ if (typeof entry !== "string") return entry;
751
+ const separator = entry.indexOf("=");
752
+ if (separator < 0) return entry;
753
+ return `${entry.slice(0, separator)}=${rebaseAdditionalContext(entry.slice(separator + 1), base, out)}`;
754
+ });
755
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([name, context]) => [name, typeof context === "string" ? rebaseAdditionalContext(context, base, out) : context]));
756
+ return value;
757
+ }
645
758
  function rebaseComposePaths(document, composeFilePath, outputProjectDir) {
646
759
  const doc = structuredClone(document), base = path.dirname(composeFilePath), out = path.resolve(outputProjectDir);
647
760
  for (const svc of Object.values(doc.services ?? {})) {
648
- if (typeof svc.build === "string") svc.build = rebase(svc.build, base, out);
649
- else if (svc.build && typeof svc.build === "object") {
761
+ if (typeof svc.build === "string") {
762
+ if (!isRemoteBuildContext(svc.build)) svc.build = rebase(svc.build, base, out);
763
+ } else if (svc.build && typeof svc.build === "object") {
650
764
  const b = svc.build;
651
765
  const context = typeof b.context === "string" ? b.context : ".";
652
- b.context = rebase(context, base, out);
766
+ if (!isRemoteBuildContext(context)) b.context = rebase(context, base, out);
767
+ if (b.additional_contexts !== void 0) b.additional_contexts = rebaseAdditionalContexts(b.additional_contexts, base, out);
653
768
  }
654
769
  if (typeof svc.env_file === "string") svc.env_file = rebase(svc.env_file, base, out);
655
770
  else if (Array.isArray(svc.env_file)) svc.env_file = svc.env_file.map((v) => typeof v === "string" ? rebase(v, base, out) : v && typeof v === "object" && typeof v.path === "string" ? { ...v, path: rebase(v.path, base, out) } : v);
@@ -714,7 +829,7 @@ function normalizeComposeEnvironment(value, context) {
714
829
  if (typeof item !== "string") throw new ConfigError({ configPath: context, value: item, reason: "Compose environment entries must be strings" });
715
830
  const at = item.indexOf("=");
716
831
  if (at < 0) {
717
- result[item] = process.env[item] ?? "";
832
+ result[item] = null;
718
833
  continue;
719
834
  }
720
835
  result[item.slice(0, at)] = item.slice(at + 1);
@@ -723,7 +838,10 @@ function normalizeComposeEnvironment(value, context) {
723
838
  }
724
839
  if (typeof value !== "object") throw new ConfigError({ configPath: context, value, reason: "Compose environment must be a map or list" });
725
840
  for (const [key, val] of Object.entries(value)) {
726
- if (val === null || val === void 0) continue;
841
+ if (val === null || val === void 0) {
842
+ result[key] = null;
843
+ continue;
844
+ }
727
845
  if (typeof val === "object") throw new ConfigError({ configPath: `${context}.${key}`, value: val, reason: "Compose environment value must be scalar" });
728
846
  result[key] = String(val);
729
847
  }
@@ -733,16 +851,81 @@ function mergeComposeEnvironment(service, overlay) {
733
851
  service.environment = { ...normalizeComposeEnvironment(service.environment, "service.environment"), ...overlay };
734
852
  }
735
853
 
854
+ // src/core/composition/composeBuildResources.ts
855
+ function buildObject(service) {
856
+ return service.build && typeof service.build === "object" && !Array.isArray(service.build) ? service.build : void 0;
857
+ }
858
+ function rewriteBuildSecretReferences(service, names) {
859
+ const build = buildObject(service);
860
+ if (!build || !Array.isArray(build.secrets)) return;
861
+ build.secrets = build.secrets.map((entry) => {
862
+ if (typeof entry === "string") return names.get(entry) ?? entry;
863
+ if (entry && typeof entry === "object" && typeof entry.source === "string") {
864
+ return { ...entry, source: names.get(entry.source) ?? entry.source };
865
+ }
866
+ return entry;
867
+ });
868
+ }
869
+ function collectBuildSecretReferences(service) {
870
+ const build = buildObject(service);
871
+ if (!build || !Array.isArray(build.secrets)) return [];
872
+ return build.secrets.flatMap((entry) => {
873
+ if (typeof entry === "string") return [entry];
874
+ return entry && typeof entry === "object" && typeof entry.source === "string" ? [entry.source] : [];
875
+ });
876
+ }
877
+ function assertNoServiceBuildContexts(service, configPath, sourceFile) {
878
+ const contexts = buildObject(service)?.additional_contexts;
879
+ const values = Array.isArray(contexts) ? contexts.map((entry) => typeof entry === "string" ? entry.slice(entry.indexOf("=") + 1) : entry) : contexts && typeof contexts === "object" ? Object.values(contexts) : [];
880
+ if (values.some((value) => typeof value === "string" && value.startsWith("service:"))) {
881
+ throw new ConfigError({
882
+ sourceFile,
883
+ configPath: `${configPath}.build.additional_contexts`,
884
+ reason: "Compose service-reference additional_contexts are unsupported"
885
+ });
886
+ }
887
+ }
888
+
889
+ // src/core/composition/namespaceResourceDefinition.ts
890
+ function namespaceResourceDefinition(originalKey, definition) {
891
+ if (definition === null || typeof definition !== "object" || Array.isArray(definition)) {
892
+ return definition;
893
+ }
894
+ const result = structuredClone(definition);
895
+ if (result.external === true) {
896
+ result.name ??= originalKey;
897
+ } else {
898
+ delete result.name;
899
+ }
900
+ return result;
901
+ }
902
+
736
903
  // src/core/composition/namespaceDependencyCompose.ts
737
904
  var entries = (obj) => obj && typeof obj === "object" && !Array.isArray(obj) ? Object.entries(obj) : [];
738
905
  function namespaceDependencyCompose(options) {
739
906
  const { document, namespacePrefix: prefix } = options, doc = structuredClone(document);
740
- const make = (kind, keys) => new Map(keys.map((k) => [k, `${prefix}--${kind}--${k}`]));
741
- const serviceNameMap = make("", Object.keys(doc.services ?? {}));
742
- for (const [k, v] of serviceNameMap) serviceNameMap.set(k, `${prefix}--${k}`);
907
+ const originalServices = doc.services ?? {};
908
+ const usesImplicitDefault = Object.values(originalServices).some((service) => service.network_mode === void 0 && service.networks === void 0);
909
+ if (usesImplicitDefault && !Object.hasOwn(doc.networks ?? {}, "default")) doc.networks = { ...doc.networks ?? {}, default: {} };
910
+ const allocator = options.allocator ?? new GeneratedComposeNameAllocator();
911
+ const identityPrefix = options.identityPrefix ?? JSON.stringify(["dependency", options.dependencyKey, prefix]);
912
+ const make = (kind, keys) => new Map(keys.sort().map((k) => [k, allocator.allocate(JSON.stringify([identityPrefix, kind, k]), kind === "service" ? `${prefix}--${k}` : `${prefix}--${kind}--${k}`)]));
913
+ const serviceNameMap = make("service", Object.keys(doc.services ?? {}));
743
914
  const volumeNameMap = make("volume", Object.keys(doc.volumes ?? {})), networkNameMap = make("network", Object.keys(doc.networks ?? {})), configNameMap = make("config", Object.keys(doc.configs ?? {})), secretNameMap = make("secret", Object.keys(doc.secrets ?? {}));
744
915
  const rewriteKeys = (obj, map) => Object.fromEntries(entries(obj).map(([k, v]) => [map.get(k) ?? k, v]));
745
- const rewriteResourceRefs = (svc) => {
916
+ const rewriteResourceDefinitions = (obj, map) => Object.fromEntries(entries(obj).map(([key, definition]) => [map.get(key) ?? key, namespaceResourceDefinition(key, definition)]));
917
+ const addOriginalNetworkAliases = (name, svc) => {
918
+ if (svc.network_mode !== void 0 || svc.networks === void 0) return;
919
+ const attached = Array.isArray(svc.networks) ? Object.fromEntries(svc.networks.filter((network) => typeof network === "string").map((network) => [network, null])) : svc.networks && typeof svc.networks === "object" ? { ...svc.networks } : {};
920
+ for (const [network, rawOptions] of Object.entries(attached)) {
921
+ const options2 = rawOptions && typeof rawOptions === "object" && !Array.isArray(rawOptions) ? rawOptions : {};
922
+ const aliases = Array.isArray(options2.aliases) ? options2.aliases.filter((alias) => typeof alias === "string") : [];
923
+ attached[network] = { ...options2, aliases: [.../* @__PURE__ */ new Set([...aliases, name])] };
924
+ }
925
+ svc.networks = attached;
926
+ };
927
+ const rewriteResourceRefs = (svc, originalName) => {
928
+ rewriteBuildSecretReferences(svc, secretNameMap);
746
929
  if (Array.isArray(svc.depends_on)) {
747
930
  svc.depends_on = svc.depends_on.map((v) => typeof v === "string" ? serviceNameMap.get(v) ?? v : v);
748
931
  } else if (svc.depends_on && typeof svc.depends_on === "object") svc.depends_on = rewriteKeys(svc.depends_on, serviceNameMap);
@@ -757,33 +940,110 @@ function namespaceDependencyCompose(options) {
757
940
  }
758
941
  if (Array.isArray(svc.volumes_from)) svc.volumes_from = svc.volumes_from.map((v) => typeof v === "string" ? v.replace(/^([^:]+)(.*)$/, (all, n, rest) => `${serviceNameMap.get(n) ?? n}${rest}`) : v);
759
942
  if (Array.isArray(svc.volumes)) svc.volumes = svc.volumes.map((v) => namespaceVolume(v, volumeNameMap));
760
- if (svc.networks === void 0 && svc.network_mode === void 0 && svc.extends === void 0 && networkNameMap.has("default")) svc.networks = { default: null };
943
+ if (svc.networks === void 0 && svc.network_mode === void 0 && networkNameMap.has("default")) svc.networks = { default: null };
761
944
  for (const key of ["ipc", "pid"]) if (typeof svc[key] === "string" && svc[key].startsWith("service:")) svc[key] = `service:${serviceNameMap.get(svc[key].slice(8)) ?? svc[key].slice(8)}`;
762
- if (svc.extends && typeof svc.extends === "object" && !svc.extends.file) {
763
- const ref = svc.extends;
764
- if (typeof ref.service === "string") ref.service = serviceNameMap.get(ref.service) ?? ref.service;
765
- }
766
945
  if (Array.isArray(svc.networks)) svc.networks = svc.networks.map((v) => typeof v === "string" ? networkNameMap.get(v) ?? v : v);
767
946
  else if (svc.networks && typeof svc.networks === "object") svc.networks = rewriteKeys(svc.networks, networkNameMap);
768
947
  for (const key of ["configs", "secrets"]) if (Array.isArray(svc[key])) svc[key] = svc[key].map((v) => typeof v === "string" ? (key === "configs" ? configNameMap : secretNameMap).get(v) ?? v : v && typeof v === "object" ? { ...v, source: (key === "configs" ? configNameMap : secretNameMap).get(v.source) ?? v.source } : v);
948
+ addOriginalNetworkAliases(originalName, svc);
769
949
  };
770
- for (const svc of Object.values(doc.services ?? {})) rewriteResourceRefs(svc);
950
+ for (const [name, svc] of Object.entries(originalServices)) rewriteResourceRefs(svc, name);
771
951
  doc.services = rewriteKeys(doc.services, serviceNameMap);
772
- if (doc.volumes) doc.volumes = rewriteKeys(doc.volumes, volumeNameMap);
773
- if (doc.networks) doc.networks = rewriteKeys(doc.networks, networkNameMap);
774
- if (doc.configs) doc.configs = rewriteKeys(doc.configs, configNameMap);
775
- if (doc.secrets) doc.secrets = rewriteKeys(doc.secrets, secretNameMap);
952
+ if (doc.volumes) doc.volumes = rewriteResourceDefinitions(doc.volumes, volumeNameMap);
953
+ if (doc.networks) doc.networks = rewriteResourceDefinitions(doc.networks, networkNameMap);
954
+ if (doc.configs) doc.configs = rewriteResourceDefinitions(doc.configs, configNameMap);
955
+ if (doc.secrets) doc.secrets = rewriteResourceDefinitions(doc.secrets, secretNameMap);
776
956
  return { document: doc, serviceNameMap, volumeNameMap, networkNameMap, configNameMap, secretNameMap };
777
957
  }
778
958
 
959
+ // src/core/composition/validateComposeResourceReferences.ts
960
+ function validateComposeResourceReferences(document, context, onlyServices) {
961
+ const fail = (configPath, kind, name) => {
962
+ throw new ConfigError({
963
+ sourceFile: context.sourceFile,
964
+ configPath,
965
+ ...context.stage ? { stage: context.stage } : {},
966
+ composition: context.composition,
967
+ referencedObject: name,
968
+ reason: `Compose ${kind} reference "${name}" has no top-level definition`
969
+ });
970
+ };
971
+ const exists = (kind, name) => {
972
+ const definitions = document[kind === "volume" ? "volumes" : kind === "network" ? "networks" : kind === "config" ? "configs" : "secrets"];
973
+ return Boolean(definitions && Object.hasOwn(definitions, name));
974
+ };
975
+ const check = (path22, kind, name) => {
976
+ if (kind === "network" && name === "default") return;
977
+ if (!exists(kind, name)) fail(path22, kind, name);
978
+ };
979
+ for (const [serviceName, service] of Object.entries(document.services ?? {})) {
980
+ validateServiceResources(serviceName, service, check);
981
+ }
982
+ }
983
+ function validateServiceResources(serviceName, service, check) {
984
+ for (const mount of Array.isArray(service.volumes) ? service.volumes : []) {
985
+ const parsed = parseVolume(mount);
986
+ if (parsed?.type === "volume" && parsed.source) {
987
+ check(`services.${serviceName}.volumes`, "volume", parsed.source);
988
+ }
989
+ }
990
+ const networks = service.networks;
991
+ const networkNames = Array.isArray(networks) ? networks.filter((name) => typeof name === "string") : networks && typeof networks === "object" ? Object.keys(networks) : [];
992
+ for (const name of networkNames) {
993
+ check(`services.${serviceName}.networks`, "network", name);
994
+ }
995
+ for (const kind of ["configs", "secrets"]) {
996
+ const entries2 = service[kind];
997
+ if (!Array.isArray(entries2)) continue;
998
+ for (const entry of entries2) {
999
+ const name = typeof entry === "string" ? entry : entry && typeof entry === "object" && typeof entry.source === "string" ? entry.source : void 0;
1000
+ if (name) check(`services.${serviceName}.${kind}`, kind === "configs" ? "config" : "secret", name);
1001
+ }
1002
+ }
1003
+ for (const name of collectBuildSecretReferences(service)) {
1004
+ check(`services.${serviceName}.build.secrets`, "secret", name);
1005
+ }
1006
+ }
1007
+
1008
+ // src/core/composition/assertComposeLifecycleAcyclic.ts
1009
+ function assertComposeLifecycleAcyclic(services, context) {
1010
+ const graph = new Map(
1011
+ Object.keys(services).map((name) => [name, /* @__PURE__ */ new Set()])
1012
+ );
1013
+ for (const [name, service] of Object.entries(services)) {
1014
+ const value = service.depends_on;
1015
+ const targets = Array.isArray(value) ? value.filter((item) => typeof item === "string") : value && typeof value === "object" ? Object.keys(value) : [];
1016
+ for (const target of targets) {
1017
+ if (graph.has(target)) graph.get(name).add(target);
1018
+ }
1019
+ }
1020
+ assertAcyclicGraph(graph, context);
1021
+ }
1022
+
1023
+ // src/core/composition/composeHealthcheck.ts
1024
+ function isEnabledValidComposeHealthcheck(value) {
1025
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1026
+ const health = value;
1027
+ if (health.disable === true) return false;
1028
+ const test = health.test;
1029
+ if (typeof test === "string") return test.trim().length > 0;
1030
+ if (!Array.isArray(test) || !test.every((item) => typeof item === "string")) return false;
1031
+ if (test[0] !== "CMD" && test[0] !== "CMD-SHELL") return false;
1032
+ return test.length >= 2 && test.slice(1).some((item) => item.trim().length > 0);
1033
+ }
1034
+
779
1035
  // src/core/composition/validateDependencyCompose.ts
780
1036
  function validateDependencyCompose(dependencyKey, dependency, document, context) {
781
1037
  const fail = (configPath, reason, value) => {
782
1038
  throw new ConfigError({ sourceFile: context.composePath, configPath, stage: context.stage, composition: "service", ...value === void 0 ? {} : { value }, reason: `Dependency "${dependencyKey}": ${reason}` });
783
1039
  };
784
1040
  if (document.include !== void 0) fail("include", "Compose include is unsupported for atomic dependency implementations");
1041
+ validateComposeResourceReferences(document, { sourceFile: context.composePath, stage: context.stage, composition: "service" });
785
1042
  const services = document.services ?? {};
786
1043
  for (const [name, svc] of Object.entries(services)) {
1044
+ assertNoServiceBuildContexts(svc, `services.${name}`, context.composePath);
1045
+ if (svc.profiles !== void 0) fail(`services.${name}.profiles`, "dependency Compose profiles are unsupported because a materialized dependency is atomic");
1046
+ if (svc.extends !== void 0) fail(`services.${name}.extends`, "dependency Compose extends is unsupported until effective endpoint-owner networking and health can be validated");
787
1047
  if (svc.ports !== void 0) fail(`services.${name}.ports`, "raw dependency ports are forbidden");
788
1048
  if (svc.network_mode === "host") fail(`services.${name}.network_mode`, "host network mode is forbidden");
789
1049
  if (svc.privileged === true) fail(`services.${name}.privileged`, `privileged services are forbidden`);
@@ -806,13 +1066,13 @@ function validateDependencyCompose(dependencyKey, dependency, document, context)
806
1066
  for (const ref of svc.volumes_from) if (typeof ref === "string") internalRefs.push(["volumes_from", ref.split(":")[0]]);
807
1067
  }
808
1068
  for (const key of ["ipc", "pid"]) if (typeof svc[key] === "string" && svc[key].startsWith("service:")) internalRefs.push([key, svc[key].slice(8)]);
809
- if (svc.extends && typeof svc.extends === "object") {
810
- const ref = svc.extends;
811
- if (ref.file !== void 0) fail(`services.${name}.extends.file`, "external extends is unsupported for atomic dependency implementations");
812
- if (typeof ref.service === "string") internalRefs.push(["extends.service", ref.service]);
813
- }
814
1069
  for (const [property, target] of internalRefs) if (!services[target]) fail(`services.${name}.${property}`, `internal service reference "${target}" does not exist in this dependency Compose bundle`, target);
815
1070
  }
1071
+ assertComposeLifecycleAcyclic(services, {
1072
+ sourceFile: context.composePath,
1073
+ stage: context.stage,
1074
+ composition: "service"
1075
+ });
816
1076
  if (!Object.keys(dependency.endpoints).length) return;
817
1077
  if (!Object.keys(services).length) fail("services", "endpoint-bearing dependency Compose must define services");
818
1078
  const owners = /* @__PURE__ */ new Set();
@@ -823,8 +1083,7 @@ function validateDependencyCompose(dependencyKey, dependency, document, context)
823
1083
  }
824
1084
  for (const owner of owners) {
825
1085
  if (services[owner].network_mode !== void 0) fail(`services.${owner}.network_mode`, `endpoint owner cannot use network_mode`);
826
- const health = services[owner].healthcheck;
827
- if (!health || health.disable === true || !health.test || typeof health.test === "string" && !health.test.trim() || Array.isArray(health.test) && (!health.test.length || health.test[0] === "NONE" || health.test.every((v) => typeof v === "string" && !v.trim()))) fail(`services.${owner}.healthcheck`, `endpoint owner requires an enabled, non-empty healthcheck`);
1086
+ if (!isEnabledValidComposeHealthcheck(services[owner].healthcheck)) fail(`services.${owner}.healthcheck`, "endpoint owner requires a valid enabled Compose healthcheck");
828
1087
  }
829
1088
  }
830
1089
  function canonicalBuildContext(value, baseDir) {
@@ -834,24 +1093,48 @@ function isSameBuildContext(actual, expected, baseDir) {
834
1093
  return canonicalBuildContext(actual, baseDir) === canonicalBuildContext(expected, baseDir);
835
1094
  }
836
1095
  function validateAndPrepareAppOverride(document, context) {
837
- const fail = (path20, reason, value) => {
838
- throw new ConfigError({ sourceFile: context.file, configPath: path20, stage: context.stage, composition: "service", ...value === void 0 ? {} : { value }, reason });
1096
+ const fail = (path22, reason, value) => {
1097
+ throw new ConfigError({ sourceFile: context.file, configPath: path22, stage: context.stage, composition: "service", ...value === void 0 ? {} : { value }, reason });
839
1098
  };
1099
+ const allowedRootKeys = /* @__PURE__ */ new Set(["services", "volumes", "networks", "configs", "secrets"]);
1100
+ for (const key of Object.keys(document)) if (!key.startsWith("x-") && !allowedRootKeys.has(key)) fail(key, "unsupported override Compose top-level field");
840
1101
  const keys = Object.keys(document.services ?? {});
841
1102
  if (keys.length !== 1 || keys[0] !== "app") fail("services", "override must define exactly one service named app");
1103
+ validateComposeResourceReferences(document, { sourceFile: context.file, stage: context.stage, composition: "service" });
842
1104
  const app = structuredClone(document.services.app);
843
- for (const k of ["ports", "depends_on", "network_mode", "container_name", "privileged"]) if (app[k] !== void 0) fail(`services.app.${k}`, "override cannot own endpoint or lifecycle behavior");
844
- if (app.healthcheck && typeof app.healthcheck === "object") {
845
- const health = app.healthcheck;
846
- 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");
1105
+ for (const k of ["ports", "depends_on", "network_mode", "container_name", "privileged", "profiles", "extends", "env_file"]) if (app[k] !== void 0) fail(`services.app.${k}`, "override cannot own endpoint or lifecycle behavior");
1106
+ if (Object.hasOwn(app, "healthcheck")) {
1107
+ const healthcheck = app.healthcheck;
1108
+ if (healthcheck === null || typeof healthcheck !== "object" || Array.isArray(healthcheck)) {
1109
+ fail(
1110
+ "services.app.healthcheck",
1111
+ "override healthcheck must be a mapping of timing fields",
1112
+ healthcheck
1113
+ );
1114
+ }
1115
+ const allowedTiming = /* @__PURE__ */ new Set([
1116
+ "interval",
1117
+ "timeout",
1118
+ "retries",
1119
+ "start_period",
1120
+ "start_interval"
1121
+ ]);
1122
+ for (const key of Object.keys(healthcheck)) {
1123
+ if (!allowedTiming.has(key)) {
1124
+ fail(
1125
+ `services.app.healthcheck.${key}`,
1126
+ "override may set only healthcheck timing fields"
1127
+ );
1128
+ }
1129
+ }
847
1130
  }
848
1131
  if (typeof app.build === "string") {
849
1132
  fail("services.app.build", "override cannot replace Builder-owned app build context; use object-form build.args for build arguments", app.build);
850
1133
  }
851
1134
  if (app.build && typeof app.build === "object") {
852
1135
  const build = app.build;
853
- for (const key of ["target", "dockerfile"]) {
854
- if (build[key] !== void 0) {
1136
+ for (const key of Object.keys(build)) {
1137
+ if (!["args", "context"].includes(key)) {
855
1138
  fail(`services.app.build.${key}`, "override cannot change Builder-owned build configuration");
856
1139
  }
857
1140
  }
@@ -867,24 +1150,26 @@ function validateAndPrepareAppOverride(document, context) {
867
1150
  const env = normalizeComposeEnvironment(app.environment, "services.app.environment");
868
1151
  for (const k of ["EXEC_MODE", "INFRA_MODE"]) if (k in env) fail(`services.app.environment.${k}`, "override cannot set Builder-owned environment");
869
1152
  app.environment = env;
1153
+ const allocator = context.allocator ?? new GeneratedComposeNameAllocator();
870
1154
  const resourceKeys = ["volumes", "networks", "configs", "secrets"];
871
1155
  const resources = {};
872
1156
  for (const kind of resourceKeys) {
873
- const defs = document[kind] ?? {}, refs2 = /* @__PURE__ */ new Set(), value = app[kind];
1157
+ const defs = document[kind] ?? {}, refs = /* @__PURE__ */ new Set(), value = app[kind];
874
1158
  if (Array.isArray(value)) for (const ref of value) {
875
1159
  if (kind === "volumes") {
876
1160
  const volume = parseVolume(ref);
877
- if (volume?.type === "volume" && volume.source) refs2.add(volume.source);
878
- } else if (typeof ref === "string") refs2.add(ref);
879
- else if (ref && typeof ref === "object" && typeof ref.source === "string") refs2.add(ref.source);
1161
+ if (volume?.type === "volume" && volume.source) refs.add(volume.source);
1162
+ } else if (typeof ref === "string") refs.add(ref);
1163
+ else if (ref && typeof ref === "object" && typeof ref.source === "string") refs.add(ref.source);
880
1164
  }
881
- else if (value && typeof value === "object") for (const name of Object.keys(value)) refs2.add(name);
1165
+ else if (value && typeof value === "object") for (const name of Object.keys(value)) refs.add(name);
882
1166
  const names = /* @__PURE__ */ new Map(), mapped = {};
883
1167
  for (const [name, definition] of Object.entries(defs)) {
884
- if (!refs2.has(name)) fail(`${kind}.${name}`, "override resource must be consumed by app");
885
- const target = `app-override--${context.stage}--${kind.slice(0, -1)}--${name}`;
1168
+ if (!refs.has(name)) fail(`${kind}.${name}`, "override resource must be consumed by app");
1169
+ const prefix = context.resourceNamespace && context.resourceNamespace !== "app" ? `svc--${context.resourceNamespace}--app-override` : "app-override";
1170
+ const target = allocator.allocate(JSON.stringify(["service", context.resourceNamespace ?? "app", "override", context.stage, kind, name]), `${prefix}--${context.stage}--${kind.slice(0, -1)}--${name}`);
886
1171
  names.set(name, target);
887
- mapped[target] = definition;
1172
+ mapped[target] = namespaceResourceDefinition(name, definition);
888
1173
  }
889
1174
  if (names.size) resources[kind] = mapped;
890
1175
  if (Array.isArray(value)) app[kind] = value.map((ref) => kind === "volumes" ? namespaceVolume(ref, names) : typeof ref === "string" ? names.get(ref) ?? ref : ref && typeof ref === "object" && typeof ref.source === "string" ? { ...ref, source: names.get(ref.source) ?? ref.source } : ref);
@@ -893,6 +1178,26 @@ function validateAndPrepareAppOverride(document, context) {
893
1178
  return { app, resources };
894
1179
  }
895
1180
 
1181
+ // src/core/composition/mergeAppOverride.ts
1182
+ function isMap(value) {
1183
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
1184
+ const prototype = Object.getPrototypeOf(value);
1185
+ return prototype === Object.prototype || prototype === null;
1186
+ }
1187
+ function mergeValue(inherited, overlay) {
1188
+ if (overlay === void 0) return structuredClone(inherited);
1189
+ if (!isMap(inherited) || !isMap(overlay)) return structuredClone(overlay);
1190
+ return Object.fromEntries(
1191
+ [.../* @__PURE__ */ new Set([...Object.keys(inherited), ...Object.keys(overlay)])].map((key) => [
1192
+ key,
1193
+ Object.hasOwn(overlay, key) ? mergeValue(inherited[key], overlay[key]) : structuredClone(inherited[key])
1194
+ ])
1195
+ );
1196
+ }
1197
+ function mergeAppOverride(inherited, overlay) {
1198
+ return mergeValue(inherited, overlay);
1199
+ }
1200
+
896
1201
  // src/core/composition/dependencyLifecycle.ts
897
1202
  function asMap(value) {
898
1203
  if (Array.isArray(value)) return Object.fromEntries(value.filter((v) => typeof v === "string").map((v) => [v, {}]));
@@ -947,13 +1252,13 @@ function buildStandaloneDependencyEndpoints(key, build, serviceNames, materializ
947
1252
  function getExecutionProfile(stage, full) {
948
1253
  switch (stage) {
949
1254
  case "dev":
950
- return { configStage: "dev", appTarget: "dev", runtimeStage: "dev", integrated: full, attachTester: false };
1255
+ return { configStage: "dev", envStage: "dev", appTarget: "dev", execMode: "dev", infraMode: full ? "integrated" : "isolated", attachTester: false };
951
1256
  case "prod":
952
- return { configStage: "prod", appTarget: "prod", runtimeStage: "prod", integrated: true, attachTester: false };
1257
+ return { configStage: "prod", envStage: "prod", appTarget: "prod", execMode: "prod", infraMode: "integrated", attachTester: false };
953
1258
  case "test":
954
- return { configStage: "test", appTarget: "test", runtimeStage: "test", integrated: false, attachTester: false };
1259
+ return { configStage: "test", envStage: "test", appTarget: "test", execMode: "test", infraMode: "isolated", attachTester: false };
955
1260
  case "e2e":
956
- return { configStage: "e2e", appTarget: "prod", runtimeStage: "e2e", integrated: true, attachTester: true, testerTarget: "test-e2e" };
1261
+ return { configStage: "e2e", envStage: "e2e", appTarget: "prod", execMode: "prod", infraMode: "integrated", attachTester: true, testerTarget: "test-e2e" };
957
1262
  }
958
1263
  }
959
1264
  function mergeDocument(target, source, context) {
@@ -962,7 +1267,7 @@ function mergeDocument(target, source, context) {
962
1267
  if (!src) continue;
963
1268
  const dst = target[section] ??= {};
964
1269
  for (const [key, value] of Object.entries(src)) {
965
- if (key in dst) throw new ConfigError({ configPath: `${section}.${key}`, referencedObject: context, reason: "Internal Compose namespace collision" });
1270
+ if (key in dst) throw new ConfigError({ ...context, configPath: `${context.configPath}.${section}.${key}`, value: key, reason: "Internal Compose namespace collision" });
966
1271
  dst[key] = value;
967
1272
  }
968
1273
  }
@@ -976,24 +1281,22 @@ function getTemplateSeed(stage, meshMode) {
976
1281
  if (meshMode) delete merged.services.tester;
977
1282
  return merged;
978
1283
  }
979
- function ownEnv(build, stage) {
980
- const env = { ...build.app.env };
981
- const reserved = ["EXEC_MODE", "INFRA_MODE", ...getPrimaryEndpoint(build.app.endpoints) ? ["PORT"] : []];
982
- 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" });
983
- return env;
984
- }
985
- function resolveEnv(input, registry, source) {
1284
+ function resolveEnv(input, registry, baseContext) {
986
1285
  const out = {};
987
1286
  for (const [key, value] of Object.entries(input)) {
988
- collectBuilderReferences(value, "build", `${source}.${key}`);
989
- out[key] = interpolateBuilderReferences(value, "build", registry).replace(/\$/g, "$$$$");
1287
+ if (value === null) {
1288
+ out[key] = null;
1289
+ continue;
1290
+ }
1291
+ const context = { ...baseContext, configPath: `${baseContext.configPath}.${key}` };
1292
+ out[key] = interpolateBuilderReferences(value, "build", registry, context).replace(/\$/g, "$$$$");
990
1293
  }
991
1294
  return out;
992
1295
  }
993
- function addPorts(service, endpointPairs) {
1296
+ function addPorts(service, endpointPairs, sourceFile, stage) {
994
1297
  for (const [ep, hostPort] of endpointPairs) {
995
1298
  const ports = Array.isArray(service.ports) ? service.ports : [];
996
- 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" });
1299
+ if (ports.some((p) => p && typeof p === "object" && p.published === hostPort)) throw new ConfigError({ sourceFile, configPath: ep.logicalPath, stage, composition: "service", referencedObject: ep.logicalPath, value: hostPort, reason: "Duplicate host port publication" });
997
1300
  ports.push({ target: ep.networkPort, published: hostPort, host_ip: PUBLIC_HOST, protocol: "tcp" });
998
1301
  service.ports = ports;
999
1302
  }
@@ -1004,28 +1307,29 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1004
1307
  const seed = getTemplateSeed(stage, Boolean(options.meshMode));
1005
1308
  const rawName = options.projectNameOverride ?? raw.name ?? path.basename(root);
1006
1309
  const projectName = deriveProjectName(rawName, stage);
1310
+ const nameAllocator = options.nameAllocator ?? new GeneratedComposeNameAllocator(["app", "tester", "default", options.appServiceName ?? "app"]);
1007
1311
  const namespaced = {};
1008
1312
  for (const [key, dep] of Object.entries(effective.dependencies).sort(([a], [b]) => a.localeCompare(b))) {
1009
1313
  const sourcePath = resolveInsideProject(root, dep.compose, { sourceFile: buildPath, configPath: `dependencies.${key}.compose`, stage });
1010
1314
  const document = rebaseComposePaths(loadComposeDocument(sourcePath, { sourceFile: buildPath, configPath: `dependencies.${key}.compose`, stage, composition: "service" }), sourcePath, options.composeOutputDir ?? root);
1011
1315
  validateDependencyCompose(key, dep, document, { composePath: sourcePath, stage });
1012
1316
  if (Object.keys(dep.endpoints).length) {
1013
- const ns = namespaceDependencyCompose({ namespacePrefix: options.namespacePrefix ? `${options.namespacePrefix}${key}` : `dep--${key}`, document });
1317
+ const ns = namespaceDependencyCompose({ dependencyKey: key, namespacePrefix: options.namespacePrefix ? `${options.namespacePrefix}${key}` : `dep--${key}`, document, allocator: nameAllocator, identityPrefix: JSON.stringify(["service", options.appServiceName ?? "app", "dependency", key]) });
1014
1318
  namespaced[key] = { doc: ns.document, map: ns.serviceNameMap, source: sourcePath };
1015
1319
  }
1016
1320
  }
1017
1321
  const materialized = {};
1018
1322
  const compose = { ...seed, ...options.meshMode ? {} : { name: projectName }, services: { ...seed.services } };
1019
1323
  let app = compose.services.app ?? (compose.services.app = { build: { context: "." } });
1020
- if (profile.integrated) for (const [key, entry] of Object.entries(namespaced)) {
1324
+ if (profile.infraMode === "integrated") for (const [key, entry] of Object.entries(namespaced)) {
1021
1325
  if (options.suppressDependencies?.has(key)) continue;
1022
1326
  const dep = effective.dependencies[key];
1023
1327
  const item = structuredClone(entry.doc);
1024
- mergeDocument(compose, item, `dependency ${key}`);
1328
+ mergeDocument(compose, item, { sourceFile: entry.source, configPath: `dependencies.${key}.compose`, stage, composition: "service" });
1025
1329
  const endpointOwnerMap = /* @__PURE__ */ new Map();
1026
1330
  for (const [epName, ep] of Object.entries(dep.endpoints)) endpointOwnerMap.set(epName, entry.map.get(ep.service));
1027
1331
  const endpointOwners = new Set(endpointOwnerMap.values());
1028
- materialized[key] = { key, composePath: entry.source, compose: item, serviceNameMap: entry.map, endpointOwnerMap, endpoints: {}, endpointOwners };
1332
+ materialized[key] = { key, composePath: entry.source, compose: item, serviceNameMap: entry.map, endpointOwnerMap, endpoints: {}, endpointOwners, serviceNames: new Set(Object.keys(item.services)) };
1029
1333
  }
1030
1334
  const appEndpoints = buildStandaloneAppEndpoints(effective, stage, options.appServiceName ?? "app");
1031
1335
  const depEndpoints = {};
@@ -1049,7 +1353,7 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1049
1353
  for (const [name, e] of Object.entries(dep.endpoints).sort(([a], [b]) => a.localeCompare(b))) if (e.publicPort !== void 0) intents.push({ logicalPath: `dependencies.${key}.endpoints.${name}`, requested: e.publicPort });
1050
1354
  }
1051
1355
  }
1052
- const allocation = allocateHostPorts(root, stage, intents, Boolean(options.validationMode));
1356
+ const allocation = allocateHostPorts(root, stage, intents, Boolean(options.validationMode), { sourceFile: buildPath, composition: "service" });
1053
1357
  for (const [name, ep] of Object.entries(appEndpoints)) if (allocation.has(ep.logicalPath)) {
1054
1358
  ep.publicHost = PUBLIC_HOST;
1055
1359
  ep.publicPort = allocation.get(ep.logicalPath);
@@ -1060,31 +1364,49 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1060
1364
  ep.publicPort = allocation.get(ep.logicalPath);
1061
1365
  ep.effectivelyPublished = true;
1062
1366
  }
1063
- const registry = (ref) => {
1367
+ const registry = (ref, context) => {
1064
1368
  if (ref.target === "app") {
1065
1369
  const ep2 = appEndpoints[ref.endpoint];
1066
- if (!ep2) throw new ConfigError({ sourceFile: buildPath, configPath: ref.raw, stage, composition: "service", referencedObject: ref.raw, reason: "Unknown app endpoint reference" });
1067
- return resolveEndpointProperty(ep2, ref.property, { sourceFile: buildPath, configPath: ref.raw, stage });
1370
+ if (!ep2) throw new ConfigError({ ...context, referencedObject: ref.raw, reason: "Unknown app endpoint reference" });
1371
+ return resolveEndpointProperty(ep2, ref.property, { ...context, referencedObject: ref.raw });
1068
1372
  }
1069
1373
  const ep = depEndpoints[ref.dependency]?.[ref.endpoint];
1070
- if (!ep) throw new ConfigError({ sourceFile: buildPath, configPath: ref.raw, stage, composition: "service", referencedObject: ref.raw, reason: "Unknown dependency endpoint reference" });
1071
- return resolveEndpointProperty(ep, ref.property, { sourceFile: buildPath, configPath: ref.raw, stage });
1374
+ if (!ep) throw new ConfigError({ ...context, referencedObject: ref.raw, reason: "Unknown dependency endpoint reference" });
1375
+ return resolveEndpointProperty(ep, ref.property, { ...context, referencedObject: ref.raw });
1072
1376
  };
1073
1377
  for (const [key, dep] of Object.entries(effective.dependencies)) {
1074
- const depEnv = options.deferReferenceResolution ? dep.env : resolveEnv(dep.env, registry, `dependencies.${key}.env`);
1378
+ const depEnv = options.deferReferenceResolution ? dep.env : resolveEnv(dep.env, registry, { sourceFile: buildPath, configPath: `dependencies.${key}.env`, stage, composition: "service" });
1075
1379
  for (const svc of Object.values(materialized[key]?.compose.services ?? {})) mergeComposeEnvironment(svc, depEnv);
1076
1380
  }
1077
- const appEnv = options.deferReferenceResolution ? ownEnv(effective, stage) : resolveEnv(ownEnv(effective, stage), registry, "app.env");
1078
- let buildAppEnvironment = { ...appEnv };
1079
- const runtimeDotenv = path.join(root, `.env.${profile.runtimeStage}`);
1080
- if (fs.existsSync(runtimeDotenv)) {
1081
- const text = fs.readFileSync(runtimeDotenv, "utf8");
1082
- for (const line of text.split(/\r?\n/)) {
1083
- const match = line.match(/^\s*(?:export\s+)?(EXEC_MODE|INFRA_MODE|PORT)\s*=/);
1084
- 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" });
1381
+ const appEnvironmentLayers = [];
1382
+ for (const layer of effective.layers) {
1383
+ if (Object.keys(layer.appEnv).length) {
1384
+ const configPath = layer.stage === "base" ? "app.env" : `${layer.stage}.app.env`;
1385
+ assertNoBuilderOwnedEnvKeys(layer.appEnv, [EXEC_MODE_KEY, INFRA_MODE_KEY, ...getPrimaryEndpoint(effective.app.endpoints) ? [PORT_KEY] : []], { sourceFile: buildPath, configPath, stage, composition: "service" });
1386
+ appEnvironmentLayers.push({ kind: "build-json", stage: layer.stage, configPath, values: { ...layer.appEnv } });
1387
+ }
1388
+ }
1389
+ const resolveAppLayers = () => {
1390
+ const result = {};
1391
+ const laterKeys = new Set(Object.keys(options.externalAppEnv ?? {}));
1392
+ for (const [key, layer] of selectAppEnvironmentEntries(appEnvironmentLayers, laterKeys)) {
1393
+ if (layer.kind === "build-json") {
1394
+ const context = {
1395
+ sourceFile: buildPath,
1396
+ configPath: layer.configPath,
1397
+ stage,
1398
+ composition: "service"
1399
+ };
1400
+ result[key] = resolveEnv({ [key]: layer.values[key] }, registry, context)[key];
1401
+ } else {
1402
+ result[key] = layer.values[key];
1403
+ }
1085
1404
  }
1086
- }
1087
- const internal = { EXEC_MODE: profile.runtimeStage, INFRA_MODE: profile.integrated ? "integrated" : "isolated", ...getPrimaryEndpoint(effective.app.endpoints) ? { PORT: String(getPrimaryEndpoint(effective.app.endpoints)[1].port) } : {} };
1405
+ return result;
1406
+ };
1407
+ const runtimeDotenv = path.join(root, `.env.${profile.envStage}`);
1408
+ assertDotenvDoesNotDefineKeys(runtimeDotenv, [EXEC_MODE_KEY, INFRA_MODE_KEY, ...getPrimaryEndpoint(effective.app.endpoints) ? [PORT_KEY] : []], { configPath: `.env.${profile.envStage}`, stage, composition: "service" });
1409
+ const internal = { EXEC_MODE: profile.execMode, INFRA_MODE: profile.infraMode, ...getPrimaryEndpoint(effective.app.endpoints) ? { PORT: String(getPrimaryEndpoint(effective.app.endpoints)[1].port) } : {} };
1088
1410
  const appBuild = app.build && typeof app.build === "object" ? app.build : { context: "." };
1089
1411
  const outputDir = options.composeOutputDir ? path.resolve(options.composeOutputDir) : root;
1090
1412
  const serviceContext = path.relative(outputDir, root).replace(/\\/g, "/") || ".";
@@ -1093,14 +1415,14 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1093
1415
  else delete appBuild.dockerfile;
1094
1416
  appBuild.target = profile.appTarget;
1095
1417
  app.build = appBuild;
1096
- app.env_file = [{ path: options.meshMode ? path.posix.join(serviceContext, `.env.${profile.runtimeStage}`) : `.env.${profile.runtimeStage}`, required: false }];
1097
- app.environment = { ...appEnv, ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
1418
+ app.env_file = [{ path: options.meshMode ? path.posix.join(serviceContext, `.env.${profile.envStage}`) : `.env.${profile.envStage}`, required: false }];
1419
+ app.environment = { ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
1098
1420
  if (stage === "dev") app.volumes = [`${options.meshMode && serviceContext !== "." ? `./${serviceContext}` : "."}:/app`, "/app/node_modules"];
1099
- for (const [name, ep] of Object.entries(appEndpoints)) if (!options.meshMode && ep.effectivelyPublished) addPorts(app, [[ep, ep.publicPort]]);
1421
+ for (const [name, ep] of Object.entries(appEndpoints)) if (!options.meshMode && ep.effectivelyPublished) addPorts(app, [[ep, ep.publicPort]], buildPath, stage);
1100
1422
  for (const [key, dependency] of Object.entries(materialized)) {
1101
1423
  for (const [epName, owner] of dependency.endpointOwnerMap.entries()) {
1102
1424
  const endpoint = depEndpoints[key][epName];
1103
- if (!options.meshMode && endpoint.effectivelyPublished) addPorts(compose.services[owner], [[endpoint, endpoint.publicPort]]);
1425
+ if (!options.meshMode && endpoint.effectivelyPublished) addPorts(compose.services[owner], [[endpoint, endpoint.publicPort]], dependency.composePath, stage);
1104
1426
  }
1105
1427
  for (const owner of dependency.endpointOwners) {
1106
1428
  const svc = compose.services[owner];
@@ -1113,34 +1435,47 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1113
1435
  }
1114
1436
  for (const [epName, ep] of Object.entries(depEndpoints[key])) dependency.endpoints[epName] = ep;
1115
1437
  }
1116
- if (effective.overrideCompose) {
1117
- const overridePath = resolveInsideProject(root, effective.overrideCompose, {
1438
+ for (const layer of effective.layers) {
1439
+ if (!layer.overrideCompose) continue;
1440
+ const overridePath = resolveInsideProject(root, layer.overrideCompose, {
1118
1441
  sourceFile: buildPath,
1119
- configPath: "override-compose",
1442
+ configPath: `${layer.stage}.override-compose`,
1120
1443
  stage
1121
1444
  });
1122
1445
  const loadedOverride = loadComposeDocument(overridePath, {
1123
1446
  sourceFile: buildPath,
1124
- configPath: "override-compose",
1447
+ configPath: `${layer.stage}.override-compose`,
1125
1448
  stage,
1126
1449
  composition: "service"
1127
1450
  });
1128
1451
  const overrideDocument = rebaseAppOverridePaths(loadedOverride, root, outputDir);
1129
1452
  const prepared = validateAndPrepareAppOverride(overrideDocument, {
1130
1453
  file: overridePath,
1131
- stage,
1454
+ stage: layer.stage === "base" ? stage : layer.stage,
1132
1455
  expectedBuildContext: String(appBuild.context),
1133
- buildContextBaseDir: outputDir
1456
+ buildContextBaseDir: outputDir,
1457
+ allocator: nameAllocator,
1458
+ resourceNamespace: options.meshMode ? options.appServiceName ?? "app" : "app"
1134
1459
  });
1135
- for (const section of ["volumes", "networks", "configs", "secrets"]) if (prepared.resources[section]) mergeDocument(compose, { services: {}, [section]: prepared.resources[section] }, "app override");
1136
- const rawOverrideEnv = normalizeComposeEnvironment(prepared.app.environment, "override-compose.services.app.environment");
1137
- const overrideEnv = options.deferReferenceResolution ? rawOverrideEnv : resolveEnv(rawOverrideEnv, registry, "override-compose.services.app.environment");
1460
+ for (const section of ["volumes", "networks", "configs", "secrets"]) if (prepared.resources[section]) mergeDocument(compose, { services: {}, [section]: prepared.resources[section] }, { sourceFile: overridePath, configPath: `${layer.stage}.override-compose`, stage, composition: "service" });
1461
+ const rawOverrideEnv = normalizeComposeEnvironment(prepared.app.environment, `${layer.stage}.override-compose.services.app.environment`);
1462
+ const overrideEnv = rawOverrideEnv;
1138
1463
  if (getPrimaryEndpoint(effective.app.endpoints) && "PORT" in overrideEnv) throw new ConfigError({ sourceFile: overridePath, configPath: "services.app.environment.PORT", stage, composition: "service", reason: "Override cannot set Builder-owned PORT" });
1139
- buildAppEnvironment = { ...appEnv, ...overrideEnv };
1140
- const merged = { ...app, ...prepared.app };
1141
- merged.environment = { ...appEnv, ...overrideEnv, ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
1464
+ const overrideStage = layer.stage === "base" ? stage : layer.stage;
1465
+ const stageOrder = { base: 0, dev: 1, prod: 1, test: 1, e2e: 2 };
1466
+ let insertAt = appEnvironmentLayers.findIndex((item) => (stageOrder[item.stage] ?? 0) > (stageOrder[overrideStage] ?? 0));
1467
+ if (insertAt < 0) insertAt = appEnvironmentLayers.length;
1468
+ appEnvironmentLayers.splice(insertAt, 0, { kind: "override-compose", stage: overrideStage, sourceFile: overridePath, configPath: `${layer.stage}.override-compose.services.app.environment`, values: overrideEnv });
1469
+ const preparedApp = { ...prepared.app };
1470
+ delete preparedApp.environment;
1471
+ delete preparedApp.build;
1472
+ const merged = mergeAppOverride(app, preparedApp);
1473
+ merged.environment = { ...app.environment, ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
1142
1474
  const overrideBuild = prepared.app.build && typeof prepared.app.build === "object" ? prepared.app.build : {};
1143
- if (overrideBuild.args !== void 0) appBuild.args = overrideBuild.args;
1475
+ if (overrideBuild.args !== void 0) {
1476
+ const current = appBuild.args, incoming = overrideBuild.args;
1477
+ appBuild.args = current && incoming && typeof current === "object" && typeof incoming === "object" && !Array.isArray(current) && !Array.isArray(incoming) ? { ...current, ...incoming } : incoming;
1478
+ }
1144
1479
  merged.build = appBuild;
1145
1480
  merged.env_file = app.env_file;
1146
1481
  merged.depends_on = app.depends_on;
@@ -1148,19 +1483,27 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1148
1483
  compose.services.app = merged;
1149
1484
  app = merged;
1150
1485
  }
1486
+ if (!options.deferReferenceResolution) {
1487
+ const finalEnv = resolveAppLayers();
1488
+ app.environment = { ...finalEnv, ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
1489
+ }
1151
1490
  if (options.meshMode && options.appServiceName && options.appServiceName !== "app") {
1152
1491
  delete compose.services.app;
1153
1492
  compose.services[options.appServiceName] = app;
1154
1493
  }
1155
- if (profile.integrated) applyDependencyLifecycle(app, materialized, effective);
1494
+ if (profile.infraMode === "integrated") applyDependencyLifecycle(app, materialized, effective);
1156
1495
  if (profile.attachTester && !options.meshMode) {
1496
+ const testerDotenvPath = path.join(root, ".env.e2e-tester"), testerBuilderKeys = [EXEC_MODE_KEY, INFRA_MODE_KEY];
1497
+ assertDotenvDoesNotDefineKeys(testerDotenvPath, testerBuilderKeys, { configPath: ".env.e2e-tester", stage: "e2e", composition: "service" });
1157
1498
  const testerEnvRaw = effective.tester?.env ?? {};
1158
- assertTesterReferencesArePublic(testerEnvRaw, "build", "tester.env");
1159
- const testerEnv = options.deferReferenceResolution ? testerEnvRaw : resolveEnv(testerEnvRaw, registry, "tester.env");
1160
- compose.services.tester = { build: { context: ".", ...raw.dockerfile ? { dockerfile: raw.dockerfile } : {}, target: "test-e2e" }, network_mode: "host", environment: testerEnv, depends_on: { app: { condition: "service_healthy" } } };
1499
+ assertNoBuilderOwnedEnvKeys(testerEnvRaw, testerBuilderKeys, { sourceFile: buildPath, configPath: "tester.env", stage: "e2e", composition: "service" });
1500
+ const testerContext = { sourceFile: buildPath, configPath: "tester.env", stage: "e2e", composition: "service" };
1501
+ assertTesterReferencesArePublic(testerEnvRaw, "build", testerContext);
1502
+ const testerEnv = options.deferReferenceResolution ? testerEnvRaw : resolveEnv(testerEnvRaw, registry, testerContext);
1503
+ compose.services.tester = { build: { context: ".", ...raw.dockerfile ? { dockerfile: raw.dockerfile } : {}, target: profile.testerTarget ?? "test-e2e" }, network_mode: "host", env_file: [{ path: ".env.e2e-tester", required: false }], environment: { ...testerEnv, EXEC_MODE: "e2e" }, depends_on: { app: { condition: "service_healthy" } } };
1161
1504
  }
1162
- const builderAppEnvironment = { ...buildAppEnvironment, ...options.externalAppEnv ?? {} };
1163
- return { compose, effectiveBuild: effective, endpoints: { app: appEndpoints, dependencies: depEndpoints }, projectName, ...profile.attachTester && !options.meshMode ? { testerServiceName: "tester" } : {}, builderAppEnvironment, buildAppEnvironment, externalAppEnvironment: { ...options.externalAppEnv ?? {} }, dependencyEnvironments: Object.fromEntries(Object.entries(effective.dependencies).map(([key, dep]) => [key, dep.env])) };
1505
+ nameAllocator.assertUnique();
1506
+ return { compose, effectiveBuild: effective, endpoints: { app: appEndpoints, dependencies: depEndpoints }, projectName, ...profile.attachTester && !options.meshMode ? { testerServiceName: "tester" } : {}, appEnvironmentLayers, builderInternalEnvironment: { ...internal }, externalAppEnvironment: { ...options.externalAppEnv ?? {} }, dependencyServiceNames: Object.fromEntries(Object.entries(materialized).map(([key, dep]) => [key, [...dep.serviceNames]])), dependencyEnvironments: Object.fromEntries(Object.entries(effective.dependencies).map(([key, dep]) => [key, dep.env])) };
1164
1507
  }
1165
1508
 
1166
1509
  // src/core/checkers/checkEffectiveServiceStages.ts
@@ -1180,7 +1523,7 @@ function checkInfra(projectDir = process.cwd()) {
1180
1523
  checkDockerfileContract(buildJson, absProjectDir);
1181
1524
  checkYamlFiles(buildJson, absProjectDir);
1182
1525
  checkAllEffectiveServiceStages(absProjectDir);
1183
- console.log(pc22.green("\n\u2705 All V2 service infrastructure and contract checks passed.\n"));
1526
+ console.log(pc14.green("\n\u2705 All V2 service infrastructure and contract checks passed.\n"));
1184
1527
  }
1185
1528
  function checkComposeAvailability() {
1186
1529
  const composeCheck = spawnSync(
@@ -1225,7 +1568,7 @@ function checkDependencies() {
1225
1568
  const count = (networkCheck.stdout || "").trim().split("\n").filter(Boolean).length;
1226
1569
  if (count > 25) {
1227
1570
  console.warn(
1228
- pc22.yellow(
1571
+ pc14.yellow(
1229
1572
  `
1230
1573
  \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.
1231
1574
  To resolve, run "builder prune" or "docker network prune -f", or configure default-address-pools in /etc/docker/daemon.json.
@@ -1270,7 +1613,8 @@ var envSchema2 = z.record(z.string(), z.string());
1270
1613
  var meshServiceSchema = z.object({ path: z.string().min(1), env: envSchema2.optional(), dependencies: z.record(identifierSchema2, serviceNameSchema).optional(), dependsOn: z.array(serviceNameSchema).optional(), publish: z.array(z.string()).optional() }).strict();
1271
1614
  var meshServiceStageOverlaySchema = z.object({ path: z.string().min(1).optional(), env: envSchema2.optional(), dependencies: z.record(identifierSchema2, serviceNameSchema).optional(), dependsOn: z.array(serviceNameSchema).optional(), publish: z.array(z.string()).optional() }).strict();
1272
1615
  var meshStageSchema = z.object({ services: z.record(serviceNameSchema, meshServiceStageOverlaySchema).optional() }).strict();
1273
- 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();
1616
+ var rootServicesSchema = z.record(serviceNameSchema, meshServiceSchema).refine((services) => Object.keys(services).length >= 1, { message: "must contain at least one root service" });
1617
+ var meshSchema = z.object({ $schema: z.string().optional(), name: z.string().optional(), tester: z.object({ compose: z.string().min(1), service: z.string().min(1), env: envSchema2.optional() }).strict().optional(), services: rootServicesSchema, dev: meshStageSchema.optional(), prod: meshStageSchema.optional(), test: meshStageSchema.optional(), e2e: meshStageSchema.optional() }).strict();
1274
1618
 
1275
1619
  // src/core/mesh/getMeshJson.ts
1276
1620
  function getMeshJson(projectDir = process.cwd()) {
@@ -1298,14 +1642,15 @@ function getMeshJson(projectDir = process.cwd()) {
1298
1642
 
1299
1643
  // src/core/config/resolveMeshStage.ts
1300
1644
  function resolveMeshStage(mesh, stage, sourceFile) {
1301
- const overlays = mesh[stage]?.services ?? {}, names = /* @__PURE__ */ new Set([...Object.keys(mesh.services), ...Object.keys(overlays)]), services = {};
1302
- for (const name of names) {
1303
- const base = mesh.services[name], patch = overlays[name];
1304
- 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) };
1305
- if (!merged.path) throw new ConfigError({ sourceFile, configPath: `services.${name}.path`, stage, composition: "mesh", reason: "Effective mesh service requires path" });
1306
- services[name] = merged;
1645
+ if (Object.keys(mesh.services).length === 0) throw new ConfigError({ sourceFile, configPath: "services", stage, composition: "mesh", reason: "mesh.json must declare at least one root service" });
1646
+ const services = {};
1647
+ for (const [name, service] of Object.entries(mesh.services)) services[name] = { path: service.path, env: { ...service.env ?? {} }, dependencies: { ...service.dependencies ?? {} }, dependsOn: [...service.dependsOn ?? []], publish: [...service.publish ?? []] };
1648
+ for (const overlayStage of stageOverlayChain(stage)) for (const [name, patch] of Object.entries(mesh[overlayStage]?.services ?? {})) {
1649
+ const prior = services[name] ?? { path: void 0, env: {}, dependencies: {}, dependsOn: [], publish: [] };
1650
+ services[name] = { path: patch.path ?? prior.path, env: mergeStringMap(prior.env, patch.env), dependencies: { ...prior.dependencies, ...patch.dependencies ?? {} }, dependsOn: unionStable(prior.dependsOn, patch.dependsOn), publish: unionStable(prior.publish, patch.publish) };
1307
1651
  }
1308
1652
  if (!Object.keys(services).length) throw new ConfigError({ sourceFile, configPath: "services", stage, composition: "mesh", reason: "At least one effective mesh service is required" });
1653
+ for (const [name, service] of Object.entries(services)) if (!service.path) throw new ConfigError({ sourceFile, configPath: `services.${name}.path`, stage, composition: "mesh", reason: "Effective mesh service requires path" });
1309
1654
  const graph = /* @__PURE__ */ new Map();
1310
1655
  for (const [name, service] of Object.entries(services)) {
1311
1656
  if (!BUILDER_IDENTIFIER_PATTERN.test(name) || RESERVED_MESH_SERVICE_NAMES.has(name)) throw new ConfigError({ sourceFile, configPath: `services.${name}`, stage, composition: "mesh", value: name, reason: "Invalid or reserved mesh service name" });
@@ -1383,40 +1728,56 @@ function resolveMeshPublication(services, bindings, stage, meshJsonPath) {
1383
1728
  }
1384
1729
 
1385
1730
  // src/core/mesh/v2/meshReferences.ts
1386
- function resolveMesh(ref, ctx, source) {
1731
+ function resolveMesh(ref, ctx, context) {
1387
1732
  const name = ref.meshService;
1388
- 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}"` });
1733
+ if (!ctx.services[name]) throw new ConfigError({ ...context, referencedObject: ref.raw, reason: `Unknown mesh service reference "${name}"` });
1389
1734
  const provider = ref.target === "dependency" ? ctx.bindings.get(bindingKey(name, ref.dependency)) : void 0;
1390
- 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];
1391
- if (!ep) throw new ConfigError({ sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage, composition: "mesh", referencedObject: ref.raw, reason: "Referenced endpoint does not exist" });
1392
- return resolveEndpointProperty(ep, ref.property, { sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage });
1735
+ const endpoint = ref.target === "app" ? ctx.endpoints.app[name]?.[ref.endpoint] : provider ? ctx.endpoints.app[provider]?.[ref.endpoint] : ctx.endpoints.dependencies[name]?.[ref.dependency]?.[ref.endpoint];
1736
+ if (!endpoint) throw new ConfigError({ ...context, referencedObject: ref.raw, reason: "Referenced endpoint does not exist" });
1737
+ return resolveEndpointProperty(endpoint, ref.property, { ...context, referencedObject: ref.raw });
1393
1738
  }
1394
- function resolveBuild(ref, consumer, ctx, source) {
1739
+ function resolveBuild(ref, consumer, ctx, context) {
1395
1740
  const provider = ref.target === "dependency" ? ctx.bindings.get(bindingKey(consumer, ref.dependency)) : void 0;
1396
- 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];
1397
- 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" });
1741
+ const endpoint = ref.target === "app" ? ctx.endpoints.app[consumer]?.[ref.endpoint] : provider ? ctx.endpoints.app[provider]?.[ref.endpoint] : ctx.endpoints.dependencies[consumer]?.[ref.dependency]?.[ref.endpoint];
1742
+ if (!endpoint) {
1743
+ const reason = provider ? `Provider "${provider}" does not expose endpoint "${ref.endpoint}"` : "Referenced endpoint does not exist";
1744
+ throw new ConfigError({ ...context, referencedObject: ref.raw, reason });
1745
+ }
1398
1746
  try {
1399
- return resolveEndpointProperty(ep, ref.property, { sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage });
1747
+ return resolveEndpointProperty(endpoint, ref.property, { ...context, referencedObject: ref.raw });
1400
1748
  } catch (error) {
1401
- 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 });
1749
+ if (provider && error instanceof ConfigError) {
1750
+ throw new ConfigError({
1751
+ ...context,
1752
+ referencedObject: `${consumer}.dependencies.${ref.dependency}.endpoints.${ref.endpoint}.${ref.property} -> ${provider}.app.endpoints.${ref.endpoint}.${ref.property}`,
1753
+ reason: error.message
1754
+ });
1755
+ }
1402
1756
  throw error;
1403
1757
  }
1404
1758
  }
1405
- function interpolate(value, scope, resolve, source) {
1406
- const sentinel = "\0DOLLAR\0";
1407
- return value.replace(/\$\$/g, sentinel).replace(/\$\{([^}]*)\}/g, (_whole, body) => {
1408
- const ref = collectBuilderReferences(`\${${body}}`, scope, source)[0];
1409
- return resolve(ref);
1410
- }).replaceAll(sentinel, "$").replace(/\$/g, "$$$$");
1759
+ function interpolate(value, scope, ctx, configPath, consumer) {
1760
+ const context = {
1761
+ sourceFile: scope === "mesh" ? ctx.meshJsonPath : ctx.services[consumer]?.buildJsonPath ?? ctx.meshJsonPath,
1762
+ configPath,
1763
+ stage: ctx.stage,
1764
+ composition: scope === "mesh" ? "mesh" : "service"
1765
+ };
1766
+ return interpolateBuilderReferences(value, scope, (ref, refContext) => scope === "mesh" ? resolveMesh(ref, ctx, refContext) : resolveBuild(ref, consumer, ctx, refContext), context).replace(/\$/g, "$$$$");
1411
1767
  }
1412
1768
  function resolveMeshEnvMap(env, ctx, sourcePrefix) {
1413
- return Object.fromEntries(Object.entries(env).map(([key, value]) => [key, interpolate(value, "mesh", (ref) => resolveMesh(ref, ctx, `${sourcePrefix}.${key}`), `${sourcePrefix}.${key}`)]));
1769
+ return Object.fromEntries(Object.entries(env).map(([key, value]) => [key, interpolate(value, "mesh", ctx, `${sourcePrefix}.${key}`)]));
1414
1770
  }
1415
1771
  function resolveServiceBuildEnvThroughMesh(consumer, env, ctx, sourcePrefix) {
1416
- return Object.fromEntries(Object.entries(env).map(([key, value]) => [key, interpolate(value, "build", (ref) => resolveBuild(ref, consumer, ctx, `${sourcePrefix}.${key}`), `${sourcePrefix}.${key}`)]));
1417
- }
1418
- function assertMeshTesterEnvPublic(env, source) {
1419
- assertTesterReferencesArePublic(env, "mesh", source);
1772
+ return Object.fromEntries(Object.entries(env).map(([key, value]) => [key, interpolate(value, "build", ctx, `${sourcePrefix}.${key}`, consumer)]));
1773
+ }
1774
+ function assertMeshTesterEnvPublic(env, ctx, configPath = "tester.env") {
1775
+ assertTesterReferencesArePublic(env, "mesh", {
1776
+ sourceFile: ctx.meshJsonPath,
1777
+ configPath,
1778
+ stage: ctx.stage,
1779
+ composition: "mesh"
1780
+ });
1420
1781
  }
1421
1782
 
1422
1783
  // src/core/mesh/v2/lifecycle.ts
@@ -1446,95 +1807,147 @@ function applyMeshLifecycleEdges(services, edges) {
1446
1807
  }
1447
1808
  }
1448
1809
 
1449
- // src/core/mesh/v2/compileMeshTester.ts
1450
- function refs(svc) {
1451
- const out = [];
1452
- const add = (v) => {
1453
- if (typeof v === "string") out.push(v);
1454
- };
1455
- if (Array.isArray(svc.depends_on)) svc.depends_on.forEach(add);
1456
- else if (svc.depends_on && typeof svc.depends_on === "object") Object.keys(svc.depends_on).forEach(add);
1457
- if (Array.isArray(svc.links)) svc.links.forEach((v) => add(typeof v === "string" ? v.split(":")[0] : v));
1458
- if (Array.isArray(svc.volumes_from)) svc.volumes_from.forEach((v) => add(typeof v === "string" ? v.split(":")[0] : v));
1459
- if (typeof svc.network_mode === "string" && svc.network_mode.startsWith("service:")) out.push(svc.network_mode.slice(8));
1460
- return out;
1810
+ // src/core/composition/composeDependsOn.ts
1811
+ function normalizeComposeDependsOn(value) {
1812
+ if (Array.isArray(value)) {
1813
+ return Object.fromEntries(value.filter((item) => typeof item === "string").map((name) => [name, {}]));
1814
+ }
1815
+ return value && typeof value === "object" ? { ...value } : {};
1461
1816
  }
1462
- function referencedResources(svc, doc) {
1463
- const sets = { volumes: /* @__PURE__ */ new Set(), networks: /* @__PURE__ */ new Set(), configs: /* @__PURE__ */ new Set(), secrets: /* @__PURE__ */ new Set() };
1464
- for (const v of Array.isArray(svc.volumes) ? svc.volumes : []) {
1465
- if (typeof v === "string") {
1466
- const source = v.split(":")[0];
1467
- if (doc.volumes?.[source]) sets.volumes.add(source);
1468
- } else if (v && typeof v === "object" && v.type === "volume" && doc.volumes?.[v.source]) sets.volumes.add(v.source);
1469
- }
1470
- const nets = svc.networks;
1471
- if (Array.isArray(nets)) nets.forEach((n) => {
1472
- if (typeof n === "string" && doc.networks?.[n]) sets.networks.add(n);
1473
- });
1474
- else if (nets && typeof nets === "object") Object.keys(nets).forEach((n) => {
1475
- if (doc.networks?.[n]) sets.networks.add(n);
1476
- });
1477
- for (const kind of ["configs", "secrets"]) {
1478
- const v = svc[kind];
1479
- if (Array.isArray(v)) for (const x of v) {
1480
- const n = typeof x === "string" ? x : x?.source;
1481
- if (typeof n === "string" && doc[kind]?.[n]) sets[kind].add(n);
1817
+
1818
+ // src/core/mesh/v2/compileMeshTester.ts
1819
+ function appendEnvFile(existing, next) {
1820
+ if (existing === void 0) return [next];
1821
+ return Array.isArray(existing) ? [...existing, next] : [existing, next];
1822
+ }
1823
+ function envFilePaths(value) {
1824
+ const entries2 = Array.isArray(value) ? value : [value];
1825
+ return entries2.flatMap((entry) => typeof entry === "string" ? [entry] : entry && typeof entry === "object" && typeof entry.path === "string" ? [entry.path] : []);
1826
+ }
1827
+ function validateServiceReferences(document, sourceFile, stage) {
1828
+ for (const [name, service] of Object.entries(document.services)) {
1829
+ const refs = [];
1830
+ const add = (value) => {
1831
+ if (typeof value === "string" && value) refs.push(value);
1832
+ };
1833
+ if (Array.isArray(service.depends_on)) service.depends_on.forEach(add);
1834
+ else if (service.depends_on && typeof service.depends_on === "object") Object.keys(service.depends_on).forEach(add);
1835
+ if (Array.isArray(service.links)) service.links.forEach((value) => add(typeof value === "string" ? value.split(":")[0] : void 0));
1836
+ if (Array.isArray(service.volumes_from)) service.volumes_from.forEach((value) => add(typeof value === "string" ? value.split(":")[0] : void 0));
1837
+ for (const key of ["network_mode", "ipc", "pid"]) {
1838
+ const value = service[key];
1839
+ if (typeof value === "string" && value.startsWith("service:")) add(value.slice("service:".length));
1482
1840
  }
1841
+ for (const ref of refs) if (!document.services[ref]) throw new ConfigError({ sourceFile, configPath: `services.${name}`, stage, composition: "mesh", referencedObject: ref, reason: "Tester Compose service reference does not exist" });
1842
+ }
1843
+ }
1844
+ function applyTesterBuildTarget(service) {
1845
+ if (service.build === void 0) return;
1846
+ if (typeof service.build === "string") {
1847
+ service.build = { context: service.build, target: "test-e2e" };
1848
+ return;
1483
1849
  }
1484
- return sets;
1850
+ if (service.build && typeof service.build === "object" && !Array.isArray(service.build)) service.build = { ...service.build, target: "test-e2e" };
1485
1851
  }
1486
- function compileMeshTester(meshDir, tester, endpointRegistry, effectiveTopLevelApps, stage, referenceContext) {
1487
- 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);
1852
+ function compileMeshTester(meshDir, tester, endpointRegistry, effectiveTopLevelApps, stage, referenceContext, nameAllocator = new GeneratedComposeNameAllocator(effectiveTopLevelApps)) {
1853
+ const meshPath = path.join(meshDir, "mesh.json"), file = resolveInsideProject(meshDir, tester.compose, { sourceFile: meshPath, configPath: "tester.compose", stage }), raw = rebaseComposePaths(loadComposeDocument(file, { sourceFile: meshPath, configPath: "tester.compose", stage, composition: "mesh" }), file, meshDir);
1488
1854
  if (!raw.services || !raw.services[tester.service]) throw new ConfigError({ sourceFile: meshPath, configPath: "tester.service", stage, composition: "mesh", value: tester.service, reason: "Selected tester service does not exist in tester Compose" });
1489
- const included = /* @__PURE__ */ new Set(), visit = (name) => {
1490
- if (included.has(name)) return;
1491
- if (!raw.services[name]) throw new ConfigError({ sourceFile: file, configPath: `services.${name}`, stage, composition: "mesh", reason: "Tester service dependency does not exist" });
1492
- included.add(name);
1493
- for (const ref of refs(raw.services[name])) visit(ref);
1494
- };
1495
- visit(tester.service);
1496
- for (const name of included) {
1497
- const svc = raw.services[name];
1498
- 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" });
1499
- 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" });
1500
- 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" });
1501
- }
1502
- const res = { volumes: /* @__PURE__ */ new Set(), networks: /* @__PURE__ */ new Set(), configs: /* @__PURE__ */ new Set(), secrets: /* @__PURE__ */ new Set() };
1503
- for (const name of included) {
1504
- const own = referencedResources(raw.services[name], raw);
1505
- for (const k of Object.keys(res)) for (const v of own[k]) res[k].add(v);
1506
- }
1507
- const selected = { services: Object.fromEntries([...included].map((k) => [k, raw.services[k]])) };
1508
- for (const k of Object.keys(res)) if (res[k].size) selected[k] = Object.fromEntries([...res[k]].map((n) => [n, raw[k]?.[n]]));
1509
- const ns = namespaceDependencyCompose({ namespacePrefix: "mesh-tester", document: selected });
1855
+ validateComposeResourceReferences(raw, { sourceFile: file, stage, composition: "mesh" });
1856
+ validateServiceReferences(raw, file, stage);
1857
+ assertComposeLifecycleAcyclic(raw.services, {
1858
+ sourceFile: file,
1859
+ stage,
1860
+ composition: "mesh"
1861
+ });
1862
+ for (const [serviceName, service] of Object.entries(raw.services)) {
1863
+ if (service.extends !== void 0) throw new ConfigError({ sourceFile: file, configPath: `services.${serviceName}.extends`, stage, composition: "mesh", reason: "Tester Compose extends is unsupported until effective Compose inheritance can be validated safely" });
1864
+ assertNoServiceBuildContexts(service, `services.${serviceName}`, file);
1865
+ }
1866
+ const selectedRaw = raw.services[tester.service];
1867
+ if (selectedRaw.network_mode !== void 0 && selectedRaw.network_mode !== "host") throw new ConfigError({ sourceFile: file, configPath: `services.${tester.service}.network_mode`, stage, composition: "mesh", reason: "Selected tester runner must be compatible with host networking" });
1868
+ if (selectedRaw.networks !== void 0) throw new ConfigError({ sourceFile: file, configPath: `services.${tester.service}.networks`, stage, composition: "mesh", reason: "Selected host-network tester runner cannot declare Compose networks" });
1869
+ if (selectedRaw.ports !== void 0) throw new ConfigError({ sourceFile: file, configPath: `services.${tester.service}.ports`, stage, composition: "mesh", reason: "Selected host-network tester runner cannot define ports" });
1870
+ const meshCtx = referenceContext ?? { services: {}, bindings: /* @__PURE__ */ new Map(), endpoints: endpointRegistry, stage, meshJsonPath: meshPath };
1871
+ const testerBuilderKeys = [EXEC_MODE_KEY, INFRA_MODE_KEY], rawRunnerEnvironment = normalizeComposeEnvironment(selectedRaw.environment, "tester runner environment");
1872
+ assertNoBuilderOwnedEnvKeys(rawRunnerEnvironment, testerBuilderKeys, { sourceFile: file, configPath: `services.${tester.service}.environment`, stage, composition: "mesh" });
1873
+ for (const envFile of envFilePaths(selectedRaw.env_file)) assertDotenvDoesNotDefineKeys(path.resolve(meshDir, envFile), testerBuilderKeys, { configPath: `services.${tester.service}.env_file`, stage, composition: "mesh" });
1874
+ const meshTesterDotenv = path.join(meshDir, ".env.e2e-tester");
1875
+ assertDotenvDoesNotDefineKeys(meshTesterDotenv, testerBuilderKeys, { configPath: ".env.e2e-tester", stage, composition: "mesh" });
1876
+ const testerEnv = tester.env ?? {};
1877
+ assertNoBuilderOwnedEnvKeys(testerEnv, testerBuilderKeys, { sourceFile: meshPath, configPath: "tester.env", stage, composition: "mesh" });
1878
+ assertMeshTesterEnvPublic(testerEnv, meshCtx);
1879
+ const ns = namespaceDependencyCompose({ dependencyKey: "mesh-tester", namespacePrefix: "mesh-tester", document: raw, allocator: nameAllocator, identityPrefix: JSON.stringify(["mesh-tester"]) });
1510
1880
  const runner = ns.serviceNameMap.get(tester.service);
1511
1881
  const runnerSvc = ns.document.services[runner];
1512
- 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" });
1882
+ applyTesterBuildTarget(runnerSvc);
1513
1883
  runnerSvc.network_mode = "host";
1514
1884
  delete runnerSvc.networks;
1515
- const meshCtx = referenceContext ?? { services: {}, bindings: /* @__PURE__ */ new Map(), endpoints: endpointRegistry, stage, meshJsonPath: meshPath };
1516
- const env = tester.env ?? {};
1517
- assertMeshTesterEnvPublic(env, "tester.env");
1518
- runnerSvc.environment = { ...normalizeComposeEnvironment(runnerSvc.environment, "tester runner environment"), ...resolveMeshEnvMap(env, meshCtx, "tester.env") };
1519
- const depends = runnerSvc.depends_on && typeof runnerSvc.depends_on === "object" && !Array.isArray(runnerSvc.depends_on) ? runnerSvc.depends_on : {};
1885
+ runnerSvc.env_file = appendEnvFile(runnerSvc.env_file, { path: ".env.e2e-tester", required: false });
1886
+ runnerSvc.environment = { ...normalizeComposeEnvironment(runnerSvc.environment, "tester runner environment"), ...resolveMeshEnvMap(testerEnv, meshCtx, "tester.env"), EXEC_MODE: "e2e" };
1887
+ const depends = normalizeComposeDependsOn(runnerSvc.depends_on);
1520
1888
  for (const app of effectiveTopLevelApps) depends[app] = { condition: "service_healthy" };
1521
1889
  runnerSvc.depends_on = depends;
1522
1890
  return { services: ns.document.services, ...ns.document.volumes ? { volumes: ns.document.volumes } : {}, ...ns.document.networks ? { networks: ns.document.networks } : {}, ...ns.document.configs ? { configs: ns.document.configs } : {}, ...ns.document.secrets ? { secrets: ns.document.secrets } : {}, runnerServiceName: runner };
1523
1891
  }
1892
+
1893
+ // src/core/mesh/v2/resolveMeshAppEnvironment.ts
1894
+ function resolveMeshAppEnvironmentLayers(serviceName, layers, context, laterKeys = /* @__PURE__ */ new Set()) {
1895
+ const result = {};
1896
+ for (const [key, layer] of selectAppEnvironmentEntries(layers, laterKeys)) {
1897
+ if (layer.kind === "build-json") {
1898
+ result[key] = resolveServiceBuildEnvThroughMesh(
1899
+ serviceName,
1900
+ { [key]: layer.values[key] },
1901
+ context,
1902
+ `services.${serviceName}.${layer.configPath}`
1903
+ )[key];
1904
+ } else {
1905
+ result[key] = layer.values[key];
1906
+ }
1907
+ }
1908
+ return result;
1909
+ }
1910
+ function validPort(value) {
1911
+ if (!/^\d+$/.test(value)) return void 0;
1912
+ const port = Number(value);
1913
+ return Number.isInteger(port) && port >= 1 && port <= 65535 ? port : void 0;
1914
+ }
1915
+ function parsePublishedHostPort(value) {
1916
+ if (value && typeof value === "object") {
1917
+ const published = value.published;
1918
+ if (typeof published === "number" && Number.isInteger(published)) {
1919
+ return published >= 1 && published <= 65535 ? published : void 0;
1920
+ }
1921
+ if (typeof published === "string") return validPort(published);
1922
+ return void 0;
1923
+ }
1924
+ if (typeof value !== "string") return void 0;
1925
+ const mapping = value.replace(/\/(?:tcp|udp|sctp)$/i, "");
1926
+ if (/^\d+(?:-\d+)?$/.test(mapping)) return void 0;
1927
+ if (mapping.startsWith("[")) {
1928
+ const close = mapping.indexOf("]");
1929
+ if (close < 0 || isIP(mapping.slice(1, close)) !== 6) return void 0;
1930
+ const suffix = mapping.slice(close + 1);
1931
+ const match = suffix.match(/^:(\d+)(?:-\d+)?:\d+(?:-\d+)?$/);
1932
+ return match ? validPort(match[1]) : void 0;
1933
+ }
1934
+ const parts = mapping.split(":");
1935
+ if (parts.length === 2) return validPort(parts[0]);
1936
+ if (parts.length >= 3) {
1937
+ const hostIp = parts.slice(0, -2).join(":");
1938
+ if (isIP(hostIp) === 4) return validPort(parts[parts.length - 2]);
1939
+ }
1940
+ return void 0;
1941
+ }
1942
+
1943
+ // src/utils/assertUniqueHostPortMappings.ts
1524
1944
  function assertUniqueHostPortMappings(yamlConfig) {
1525
1945
  const parsed = parse(yamlConfig);
1526
1946
  const owners = /* @__PURE__ */ new Map();
1527
1947
  for (const [serviceName, service] of Object.entries(parsed?.services ?? {})) {
1528
1948
  for (const port of service?.ports ?? []) {
1529
- let hostPort = null;
1530
- if (typeof port === "string") {
1531
- const parts = port.split(":");
1532
- if (parts.length === 2) hostPort = Number(parts[0]);
1533
- if (parts.length === 3) hostPort = Number(parts[1]);
1534
- } else if (port && typeof port === "object" && "published" in port) {
1535
- hostPort = Number(port.published);
1536
- }
1537
- if (!hostPort || !Number.isInteger(hostPort)) continue;
1949
+ const hostPort = parsePublishedHostPort(port);
1950
+ if (hostPort === void 0) continue;
1538
1951
  const existing = owners.get(hostPort);
1539
1952
  if (existing) {
1540
1953
  throw new ScriptError(
@@ -1563,6 +1976,26 @@ function appendPort(service, target, published) {
1563
1976
  ports.push({ target, published, host_ip: PUBLIC_HOST, protocol: "tcp" });
1564
1977
  service.ports = ports;
1565
1978
  }
1979
+ function buildMeshPortIntents(services, publication) {
1980
+ const intents = [];
1981
+ for (const name of Object.keys(services).sort((a, b) => a.localeCompare(b))) {
1982
+ const service = services[name];
1983
+ const appPublications = publication.filter((pub) => pub.ownerMeshService === name && pub.target === "app").sort((a, b) => a.endpoint.localeCompare(b.endpoint));
1984
+ for (const pub of appPublications) {
1985
+ const endpoint = service.effectiveBuild.app.endpoints[pub.endpoint];
1986
+ intents.push({ logicalPath: pub.logicalPath, requested: endpoint.publicPort });
1987
+ }
1988
+ const dependencyNames = [...new Set(publication.filter((pub) => pub.ownerMeshService === name && pub.target === "dependency").map((pub) => pub.dependency))].sort((a, b) => a.localeCompare(b));
1989
+ for (const dependency of dependencyNames) {
1990
+ const dependencyPublications = publication.filter((pub) => pub.ownerMeshService === name && pub.target === "dependency" && pub.dependency === dependency).sort((a, b) => a.endpoint.localeCompare(b.endpoint));
1991
+ for (const pub of dependencyPublications) {
1992
+ const endpoint = service.effectiveBuild.dependencies[dependency].endpoints[pub.endpoint];
1993
+ intents.push({ logicalPath: pub.logicalPath, requested: endpoint.publicPort });
1994
+ }
1995
+ }
1996
+ }
1997
+ return intents;
1998
+ }
1566
1999
  function ownerFor(pub, fragment) {
1567
2000
  return pub.target === "app" ? pub.ownerMeshService : fragment.endpoints.dependencies[pub.dependency]?.[pub.endpoint]?.networkHost ?? "";
1568
2001
  }
@@ -1570,15 +2003,20 @@ function setEnv(service, env) {
1570
2003
  const current = service.environment && typeof service.environment === "object" && !Array.isArray(service.environment) ? service.environment : {};
1571
2004
  service.environment = { ...current, ...env };
1572
2005
  }
2006
+ function attachNetworkIfCompatible(service, networkName) {
2007
+ if (service.network_mode !== void 0) return;
2008
+ service.networks = { ...normalizeNetworks(service.networks), [networkName]: null };
2009
+ }
1573
2010
  function compileMeshComposition(stage, meshDir, options = {}) {
1574
2011
  const meshPath = path.join(meshDir, "mesh.json"), raw = getMeshJson(meshDir), effective = resolveMeshStage(raw, stage, meshPath), services = loadEffectiveMeshServices(meshDir, effective, stage), bindings = buildDependencyBindings(services, stage, meshPath), bindingMap = bindingsMap(bindings);
1575
2012
  const rawName = raw.name ?? path.basename(meshDir), projectName = deriveProjectName(rawName, stage, meshDir);
2013
+ const nameAllocator = new GeneratedComposeNameAllocator(["mesh", "default", ...Object.keys(services), ...Object.keys(services).map((name) => `mesh--${name}`)]);
1576
2014
  const fragments = {};
1577
2015
  const compose = { name: projectName, services: {}, networks: { mesh: { driver: "bridge" } } };
1578
2016
  for (const [name, svc] of Object.entries(services).sort(([a], [b]) => a.localeCompare(b))) {
1579
2017
  for (const key of ["EXEC_MODE", "INFRA_MODE", ...Object.keys(svc.effectiveBuild.app.endpoints).some((ep) => svc.effectiveBuild.app.endpoints[ep]?.primary) ? ["PORT"] : []]) if (key in svc.meshEnv) throw new ConfigError({ sourceFile: meshPath, configPath: `services.${name}.env.${key}`, stage, composition: "mesh", reason: "Mesh service env cannot set Builder-owned environment" });
1580
2018
  const suppress = new Set(Object.keys(svc.dependencyBindings));
1581
- const fragment = compileServiceComposition(stage, svc.absolutePath, { full: true, meshMode: true, projectNameOverride: projectName, namespacePrefix: `svc--${name}--dep--`, suppressDependencies: suppress, externalAppEnv: svc.meshEnv, deferReferenceResolution: true, appServiceName: name, composeOutputDir: meshDir, validationMode: options.validationMode });
2019
+ const fragment = compileServiceComposition(stage, svc.absolutePath, { nameAllocator, full: true, meshMode: true, projectNameOverride: projectName, namespacePrefix: `svc--${name}--dep--`, suppressDependencies: suppress, externalAppEnv: svc.meshEnv, deferReferenceResolution: true, appServiceName: name, composeOutputDir: meshDir, validationMode: options.validationMode });
1582
2020
  fragments[name] = fragment;
1583
2021
  mergeFragment(compose, fragment.compose, name);
1584
2022
  const app = compose.services[name];
@@ -1593,31 +2031,19 @@ function compileMeshComposition(stage, meshDir, options = {}) {
1593
2031
  const owner = ep.networkHost;
1594
2032
  const ownerService = compose.services[owner];
1595
2033
  if (ownerService) {
1596
- const old = normalizeNetworks(ownerService.networks);
1597
- old[privateName] = null;
1598
- ownerService.networks = old;
2034
+ attachNetworkIfCompatible(ownerService, privateName);
2035
+ attachNetworkIfCompatible(ownerService, "mesh");
1599
2036
  }
1600
2037
  }
1601
- for (const generated of Object.keys(fragment.compose.services).filter((k) => k.startsWith(`svc--${name}--dep--${dep}--`))) {
2038
+ for (const generated of fragment.dependencyServiceNames?.[dep] ?? []) {
1602
2039
  const ownerService = compose.services[generated];
1603
- const old = normalizeNetworks(ownerService.networks);
1604
- old[privateName] = null;
1605
- ownerService.networks = old;
2040
+ attachNetworkIfCompatible(ownerService, privateName);
1606
2041
  }
1607
2042
  }
1608
2043
  }
1609
2044
  app.networks = { ...normalizeNetworks(app.networks), ...networks };
1610
2045
  }
1611
- const publication = resolveMeshPublication(services, bindingMap, stage, meshPath), intents = [];
1612
- for (const name of Object.keys(services).sort()) for (const pub of publication.filter((p) => p.ownerMeshService === name && p.target === "app").sort((a, b) => a.endpoint.localeCompare(b.endpoint))) {
1613
- const ep = services[name].effectiveBuild.app.endpoints[pub.endpoint];
1614
- intents.push({ logicalPath: pub.logicalPath, requested: ep.publicPort });
1615
- }
1616
- for (const name of Object.keys(services).sort()) for (const pub of publication.filter((p) => p.ownerMeshService === name && p.target === "dependency").sort((a, b) => `${a.dependency}.${a.endpoint}`.localeCompare(`${b.dependency}.${b.endpoint}`))) {
1617
- const ep = services[name].effectiveBuild.dependencies[pub.dependency].endpoints[pub.endpoint];
1618
- intents.push({ logicalPath: pub.logicalPath, requested: ep.publicPort });
1619
- }
1620
- const ports = allocateHostPorts(meshDir, stage, intents, Boolean(options.validationMode));
2046
+ const publication = resolveMeshPublication(services, bindingMap, stage, meshPath), intents = buildMeshPortIntents(services, publication), ports = allocateHostPorts(meshDir, stage, intents, Boolean(options.validationMode), { sourceFile: meshPath, composition: "mesh" });
1621
2047
  const endpoints = { app: {}, dependencies: {} };
1622
2048
  for (const [name, svc] of Object.entries(services)) {
1623
2049
  endpoints.app[name] = {};
@@ -1654,15 +2080,17 @@ function compileMeshComposition(stage, meshDir, options = {}) {
1654
2080
  const refContext = { services, bindings: bindingMap, endpoints, stage, meshJsonPath: meshPath };
1655
2081
  for (const [name, fragment] of Object.entries(fragments)) {
1656
2082
  const app = compose.services[name];
1657
- const buildEnv = resolveServiceBuildEnvThroughMesh(name, fragment.buildAppEnvironment ?? fragment.builderAppEnvironment ?? {}, refContext, `services.${name}.app.env`);
1658
2083
  const meshEnv = resolveMeshEnvMap(fragment.externalAppEnvironment ?? {}, refContext, `services.${name}.env`);
1659
- setEnv(app, { ...buildEnv, ...meshEnv });
2084
+ const serviceEnv = resolveMeshAppEnvironmentLayers(name, fragment.appEnvironmentLayers, refContext, new Set(Object.keys(meshEnv)));
2085
+ app.environment = { ...serviceEnv, ...meshEnv, ...fragment.builderInternalEnvironment ?? {} };
1660
2086
  for (const [depName, depEnv] of Object.entries(fragment.dependencyEnvironments ?? {})) {
1661
2087
  const logicalBinding = bindingMap.get(bindingKey(name, depName));
1662
2088
  if (logicalBinding) continue;
1663
2089
  const resolvedDep = resolveServiceBuildEnvThroughMesh(name, depEnv, refContext, `services.${name}.dependencies.${depName}.env`);
1664
- const prefix = `svc--${name}--dep--${depName}--`;
1665
- for (const [serviceName, service] of Object.entries(compose.services)) if (serviceName.startsWith(prefix)) setEnv(service, resolvedDep);
2090
+ for (const serviceName of fragment.dependencyServiceNames?.[depName] ?? []) {
2091
+ const service = compose.services[serviceName];
2092
+ if (service) setEnv(service, resolvedDep);
2093
+ }
1666
2094
  }
1667
2095
  }
1668
2096
  const edges = buildMeshLifecycleEdges(services, bindingMap, stage, meshPath);
@@ -1697,40 +2125,115 @@ function compileMeshComposition(stage, meshDir, options = {}) {
1697
2125
  let testerServiceName;
1698
2126
  if (stage === "e2e") {
1699
2127
  if (!raw.tester && !options.allowMissingTester) throw new ConfigError({ sourceFile: meshPath, configPath: "tester", stage, composition: "mesh", reason: "Global mesh E2E requires root mesh.json.tester { compose, service, env? }" });
1700
- const built = raw.tester ? compileMeshTester(meshDir, raw.tester, endpoints, Object.keys(services).sort(), "e2e", refContext) : void 0;
2128
+ const built = raw.tester ? compileMeshTester(meshDir, raw.tester, endpoints, Object.keys(services).sort(), "e2e", refContext, nameAllocator) : void 0;
1701
2129
  if (built) {
1702
2130
  const fragment = { services: built.services, ...built.volumes ? { volumes: built.volumes } : {}, ...built.networks ? { networks: built.networks } : {}, ...built.configs ? { configs: built.configs } : {}, ...built.secrets ? { secrets: built.secrets } : {} };
1703
2131
  mergeFragment(compose, fragment, "mesh tester");
1704
2132
  testerServiceName = built.runnerServiceName;
1705
2133
  }
1706
2134
  }
2135
+ nameAllocator.assertUnique();
1707
2136
  const yaml = stringify(compose);
1708
2137
  assertUniqueHostPortMappings(yaml);
1709
2138
  return { compose, effectiveMesh: effective, loadedServices: services, endpoints, projectName, ...testerServiceName ? { testerServiceName } : {} };
1710
2139
  }
1711
2140
 
2141
+ // src/core/mesh/v2/validateMeshTestStage.ts
2142
+ function validateMeshTestStage(services, meshDir, meshPath, validationMode = false) {
2143
+ const bindings = bindingsMap(buildDependencyBindings(services, "test", meshPath));
2144
+ const publication = resolveMeshPublication(
2145
+ services,
2146
+ bindings,
2147
+ "test",
2148
+ meshPath
2149
+ );
2150
+ for (const pub of publication) {
2151
+ if (pub.target === "dependency") {
2152
+ throw new ConfigError({
2153
+ sourceFile: meshPath,
2154
+ configPath: `services.${pub.ownerMeshService}.publish`,
2155
+ stage: "test",
2156
+ composition: "mesh",
2157
+ value: pub.logicalPath,
2158
+ reason: "mesh.test is isolated; dependency endpoints are not materialized and cannot be published"
2159
+ });
2160
+ }
2161
+ }
2162
+ const appPublications = publication.filter((pub) => pub.target === "app").sort(
2163
+ (a, b) => a.ownerMeshService.localeCompare(b.ownerMeshService) || a.endpoint.localeCompare(b.endpoint)
2164
+ ).map((pub) => {
2165
+ const endpoint = services[pub.ownerMeshService].effectiveBuild.app.endpoints[pub.endpoint];
2166
+ return {
2167
+ meshService: pub.ownerMeshService,
2168
+ endpoint: pub.endpoint,
2169
+ logicalPath: pub.logicalPath,
2170
+ containerPort: endpoint.port,
2171
+ requested: endpoint.publicPort
2172
+ };
2173
+ });
2174
+ const allocatedPorts = /* @__PURE__ */ new Map();
2175
+ for (const name of Object.keys(services).sort((a, b) => a.localeCompare(b))) {
2176
+ const intents = appPublications.filter((pub) => pub.meshService === name).map((pub) => ({
2177
+ logicalPath: pub.logicalPath,
2178
+ requested: pub.requested
2179
+ }));
2180
+ const ownPorts = allocateHostPorts(
2181
+ meshDir,
2182
+ "test",
2183
+ intents,
2184
+ validationMode,
2185
+ { sourceFile: meshPath, composition: "mesh" }
2186
+ );
2187
+ for (const [logicalPath, port] of ownPorts) allocatedPorts.set(logicalPath, port);
2188
+ }
2189
+ return { bindings, appPublications, allocatedPorts };
2190
+ }
2191
+ function applyTestAppPublications(validated, meshService, app, endpointRegistry) {
2192
+ for (const publication of validated.appPublications) {
2193
+ if (publication.meshService !== meshService) continue;
2194
+ const published = validated.allocatedPorts.get(publication.logicalPath);
2195
+ const ports = Array.isArray(app.ports) ? app.ports : [];
2196
+ ports.push({
2197
+ target: publication.containerPort,
2198
+ published,
2199
+ host_ip: PUBLIC_HOST,
2200
+ protocol: "tcp"
2201
+ });
2202
+ app.ports = ports;
2203
+ const endpoint = endpointRegistry[publication.endpoint];
2204
+ if (endpoint) {
2205
+ endpoint.publicHost = PUBLIC_HOST;
2206
+ endpoint.publicPort = published;
2207
+ endpoint.effectivelyPublished = true;
2208
+ }
2209
+ }
2210
+ }
2211
+
1712
2212
  // src/core/mesh/checkers/checkMeshServices.ts
1713
- function checkMeshServices(mesh, meshDir) {
2213
+ function checkMeshServices(mesh, meshDir, options = {}) {
1714
2214
  const root = resolveProjectDir(meshDir), meshPath = path.join(root, "mesh.json");
1715
2215
  const checked = /* @__PURE__ */ new Set();
1716
- for (const stage of ["dev", "prod", "test", "e2e"]) {
2216
+ const stages = options.includeTestStage ? ["dev", "prod", "test", "e2e"] : ["dev", "prod", "e2e"];
2217
+ for (const stage of stages) {
1717
2218
  const effective = resolveMeshStage(mesh, stage, meshPath);
1718
2219
  const services = loadEffectiveMeshServices(root, effective, stage);
2220
+ const testValidation = stage === "test" ? validateMeshTestStage(services, root, meshPath, true) : void 0;
1719
2221
  for (const [name, svc] of Object.entries(services)) {
1720
2222
  if (!checked.has(svc.absolutePath)) {
1721
- console.log(pc22.cyan(`
2223
+ console.log(pc14.cyan(`
1722
2224
  \u{1F50D} Checking mesh service ${name}...`));
1723
2225
  checkInfra(svc.absolutePath);
1724
2226
  checked.add(svc.absolutePath);
1725
2227
  }
1726
2228
  if (stage === "test") {
1727
2229
  const fragment = compileServiceComposition("test", svc.absolutePath, { validationMode: true, meshMode: true, deferReferenceResolution: true });
2230
+ applyTestAppPublications(testValidation, name, fragment.compose.services.app, fragment.endpoints.app);
1728
2231
  const endpoints = { app: { [name]: fragment.endpoints.app }, dependencies: { [name]: fragment.endpoints.dependencies } };
1729
2232
  const ctx = { services: { [name]: svc }, bindings: /* @__PURE__ */ new Map(), endpoints, stage: "test", meshJsonPath: meshPath };
1730
2233
  for (const key of ["EXEC_MODE", "INFRA_MODE", ...Object.values(svc.effectiveBuild.app.endpoints).some((ep) => ep.primary) ? ["PORT"] : []]) {
1731
2234
  if (key in svc.meshEnv) throw new ConfigError({ sourceFile: meshPath, configPath: `services.${name}.env.${key}`, stage: "test", composition: "mesh", reason: "Mesh service env cannot set Builder-owned environment" });
1732
2235
  }
1733
- resolveServiceBuildEnvThroughMesh(name, fragment.builderAppEnvironment ?? {}, ctx, `services.${name}.app.env`);
2236
+ resolveMeshAppEnvironmentLayers(name, fragment.appEnvironmentLayers, ctx, new Set(Object.keys(svc.meshEnv)));
1734
2237
  for (const [depName, depEnv] of Object.entries(fragment.dependencyEnvironments ?? {})) resolveServiceBuildEnvThroughMesh(name, depEnv, ctx, `services.${name}.dependencies.${depName}.env`);
1735
2238
  resolveMeshEnvMap(svc.meshEnv, ctx, `services.${name}.env`);
1736
2239
  }
@@ -1753,11 +2256,13 @@ function checkMeshTester(mesh, meshDir, options = {}) {
1753
2256
  function checkMesh(meshDir = process.cwd(), options = {}) {
1754
2257
  const absMeshDir = resolveProjectDir(meshDir);
1755
2258
  const mesh = getMeshJson(absMeshDir);
1756
- checkMeshServices(mesh, absMeshDir);
2259
+ checkMeshServices(mesh, absMeshDir, {
2260
+ includeTestStage: Boolean(options.includeTestStage)
2261
+ });
1757
2262
  checkMeshTester(mesh, absMeshDir, { required: Boolean(options.requireTester) });
1758
2263
  console.log(
1759
- pc22.bold(
1760
- pc22.green("\n\u{1F389} All V2 mesh infrastructure, services, and contract checks passed!\n")
2264
+ pc14.bold(
2265
+ pc14.green("\n\u{1F389} All V2 mesh infrastructure, services, and contract checks passed!\n")
1761
2266
  )
1762
2267
  );
1763
2268
  }
@@ -1877,18 +2382,19 @@ function ensureSignalHandlers() {
1877
2382
  }
1878
2383
  if (isShuttingDown) return;
1879
2384
  isShuttingDown = true;
1880
- for (const item of activeComposeSet) {
1881
- try {
1882
- teardownCompose(item.yamlConfig, item.projectDir, {
1883
- removeVolumes: item.removeVolumes ?? false
1884
- }).catch(() => {
1885
- });
1886
- } catch {
1887
- }
1888
- }
1889
- activeComposeSet.clear();
1890
2385
  const signalNumber = os.constants.signals[signal] ?? 0;
1891
- process.exit(128 + signalNumber);
2386
+ void (async () => {
2387
+ for (const item of activeComposeSet) {
2388
+ try {
2389
+ await teardownCompose(item.yamlConfig, item.projectDir, {
2390
+ removeVolumes: item.removeVolumes ?? false
2391
+ });
2392
+ activeComposeSet.delete(item);
2393
+ } catch (error) {
2394
+ console.error("Compose cleanup failed during signal shutdown:", error);
2395
+ }
2396
+ }
2397
+ })().finally(() => process.exit(128 + signalNumber));
1892
2398
  };
1893
2399
  const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
1894
2400
  for (const sig of SIGNALS) {
@@ -1984,17 +2490,11 @@ async function teardownCompose(yamlConfig, projectDir, options = {}) {
1984
2490
  6e4
1985
2491
  );
1986
2492
  }
1987
- if (result.error) {
1988
- if (!silent) {
1989
- console.error(
1990
- pc22.red(`Failed to run docker compose down: ${result.error.message}`)
1991
- );
1992
- }
1993
- } else if (result.status !== 0 && !silent) {
1994
- console.error(
1995
- pc22.red(
1996
- `Docker compose down exited with non-zero status code: ${result.status}`
1997
- )
2493
+ if (result.error || result.status !== 0) {
2494
+ const detail = result.error?.message ?? `exit code ${result.status ?? "unknown"}`;
2495
+ throw new ScriptError(
2496
+ `Failed to tear down Compose project in ${absProjectDir} after two attempts: ${detail}`,
2497
+ result.error ? { cause: result.error } : void 0
1998
2498
  );
1999
2499
  }
2000
2500
  } finally {
@@ -2126,7 +2626,7 @@ async function handleMeshDown(rawStage = "dev", options = {}) {
2126
2626
  );
2127
2627
  }
2128
2628
  console.log(
2129
- pc22.cyan(`
2629
+ pc14.cyan(`
2130
2630
  \u{1F9F9} Stopping and tearing down global mesh environment [${stage}]...`)
2131
2631
  );
2132
2632
  if (options.debug) {
@@ -2134,7 +2634,7 @@ async function handleMeshDown(rawStage = "dev", options = {}) {
2134
2634
  const mode = stage === "dev" ? "dev" : stage === "test-e2e" ? "e2e" : "prod";
2135
2635
  const { yaml } = compileMeshEnvironment(mode, meshDir, { validateWithDocker: false });
2136
2636
  console.log(
2137
- pc22.yellow("\nFinal merged Mesh YAML configuration:\n"),
2637
+ pc14.yellow("\nFinal merged Mesh YAML configuration:\n"),
2138
2638
  redactYamlSecrets(yaml)
2139
2639
  );
2140
2640
  } catch {
@@ -2155,7 +2655,7 @@ async function handleMeshDown(rawStage = "dev", options = {}) {
2155
2655
  }
2156
2656
  clearRunState(meshDir);
2157
2657
  console.log(
2158
- pc22.green(`\u2705 Global mesh environment [${stage}] stopped and removed.
2658
+ pc14.green(`\u2705 Global mesh environment [${stage}] stopped and removed.
2159
2659
  `)
2160
2660
  );
2161
2661
  return 0;
@@ -2192,6 +2692,36 @@ Examples:
2192
2692
  }
2193
2693
  );
2194
2694
  };
2695
+
2696
+ // src/core/runWithCleanup.ts
2697
+ async function runWithCleanup(run, cleanup) {
2698
+ let executionFailed = false;
2699
+ let executionError;
2700
+ try {
2701
+ const status = await run();
2702
+ if (status !== 0) {
2703
+ executionFailed = true;
2704
+ executionError = new ScriptError(`Compose execution exited with code ${status}`, { exitCode: status });
2705
+ }
2706
+ return status;
2707
+ } catch (error) {
2708
+ executionFailed = true;
2709
+ executionError = error;
2710
+ throw error;
2711
+ } finally {
2712
+ try {
2713
+ await cleanup();
2714
+ } catch (cleanupError) {
2715
+ if (executionFailed) {
2716
+ throw new AggregateError(
2717
+ [executionError, cleanupError],
2718
+ `Compose execution failed (${errorMessage(executionError)}); cleanup also failed (${errorMessage(cleanupError)}). Saved run state was retained`
2719
+ );
2720
+ }
2721
+ throw cleanupError;
2722
+ }
2723
+ }
2724
+ }
2195
2725
  function extractHostPorts(yamlConfig) {
2196
2726
  const ports = [];
2197
2727
  try {
@@ -2199,15 +2729,9 @@ function extractHostPorts(yamlConfig) {
2199
2729
  if (parsed?.services && typeof parsed.services === "object") {
2200
2730
  for (const svc of Object.values(parsed.services)) {
2201
2731
  if (Array.isArray(svc?.ports)) {
2202
- for (const p of svc.ports) {
2203
- if (typeof p === "string") {
2204
- const parts = p.split(":");
2205
- const hostPort = parts.length > 1 ? parseInt(parts[0], 10) : parseInt(p, 10);
2206
- if (!isNaN(hostPort)) ports.push(hostPort);
2207
- } else if (typeof p === "object" && p.published) {
2208
- const hostPort = parseInt(p.published, 10);
2209
- if (!isNaN(hostPort)) ports.push(hostPort);
2210
- }
2732
+ for (const mapping of svc.ports) {
2733
+ const hostPort = parsePublishedHostPort(mapping);
2734
+ if (hostPort !== void 0) ports.push(hostPort);
2211
2735
  }
2212
2736
  }
2213
2737
  }
@@ -2298,19 +2822,19 @@ async function runCompose(args, yamlConfig, projectDir, options = {}) {
2298
2822
  // src/core/mesh/runners/runMeshDev.ts
2299
2823
  async function runMeshDev(options = {}) {
2300
2824
  const meshDir = resolveProjectDir(options.projectDir);
2301
- console.log(pc22.cyan(`
2825
+ console.log(pc14.cyan(`
2302
2826
  \u{1F680} Starting Global DEV Mesh Environment...`));
2303
2827
  const { yaml } = compileMeshEnvironment("dev", meshDir);
2304
2828
  const parsed = parse(yaml);
2305
2829
  const projectName = parsed?.name || "mesh-dev";
2306
2830
  if (options.debug) {
2307
2831
  console.log(
2308
- pc22.yellow("\nFinal merged Mesh Dev YAML configuration:\n"),
2832
+ pc14.yellow("\nFinal merged Mesh Dev YAML configuration:\n"),
2309
2833
  redactYamlSecrets(yaml)
2310
2834
  );
2311
2835
  }
2312
2836
  if (options.dryRun) {
2313
- console.log(pc22.green("Dry run complete. Compose was not started."));
2837
+ console.log(pc14.green("Dry run complete. Compose was not started."));
2314
2838
  return 0;
2315
2839
  }
2316
2840
  const hostPorts = extractHostPorts(yaml);
@@ -2325,34 +2849,34 @@ async function runMeshDev(options = {}) {
2325
2849
  if (options.detach) {
2326
2850
  upArgs.push("-d");
2327
2851
  }
2328
- let status = 0;
2329
- try {
2330
- status = await runCompose(upArgs, yaml, meshDir, {
2852
+ const status = await runWithCleanup(
2853
+ () => runCompose(upArgs, yaml, meshDir, {
2331
2854
  removeVolumes: false
2332
- });
2333
- } finally {
2334
- if (!options.detach) {
2335
- await teardownCompose(yaml, meshDir, { removeVolumes: false });
2336
- clearRunState(meshDir);
2855
+ }),
2856
+ async () => {
2857
+ if (!options.detach) {
2858
+ await teardownCompose(yaml, meshDir, { removeVolumes: false });
2859
+ clearRunState(meshDir);
2860
+ }
2337
2861
  }
2338
- }
2862
+ );
2339
2863
  return status;
2340
2864
  }
2341
2865
  async function runMeshProd(options = {}) {
2342
2866
  const meshDir = resolveProjectDir(options.projectDir);
2343
- console.log(pc22.cyan(`
2867
+ console.log(pc14.cyan(`
2344
2868
  \u{1F3ED} Starting Global PROD Mesh Environment...`));
2345
2869
  const { yaml } = compileMeshEnvironment("prod", meshDir);
2346
2870
  const parsed = parse(yaml);
2347
2871
  const projectName = parsed?.name || "mesh-prod";
2348
2872
  if (options.debug) {
2349
2873
  console.log(
2350
- pc22.yellow("\nFinal merged Mesh Prod YAML configuration:\n"),
2874
+ pc14.yellow("\nFinal merged Mesh Prod YAML configuration:\n"),
2351
2875
  redactYamlSecrets(yaml)
2352
2876
  );
2353
2877
  }
2354
2878
  if (options.dryRun) {
2355
- console.log(pc22.green("Dry run complete. Compose was not started."));
2879
+ console.log(pc14.green("Dry run complete. Compose was not started."));
2356
2880
  return 0;
2357
2881
  }
2358
2882
  const hostPorts = extractHostPorts(yaml);
@@ -2367,88 +2891,267 @@ async function runMeshProd(options = {}) {
2367
2891
  if (options.detach) {
2368
2892
  upArgs.push("-d");
2369
2893
  }
2370
- let status = 0;
2371
- try {
2372
- status = await runCompose(upArgs, yaml, meshDir, {
2894
+ const status = await runWithCleanup(
2895
+ () => runCompose(upArgs, yaml, meshDir, {
2373
2896
  removeVolumes: false
2374
- });
2375
- } finally {
2376
- if (!options.detach) {
2377
- await teardownCompose(yaml, meshDir, { removeVolumes: false });
2378
- clearRunState(meshDir);
2897
+ }),
2898
+ async () => {
2899
+ if (!options.detach) {
2900
+ await teardownCompose(yaml, meshDir, { removeVolumes: false });
2901
+ clearRunState(meshDir);
2902
+ }
2379
2903
  }
2380
- }
2904
+ );
2381
2905
  return status;
2382
2906
  }
2383
- async function runMeshTestUnit(options = {}) {
2384
- const meshDir = resolveProjectDir(options.projectDir), meshPath = path.join(meshDir, "mesh.json"), raw = getMeshJson(meshDir), effective = resolveMeshStage(raw, "test", meshPath), services = loadEffectiveMeshServices(meshDir, effective, "test");
2385
- console.log(pc22.bold(pc22.blue("\n[1/2] MESH SERVICE UNIT/ISOLATED TESTS\n")));
2386
- for (const [name, svc] of Object.entries(services).sort(([a], [b]) => a.localeCompare(b))) {
2387
- console.log(pc22.cyan(`-> Running isolated unit tests for [${name}]`));
2388
- const compiled = compileServiceComposition("test", svc.absolutePath, { meshMode: true, full: false, externalAppEnv: {}, deferReferenceResolution: true, appServiceName: "app" });
2389
- const endpoints = { app: { [name]: compiled.endpoints.app }, dependencies: { [name]: compiled.endpoints.dependencies } };
2390
- const refCtx = { services: { [name]: svc }, bindings: /* @__PURE__ */ new Map(), endpoints, stage: "test", meshJsonPath: meshPath };
2391
- const env = svc.meshEnv;
2392
- 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" });
2393
- const resolvedBuild = resolveServiceBuildEnvThroughMesh(name, compiled.builderAppEnvironment ?? {}, refCtx, `services.${name}.app.env`);
2394
- for (const [depName, depEnv] of Object.entries(compiled.dependencyEnvironments ?? {})) resolveServiceBuildEnvThroughMesh(name, depEnv, refCtx, `services.${name}.dependencies.${depName}.env`);
2395
- const resolved = resolveMeshEnvMap(env, refCtx, `services.${name}.env`);
2396
- const app = compiled.compose.services.app;
2397
- app.environment = { ...app.environment, ...resolvedBuild, ...resolved };
2398
- const projectName = `${deriveProjectName(raw.name ?? path.basename(meshDir), "dev")}-${name}-test`;
2399
- compiled.compose.name = projectName;
2400
- const yaml = stringify(compiled.compose);
2401
- if (options.debug) console.log(yaml);
2402
- if (options.dryRun) {
2403
- console.log(pc22.green(`[DRY-RUN] Unit tests for ${name} compiled.`));
2404
- continue;
2405
- }
2406
- await teardownCompose(yaml, svc.absolutePath, { removeVolumes: true, silent: true });
2407
- writeRunState(svc.absolutePath, { projectName, stage: "test-unit", projectDir: svc.absolutePath });
2408
- let status;
2409
- try {
2410
- status = await runCompose(["up", "--build", "--abort-on-container-exit", "--exit-code-from", "app"], yaml, svc.absolutePath, { removeVolumes: true });
2411
- } finally {
2412
- await teardownCompose(yaml, svc.absolutePath, { removeVolumes: true });
2413
- clearRunState(svc.absolutePath);
2414
- }
2415
- if (status !== 0) return status;
2907
+ var compileEnvironment = (stage, projectDir = process.cwd(), options = {}) => stringify(compileServiceComposition(stage, projectDir, { full: Boolean(options.full), silenceWarnings: options.silenceWarnings }).compose);
2908
+
2909
+ // src/core/runners/runTestUnit.ts
2910
+ var runTestUnit = async (options) => {
2911
+ if (!options.skipBanner) {
2912
+ console.log(pc14.bold(pc14.blue(`
2913
+ ========================================`)));
2914
+ console.log(pc14.bold(pc14.blue(`\u{1F9EA} STAGE: UNIT & ISOLATED TESTS`)));
2915
+ console.log(pc14.bold(pc14.blue(`========================================
2916
+ `)));
2917
+ }
2918
+ const finalYamlConfig = compileEnvironment("test", options.projectDir, {
2919
+ silenceWarnings: options.silenceWarnings
2920
+ });
2921
+ const parsed = parse(finalYamlConfig);
2922
+ const projectName = parsed?.name || "test";
2923
+ if (options.debug) {
2924
+ console.log(
2925
+ pc14.yellow("Final merged YAML configuration:\n"),
2926
+ redactYamlSecrets(finalYamlConfig)
2927
+ );
2416
2928
  }
2417
- return 0;
2418
- }
2419
- async function runMeshTestE2e(options = {}) {
2420
- const meshDir = resolveProjectDir(options.projectDir), mesh = getMeshJson(meshDir);
2421
- if (!mesh.tester) throw new ScriptError("Global mesh E2E requires root mesh.json.tester { compose, service, env? }");
2422
- const { yaml, testerServiceName } = compileMeshEnvironment("e2e", meshDir);
2423
- if (!testerServiceName) throw new ScriptError("Global mesh E2E tester runner could not be compiled.");
2424
- if (options.debug) console.log(pc22.yellow("\nFinal global mesh E2E YAML configuration:\n"), redactYamlSecrets(yaml));
2425
2929
  if (options.dryRun) {
2426
- console.log(pc22.green("[DRY-RUN] Global mesh E2E compiled; Compose was not started."));
2930
+ console.log(pc14.green("[DRY-RUN] Unit tests simulated. Compose was not started."));
2427
2931
  return 0;
2428
2932
  }
2429
- await checkHostPortCollisions(extractHostPorts(yaml));
2430
- const projectName = parse(yaml)?.name || "mesh-e2e";
2431
- await teardownCompose(yaml, meshDir, { removeVolumes: true, silent: true });
2432
- writeRunState(meshDir, { projectName, stage: "test-e2e", projectDir: meshDir });
2433
- let status = 0;
2434
- try {
2435
- status = await runCompose(["up", "--build", "--abort-on-container-exit", "--exit-code-from", testerServiceName], yaml, meshDir, { removeVolumes: true });
2436
- } finally {
2437
- await teardownCompose(yaml, meshDir, { removeVolumes: true });
2438
- clearRunState(meshDir);
2933
+ await checkHostPortCollisions(extractHostPorts(finalYamlConfig));
2934
+ await teardownCompose(finalYamlConfig, options.projectDir, {
2935
+ removeVolumes: true,
2936
+ silent: true
2937
+ });
2938
+ writeRunState(options.projectDir, {
2939
+ projectName,
2940
+ stage: "test-unit",
2941
+ projectDir: options.projectDir
2942
+ });
2943
+ const status = await runWithCleanup(
2944
+ () => runCompose(
2945
+ ["up", "--build", "--abort-on-container-exit", "--exit-code-from", "app"],
2946
+ finalYamlConfig,
2947
+ options.projectDir,
2948
+ { removeVolumes: true }
2949
+ ),
2950
+ async () => {
2951
+ await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
2952
+ clearRunState(options.projectDir);
2953
+ }
2954
+ );
2955
+ if (status === 0) {
2956
+ console.log(pc14.bold(pc14.green(`
2957
+ \u2705 Unit tests passed successfully.
2958
+ `)));
2959
+ } else {
2960
+ console.error(pc14.red(`
2961
+ \u274C Unit tests failed with exit code ${status}.
2962
+ `));
2963
+ }
2964
+ return status;
2965
+ };
2966
+ var runTestE2e = async (options) => {
2967
+ if (!options.skipBanner) {
2968
+ console.log(pc14.bold(pc14.blue(`
2969
+ ========================================`)));
2970
+ console.log(pc14.bold(pc14.blue(`\u{1F6A6} STAGE: INTEGRATED E2E TESTS`)));
2971
+ console.log(pc14.bold(pc14.blue(`========================================
2972
+ `)));
2973
+ }
2974
+ const finalYamlConfig = compileEnvironment("e2e", options.projectDir, {
2975
+ silenceWarnings: options.silenceWarnings
2976
+ });
2977
+ const parsed = parse(finalYamlConfig);
2978
+ const projectName = parsed?.name || "e2e";
2979
+ if (options.debug) {
2980
+ console.log(
2981
+ pc14.yellow("Final merged YAML configuration:\n"),
2982
+ redactYamlSecrets(finalYamlConfig)
2983
+ );
2984
+ }
2985
+ if (options.dryRun) {
2986
+ console.log(pc14.green("[DRY-RUN] E2E tests simulated. Compose was not started."));
2987
+ return 0;
2988
+ }
2989
+ await checkHostPortCollisions(extractHostPorts(finalYamlConfig));
2990
+ await teardownCompose(finalYamlConfig, options.projectDir, {
2991
+ removeVolumes: true,
2992
+ silent: true
2993
+ });
2994
+ writeRunState(options.projectDir, {
2995
+ projectName,
2996
+ stage: "test-e2e",
2997
+ projectDir: options.projectDir
2998
+ });
2999
+ const status = await runWithCleanup(
3000
+ () => runCompose(
3001
+ [
3002
+ "up",
3003
+ "--build",
3004
+ "--abort-on-container-exit",
3005
+ "--exit-code-from",
3006
+ "tester"
3007
+ ],
3008
+ finalYamlConfig,
3009
+ options.projectDir,
3010
+ { removeVolumes: true }
3011
+ ),
3012
+ async () => {
3013
+ await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
3014
+ clearRunState(options.projectDir);
3015
+ }
3016
+ );
3017
+ if (status === 0) {
3018
+ console.log(pc14.bold(pc14.green(`
3019
+ \u2705 E2E tests passed successfully.
3020
+ `)));
3021
+ } else {
3022
+ console.error(pc14.red(`
3023
+ \u274C E2E tests failed with exit code ${status}.
3024
+ `));
3025
+ }
3026
+ return status;
3027
+ };
3028
+
3029
+ // src/core/runners/runTest.ts
3030
+ var runTest = async (options) => {
3031
+ console.log(pc14.bold(pc14.blue(`
3032
+ ========================================`)));
3033
+ console.log(pc14.bold(pc14.blue(`\u{1F9EA} [1/2] STAGE: UNIT & ISOLATED TESTS`)));
3034
+ console.log(pc14.bold(pc14.blue(`========================================
3035
+ `)));
3036
+ const unitStatus = await runTestUnit({ ...options, skipBanner: true });
3037
+ if (unitStatus !== 0) {
3038
+ console.error(
3039
+ pc14.red(
3040
+ `
3041
+ \u274C [1/2] Unit tests failed with exit code ${unitStatus}. Aborting E2E tests.
3042
+ `
3043
+ )
3044
+ );
3045
+ return unitStatus;
3046
+ }
3047
+ console.log(
3048
+ pc14.bold(pc14.green(`
3049
+ \u2705 [1/2] Unit tests passed successfully.
3050
+ `))
3051
+ );
3052
+ console.log(pc14.bold(pc14.blue(`========================================`)));
3053
+ console.log(pc14.bold(pc14.blue(`\u{1F6A6} [2/2] STAGE: INTEGRATED E2E TESTS`)));
3054
+ console.log(pc14.bold(pc14.blue(`========================================
3055
+ `)));
3056
+ const e2eStatus = await runTestE2e({ ...options, skipBanner: true });
3057
+ if (e2eStatus !== 0) {
3058
+ console.error(
3059
+ pc14.red(`
3060
+ \u274C [2/2] E2E tests failed with exit code ${e2eStatus}.
3061
+ `)
3062
+ );
3063
+ return e2eStatus;
3064
+ }
3065
+ console.log(pc14.bold(pc14.green(`
3066
+ \u2705 [2/2] E2E tests passed successfully.
3067
+ `)));
3068
+ console.log(
3069
+ pc14.bold(
3070
+ pc14.green(`\u{1F389} All test stages (unit + e2e) completed successfully!
3071
+ `)
3072
+ )
3073
+ );
3074
+ return 0;
3075
+ };
3076
+
3077
+ // src/core/mesh/runners/runMeshServiceTests.ts
3078
+ async function runMeshServiceTests(options = {}) {
3079
+ const meshDir = resolveProjectDir(options.projectDir), meshPath = path.join(meshDir, "mesh.json"), mesh = getMeshJson(meshDir);
3080
+ const rootServices = Object.entries(mesh.services).sort(([left], [right]) => left.localeCompare(right));
3081
+ for (const [serviceName, service] of rootServices) {
3082
+ const serviceDir = resolveInsideProject(meshDir, service.path, { sourceFile: meshPath, configPath: `services.${serviceName}.path`, stage: "test" });
3083
+ console.log(pc14.bold(pc14.cyan(`
3084
+ -> Running full standalone test lifecycle for [${serviceName}]
3085
+ `)));
3086
+ const status = await runTest({ projectDir: serviceDir, debug: Boolean(options.debug), detach: false, skipBanner: true, silenceWarnings: false, ...options.dryRun !== void 0 ? { dryRun: options.dryRun } : {} });
3087
+ if (status !== 0) return status;
2439
3088
  }
3089
+ return 0;
3090
+ }
3091
+ async function runMeshTestE2e(options = {}) {
3092
+ const meshDir = resolveProjectDir(options.projectDir), mesh = getMeshJson(meshDir);
3093
+ if (!mesh.tester) throw new ScriptError("Global mesh E2E requires root mesh.json.tester { compose, service, env? }");
3094
+ const { yaml, testerServiceName } = compileMeshEnvironment("e2e", meshDir);
3095
+ if (!testerServiceName) throw new ScriptError("Global mesh E2E tester runner could not be compiled.");
3096
+ if (options.debug) console.log(pc14.yellow("\nFinal global mesh E2E YAML configuration:\n"), redactYamlSecrets(yaml));
3097
+ if (options.dryRun) {
3098
+ console.log(pc14.green("[DRY-RUN] Global mesh E2E compiled; Compose was not started."));
3099
+ return 0;
3100
+ }
3101
+ await checkHostPortCollisions(extractHostPorts(yaml));
3102
+ const projectName = parse(yaml)?.name || "mesh-e2e";
3103
+ await teardownCompose(yaml, meshDir, { removeVolumes: true, silent: true });
3104
+ writeRunState(meshDir, { projectName, stage: "test-e2e", projectDir: meshDir });
3105
+ const status = await runWithCleanup(() => runCompose(["up", "--build", "--abort-on-container-exit", "--exit-code-from", testerServiceName], yaml, meshDir, { removeVolumes: true }), async () => {
3106
+ await teardownCompose(yaml, meshDir, { removeVolumes: true });
3107
+ clearRunState(meshDir);
3108
+ });
2440
3109
  return status;
2441
3110
  }
2442
3111
 
2443
3112
  // src/core/mesh/runners/runMeshTest.ts
2444
3113
  async function runMeshTest(options = {}) {
2445
- console.log(pc22.bold(pc22.blue("\n========================================\nMESH TEST PIPELINE\n========================================\n")));
2446
- console.log(pc22.bold(pc22.blue("[1/2] MESH SERVICE UNIT/ISOLATED TESTS")));
2447
- const unitStatus = await runMeshTestUnit(options);
2448
- if (unitStatus !== 0) return unitStatus;
2449
- console.log(pc22.bold(pc22.blue("[2/2] GLOBAL MESH E2E")));
3114
+ console.log(pc14.bold(pc14.blue("\n========================================\nMESH TEST PIPELINE\n========================================\n")));
3115
+ console.log(pc14.bold(pc14.blue("[1/2] ROOT SERVICE TEST LIFECYCLES")));
3116
+ const serviceStatus = await runMeshServiceTests(options);
3117
+ if (serviceStatus !== 0) return serviceStatus;
3118
+ console.log(pc14.bold(pc14.blue("[2/2] GLOBAL MESH E2E")));
2450
3119
  return runMeshTestE2e(options);
2451
3120
  }
3121
+ async function runMeshTestUnit(options = {}) {
3122
+ const meshDir = resolveProjectDir(options.projectDir), meshPath = path.join(meshDir, "mesh.json"), raw = getMeshJson(meshDir), effective = resolveMeshStage(raw, "test", meshPath), services = loadEffectiveMeshServices(meshDir, effective, "test"), validated = validateMeshTestStage(services, meshDir, meshPath, Boolean(options.dryRun));
3123
+ console.log(pc14.bold(pc14.blue("\nEXPLICIT MESH TEST-STAGE (UNIT/ISOLATED)\n")));
3124
+ for (const [name, svc] of Object.entries(services).sort(([a], [b]) => a.localeCompare(b))) {
3125
+ console.log(pc14.cyan(`-> Running isolated unit tests for [${name}]`));
3126
+ const compiled = compileServiceComposition("test", svc.absolutePath, { meshMode: true, full: false, externalAppEnv: {}, deferReferenceResolution: true, appServiceName: "app" });
3127
+ const app = compiled.compose.services.app;
3128
+ applyTestAppPublications(validated, name, app, compiled.endpoints.app);
3129
+ const endpoints = { app: { [name]: compiled.endpoints.app }, dependencies: { [name]: compiled.endpoints.dependencies } };
3130
+ const refCtx = { services: { [name]: svc }, bindings: /* @__PURE__ */ new Map(), endpoints, stage: "test", meshJsonPath: meshPath };
3131
+ const env = svc.meshEnv;
3132
+ for (const key of ["EXEC_MODE", "INFRA_MODE", ...Object.keys(svc.effectiveBuild.app.endpoints).some((k) => svc.effectiveBuild.app.endpoints[k]?.primary) ? ["PORT"] : []]) if (key in env) throw new ConfigError({ sourceFile: meshPath, configPath: `services.${name}.env.${key}`, stage: "test", composition: "mesh", reason: "Mesh service env cannot set Builder-owned environment" });
3133
+ const resolvedBuild = resolveMeshAppEnvironmentLayers(name, compiled.appEnvironmentLayers, refCtx, new Set(Object.keys(svc.meshEnv)));
3134
+ for (const [depName, depEnv] of Object.entries(compiled.dependencyEnvironments ?? {})) resolveServiceBuildEnvThroughMesh(name, depEnv, refCtx, `services.${name}.dependencies.${depName}.env`);
3135
+ const resolved = resolveMeshEnvMap(env, refCtx, `services.${name}.env`);
3136
+ app.environment = { ...resolvedBuild, ...resolved, ...compiled.builderInternalEnvironment ?? {} };
3137
+ const projectName = `${deriveProjectName(raw.name ?? path.basename(meshDir), "dev")}-${name}-test`;
3138
+ compiled.compose.name = projectName;
3139
+ const yaml = stringify(compiled.compose);
3140
+ if (options.debug) console.log(redactYamlSecrets(yaml));
3141
+ if (options.dryRun) {
3142
+ console.log(pc14.green(`[DRY-RUN] Unit tests for ${name} compiled.`));
3143
+ continue;
3144
+ }
3145
+ await teardownCompose(yaml, svc.absolutePath, { removeVolumes: true, silent: true });
3146
+ writeRunState(svc.absolutePath, { projectName, stage: "test-unit", projectDir: svc.absolutePath });
3147
+ const status = await runWithCleanup(() => runCompose(["up", "--build", "--abort-on-container-exit", "--exit-code-from", "app"], yaml, svc.absolutePath, { removeVolumes: true }), async () => {
3148
+ await teardownCompose(yaml, svc.absolutePath, { removeVolumes: true });
3149
+ clearRunState(svc.absolutePath);
3150
+ });
3151
+ if (status !== 0) return status;
3152
+ }
3153
+ return 0;
3154
+ }
2452
3155
 
2453
3156
  // src/commands/mesh/commands/up/handler.ts
2454
3157
  async function handleMeshUp(rawStage = "dev", options = {}) {
@@ -2459,7 +3162,10 @@ async function handleMeshUp(rawStage = "dev", options = {}) {
2459
3162
  projectDir
2460
3163
  };
2461
3164
  if (["dev", "prod", "test-unit", "test-e2e", "test"].includes(stage) && !options.skipChecks) {
2462
- checkMesh(projectDir, { requireTester: stage === "test-e2e" || stage === "test" });
3165
+ checkMesh(projectDir, {
3166
+ requireTester: stage === "test-e2e" || stage === "test",
3167
+ includeTestStage: stage === "test-unit"
3168
+ });
2463
3169
  }
2464
3170
  switch (stage) {
2465
3171
  case "dev":
@@ -2506,7 +3212,8 @@ Examples:
2506
3212
  $ builder mesh up test-e2e
2507
3213
 
2508
3214
  JSON overlays: test-unit uses mesh/build test; test-e2e uses mesh/build e2e.
2509
- The test command runs per-service unit tests before global E2E.`
3215
+ The test command runs each root service test lifecycle (unit, then service E2E) before global E2E.
3216
+ The explicit test-unit stage exercises mesh.json.test overlays only.`
2510
3217
  ).action(
2511
3218
  async (stage = "dev", options = {}) => {
2512
3219
  const exitCode = await handleMeshUp(stage, {
@@ -2534,7 +3241,7 @@ var registerMeshCommand = (program) => {
2534
3241
  registerMeshCheckCommand(meshCmd);
2535
3242
  };
2536
3243
  async function handlePrune(options = {}) {
2537
- console.log(pc22.cyan("\n\u{1F9F9} Pruning stopped Compose containers and unused networks..."));
3244
+ console.log(pc14.cyan("\n\u{1F9F9} Pruning stopped Compose containers and unused networks..."));
2538
3245
  const rmContainers = spawnSync("docker", ["container", "prune", "-f"], {
2539
3246
  stdio: "inherit",
2540
3247
  encoding: "utf-8"
@@ -2554,13 +3261,13 @@ async function handlePrune(options = {}) {
2554
3261
  });
2555
3262
  }
2556
3263
  if (options.volumes) {
2557
- console.log(pc22.cyan("\u{1F9F9} Pruning dangling volumes..."));
3264
+ console.log(pc14.cyan("\u{1F9F9} Pruning dangling volumes..."));
2558
3265
  spawnSync("docker", ["volume", "prune", "-f"], {
2559
3266
  stdio: "inherit",
2560
3267
  encoding: "utf-8"
2561
3268
  });
2562
3269
  }
2563
- console.log(pc22.green("\u2705 Docker environment pruned successfully.\n"));
3270
+ console.log(pc14.green("\u2705 Docker environment pruned successfully.\n"));
2564
3271
  return 0;
2565
3272
  }
2566
3273
 
@@ -2575,9 +3282,6 @@ var registerPruneCommand = (cmd) => {
2575
3282
  }
2576
3283
  });
2577
3284
  };
2578
- var compileEnvironment = (stage, projectDir = process.cwd(), options = {}) => stringify(compileServiceComposition(stage, projectDir, { full: Boolean(options.full), silenceWarnings: options.silenceWarnings }).compose);
2579
-
2580
- // src/commands/service/commands/down/handler.ts
2581
3285
  async function handleServiceDown(rawStage = "dev", options = {}) {
2582
3286
  const projectDir = resolveProjectDir(options.projectDir);
2583
3287
  const stage = (rawStage || "dev").toLowerCase();
@@ -2588,7 +3292,7 @@ async function handleServiceDown(rawStage = "dev", options = {}) {
2588
3292
  );
2589
3293
  }
2590
3294
  console.log(
2591
- pc22.cyan(`
3295
+ pc14.cyan(`
2592
3296
  \u{1F9F9} Stopping and tearing down service environment [${stage}]...`)
2593
3297
  );
2594
3298
  if (options.debug) {
@@ -2599,7 +3303,7 @@ async function handleServiceDown(rawStage = "dev", options = {}) {
2599
3303
  else if (stage === "test-e2e") env = "e2e";
2600
3304
  const finalYamlConfig = compileEnvironment(env, projectDir);
2601
3305
  console.log(
2602
- pc22.yellow("Final merged YAML configuration:\n"),
3306
+ pc14.yellow("Final merged YAML configuration:\n"),
2603
3307
  redactYamlSecrets(finalYamlConfig)
2604
3308
  );
2605
3309
  } catch {
@@ -2620,7 +3324,7 @@ async function handleServiceDown(rawStage = "dev", options = {}) {
2620
3324
  }
2621
3325
  clearRunState(projectDir);
2622
3326
  console.log(
2623
- pc22.green(`\u2705 Service environment [${stage}] stopped and removed.
3327
+ pc14.green(`\u2705 Service environment [${stage}] stopped and removed.
2624
3328
  `)
2625
3329
  );
2626
3330
  return 0;
@@ -2659,7 +3363,7 @@ Examples:
2659
3363
  };
2660
3364
  var runDev = async (options) => {
2661
3365
  console.log(
2662
- pc22.cyan(
3366
+ pc14.cyan(
2663
3367
  options.full ? `\u{1F680} Starting DEV environment (full / integrated)...` : `\u{1F680} Starting DEV environment...`
2664
3368
  )
2665
3369
  );
@@ -2671,12 +3375,12 @@ var runDev = async (options) => {
2671
3375
  const projectName = parsed?.name || "dev";
2672
3376
  if (options.debug) {
2673
3377
  console.log(
2674
- pc22.yellow("Final merged YAML configuration:\n"),
3378
+ pc14.yellow("Final merged YAML configuration:\n"),
2675
3379
  redactYamlSecrets(finalYamlConfig)
2676
3380
  );
2677
3381
  }
2678
3382
  if (options.dryRun) {
2679
- console.log(pc22.green("Dry run complete. Compose was not started."));
3383
+ console.log(pc14.green("Dry run complete. Compose was not started."));
2680
3384
  return 0;
2681
3385
  }
2682
3386
  const hostPorts = extractHostPorts(finalYamlConfig);
@@ -2691,23 +3395,23 @@ var runDev = async (options) => {
2691
3395
  if (options.detach) {
2692
3396
  upArgs.push("-d");
2693
3397
  }
2694
- let status = 0;
2695
- try {
2696
- status = await runCompose(upArgs, finalYamlConfig, options.projectDir, {
3398
+ const status = await runWithCleanup(
3399
+ () => runCompose(upArgs, finalYamlConfig, options.projectDir, {
2697
3400
  removeVolumes: false
2698
- });
2699
- } finally {
2700
- if (!options.detach) {
2701
- await teardownCompose(finalYamlConfig, options.projectDir, {
2702
- removeVolumes: false
2703
- });
2704
- clearRunState(options.projectDir);
3401
+ }),
3402
+ async () => {
3403
+ if (!options.detach) {
3404
+ await teardownCompose(finalYamlConfig, options.projectDir, {
3405
+ removeVolumes: false
3406
+ });
3407
+ clearRunState(options.projectDir);
3408
+ }
2705
3409
  }
2706
- }
3410
+ );
2707
3411
  return status;
2708
3412
  };
2709
3413
  var runProd = async (options) => {
2710
- console.log(pc22.cyan(`\u{1F3ED} Starting PROD environment...`));
3414
+ console.log(pc14.cyan(`\u{1F3ED} Starting PROD environment...`));
2711
3415
  const finalYamlConfig = compileEnvironment("prod", options.projectDir, {
2712
3416
  silenceWarnings: options.silenceWarnings
2713
3417
  });
@@ -2715,12 +3419,12 @@ var runProd = async (options) => {
2715
3419
  const projectName = parsed?.name || "prod";
2716
3420
  if (options.debug) {
2717
3421
  console.log(
2718
- pc22.yellow("Final merged YAML configuration:\n"),
3422
+ pc14.yellow("Final merged YAML configuration:\n"),
2719
3423
  redactYamlSecrets(finalYamlConfig)
2720
3424
  );
2721
3425
  }
2722
3426
  if (options.dryRun) {
2723
- console.log(pc22.green("Dry run complete. Compose was not started."));
3427
+ console.log(pc14.green("Dry run complete. Compose was not started."));
2724
3428
  return 0;
2725
3429
  }
2726
3430
  const hostPorts = extractHostPorts(finalYamlConfig);
@@ -2735,186 +3439,20 @@ var runProd = async (options) => {
2735
3439
  if (options.detach) {
2736
3440
  upArgs.push("-d");
2737
3441
  }
2738
- let status = 0;
2739
- try {
2740
- status = await runCompose(upArgs, finalYamlConfig, options.projectDir, {
3442
+ const status = await runWithCleanup(
3443
+ () => runCompose(upArgs, finalYamlConfig, options.projectDir, {
2741
3444
  removeVolumes: false
2742
- });
2743
- } finally {
2744
- if (!options.detach) {
2745
- await teardownCompose(finalYamlConfig, options.projectDir, {
2746
- removeVolumes: false
2747
- });
2748
- clearRunState(options.projectDir);
3445
+ }),
3446
+ async () => {
3447
+ if (!options.detach) {
3448
+ await teardownCompose(finalYamlConfig, options.projectDir, {
3449
+ removeVolumes: false
3450
+ });
3451
+ clearRunState(options.projectDir);
3452
+ }
2749
3453
  }
2750
- }
2751
- return status;
2752
- };
2753
- var runTestUnit = async (options) => {
2754
- if (!options.skipBanner) {
2755
- console.log(pc22.bold(pc22.blue(`
2756
- ========================================`)));
2757
- console.log(pc22.bold(pc22.blue(`\u{1F9EA} STAGE: UNIT & ISOLATED TESTS`)));
2758
- console.log(pc22.bold(pc22.blue(`========================================
2759
- `)));
2760
- }
2761
- const finalYamlConfig = compileEnvironment("test", options.projectDir, {
2762
- silenceWarnings: options.silenceWarnings
2763
- });
2764
- const parsed = parse(finalYamlConfig);
2765
- const projectName = parsed?.name || "test";
2766
- if (options.debug) {
2767
- console.log(
2768
- pc22.yellow("Final merged YAML configuration:\n"),
2769
- redactYamlSecrets(finalYamlConfig)
2770
- );
2771
- }
2772
- if (options.dryRun) {
2773
- console.log(pc22.green("[DRY-RUN] Unit tests simulated. Compose was not started."));
2774
- return 0;
2775
- }
2776
- await checkHostPortCollisions(extractHostPorts(finalYamlConfig));
2777
- await teardownCompose(finalYamlConfig, options.projectDir, {
2778
- removeVolumes: true,
2779
- silent: true
2780
- });
2781
- writeRunState(options.projectDir, {
2782
- projectName,
2783
- stage: "test-unit",
2784
- projectDir: options.projectDir
2785
- });
2786
- let status = 0;
2787
- try {
2788
- status = await runCompose(
2789
- ["up", "--build", "--abort-on-container-exit", "--exit-code-from", "app"],
2790
- finalYamlConfig,
2791
- options.projectDir,
2792
- { removeVolumes: true }
2793
- );
2794
- } finally {
2795
- await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
2796
- clearRunState(options.projectDir);
2797
- }
2798
- if (status === 0) {
2799
- console.log(pc22.bold(pc22.green(`
2800
- \u2705 Unit tests passed successfully.
2801
- `)));
2802
- } else {
2803
- console.error(pc22.red(`
2804
- \u274C Unit tests failed with exit code ${status}.
2805
- `));
2806
- }
2807
- return status;
2808
- };
2809
- var runTestE2e = async (options) => {
2810
- if (!options.skipBanner) {
2811
- console.log(pc22.bold(pc22.blue(`
2812
- ========================================`)));
2813
- console.log(pc22.bold(pc22.blue(`\u{1F6A6} STAGE: INTEGRATED E2E TESTS`)));
2814
- console.log(pc22.bold(pc22.blue(`========================================
2815
- `)));
2816
- }
2817
- const finalYamlConfig = compileEnvironment("e2e", options.projectDir, {
2818
- silenceWarnings: options.silenceWarnings
2819
- });
2820
- const parsed = parse(finalYamlConfig);
2821
- const projectName = parsed?.name || "e2e";
2822
- if (options.debug) {
2823
- console.log(
2824
- pc22.yellow("Final merged YAML configuration:\n"),
2825
- redactYamlSecrets(finalYamlConfig)
2826
- );
2827
- }
2828
- if (options.dryRun) {
2829
- console.log(pc22.green("[DRY-RUN] E2E tests simulated. Compose was not started."));
2830
- return 0;
2831
- }
2832
- await checkHostPortCollisions(extractHostPorts(finalYamlConfig));
2833
- await teardownCompose(finalYamlConfig, options.projectDir, {
2834
- removeVolumes: true,
2835
- silent: true
2836
- });
2837
- writeRunState(options.projectDir, {
2838
- projectName,
2839
- stage: "test-e2e",
2840
- projectDir: options.projectDir
2841
- });
2842
- let status = 0;
2843
- try {
2844
- status = await runCompose(
2845
- [
2846
- "up",
2847
- "--build",
2848
- "--abort-on-container-exit",
2849
- "--exit-code-from",
2850
- "tester"
2851
- ],
2852
- finalYamlConfig,
2853
- options.projectDir,
2854
- { removeVolumes: true }
2855
- );
2856
- } finally {
2857
- await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
2858
- clearRunState(options.projectDir);
2859
- }
2860
- if (status === 0) {
2861
- console.log(pc22.bold(pc22.green(`
2862
- \u2705 E2E tests passed successfully.
2863
- `)));
2864
- } else {
2865
- console.error(pc22.red(`
2866
- \u274C E2E tests failed with exit code ${status}.
2867
- `));
2868
- }
2869
- return status;
2870
- };
2871
-
2872
- // src/core/runners/runTest.ts
2873
- var runTest = async (options) => {
2874
- console.log(pc22.bold(pc22.blue(`
2875
- ========================================`)));
2876
- console.log(pc22.bold(pc22.blue(`\u{1F9EA} [1/2] STAGE: UNIT & ISOLATED TESTS`)));
2877
- console.log(pc22.bold(pc22.blue(`========================================
2878
- `)));
2879
- const unitStatus = await runTestUnit({ ...options, skipBanner: true });
2880
- if (unitStatus !== 0) {
2881
- console.error(
2882
- pc22.red(
2883
- `
2884
- \u274C [1/2] Unit tests failed with exit code ${unitStatus}. Aborting E2E tests.
2885
- `
2886
- )
2887
- );
2888
- return unitStatus;
2889
- }
2890
- console.log(
2891
- pc22.bold(pc22.green(`
2892
- \u2705 [1/2] Unit tests passed successfully.
2893
- `))
2894
3454
  );
2895
- console.log(pc22.bold(pc22.blue(`========================================`)));
2896
- console.log(pc22.bold(pc22.blue(`\u{1F6A6} [2/2] STAGE: INTEGRATED E2E TESTS`)));
2897
- console.log(pc22.bold(pc22.blue(`========================================
2898
- `)));
2899
- const e2eStatus = await runTestE2e({ ...options, skipBanner: true });
2900
- if (e2eStatus !== 0) {
2901
- console.error(
2902
- pc22.red(`
2903
- \u274C [2/2] E2E tests failed with exit code ${e2eStatus}.
2904
- `)
2905
- );
2906
- return e2eStatus;
2907
- }
2908
- console.log(pc22.bold(pc22.green(`
2909
- \u2705 [2/2] E2E tests passed successfully.
2910
- `)));
2911
- console.log(
2912
- pc22.bold(
2913
- pc22.green(`\u{1F389} All test stages (unit + e2e) completed successfully!
2914
- `)
2915
- )
2916
- );
2917
- return 0;
3455
+ return status;
2918
3456
  };
2919
3457
 
2920
3458
  // src/commands/service/commands/up/handler.ts
@@ -3047,6 +3585,16 @@ async function handleExportEnv(rawStage, options = {}) {
3047
3585
  throw new ScriptError(`Unknown environment stage: "${rawStage}". Supported stages: ${STAGES.join(", ")}`);
3048
3586
  }
3049
3587
  const projectDir = resolveProjectDir(options.projectDir);
3588
+ const runtimeInputs = new Set(
3589
+ STAGES.map((s) => canonicalPath(path.join(projectDir, `.env.${s}`)))
3590
+ );
3591
+ const assertSafeDestination = (candidate) => {
3592
+ if (runtimeInputs.has(canonicalPath(candidate))) {
3593
+ throw new ScriptError(
3594
+ `Resolved env export cannot overwrite a runtime .env.<stage> input: ${candidate}`
3595
+ );
3596
+ }
3597
+ };
3050
3598
  const stages = stage === void 0 ? STAGES : [stage];
3051
3599
  const snapshots = stages.map((stage2) => ({
3052
3600
  stage: stage2,
@@ -3064,7 +3612,7 @@ async function handleExportEnv(rawStage, options = {}) {
3064
3612
  const files = [];
3065
3613
  try {
3066
3614
  for (const snapshot of snapshots) {
3067
- let filename = path.join(projectDir, `.env.${snapshot.stage}`);
3615
+ let filename = path.join(projectDir, `.env.${snapshot.stage}.resolved`);
3068
3616
  while (true) {
3069
3617
  let overwrite = false;
3070
3618
  if (existsSync(filename)) {
@@ -3074,9 +3622,11 @@ async function handleExportEnv(rawStage, options = {}) {
3074
3622
  const name = (await ask(`New filename for ${snapshot.stage} (relative to the service directory): `)).trim();
3075
3623
  if (!name) continue;
3076
3624
  filename = path.resolve(projectDir, name);
3625
+ assertSafeDestination(filename);
3077
3626
  continue;
3078
3627
  }
3079
3628
  }
3629
+ assertSafeDestination(filename);
3080
3630
  mkdirSync(path.dirname(filename), { recursive: true });
3081
3631
  try {
3082
3632
  writeFileSync(filename, snapshot.content, { encoding: "utf-8", flag: overwrite ? "w" : "wx", mode: 384 });
@@ -3085,7 +3635,7 @@ async function handleExportEnv(rawStage, options = {}) {
3085
3635
  throw error;
3086
3636
  }
3087
3637
  files.push(filename);
3088
- console.log(pc22.green(`Exported ${snapshot.stage} application environment to ${filename}`));
3638
+ console.log(pc14.green(`Exported ${snapshot.stage} application environment to ${filename}`));
3089
3639
  break;
3090
3640
  }
3091
3641
  }
@@ -3161,10 +3711,10 @@ async function runCli(argv = process.argv) {
3161
3711
  (arg) => arg === "-h" || arg === "--help" || arg === "-V" || arg === "--version"
3162
3712
  );
3163
3713
  if (!isHelpOrVersion && argv.length > 2) {
3164
- console.log(pc22.dim(`builder v${version}`));
3714
+ console.log(pc14.dim(`builder v${version}`));
3165
3715
  }
3166
3716
  if (argv.length <= 2) {
3167
- console.log(pc22.dim(`builder v${version}
3717
+ console.log(pc14.dim(`builder v${version}
3168
3718
  `));
3169
3719
  cli.outputHelp();
3170
3720
  return;
@@ -3187,20 +3737,20 @@ async function runCli(argv = process.argv) {
3187
3737
  if (err instanceof ScriptError) {
3188
3738
  exitCode = err.exitCode;
3189
3739
  const formatted = err.message.startsWith("\u274C") ? err.message : `\u274C ${err.message}`;
3190
- console.error(pc22.red(`
3740
+ console.error(pc14.red(`
3191
3741
  ${formatted}
3192
3742
  `));
3193
3743
  if (isVerbose && err.stack) {
3194
- console.error(pc22.dim(err.stack));
3744
+ console.error(pc14.dim(err.stack));
3195
3745
  }
3196
3746
  } else {
3197
3747
  const message = errorMessage(err);
3198
3748
  const formatted = message.startsWith("\u274C") ? message : `\u274C Error: ${message}`;
3199
- console.error(pc22.red(`
3749
+ console.error(pc14.red(`
3200
3750
  ${formatted}
3201
3751
  `));
3202
3752
  if (isVerbose && err instanceof Error && err.stack) {
3203
- console.error(pc22.dim(err.stack));
3753
+ console.error(pc14.dim(err.stack));
3204
3754
  }
3205
3755
  }
3206
3756
  if (process.env.VITEST) {