@solid-stack/builder 2.0.2 → 2.0.3

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 (42) hide show
  1. package/dist/bin.js +381 -93
  2. package/dist/bin.js.map +1 -1
  3. package/dist/core/composition/compileServiceComposition.d.ts +2 -0
  4. package/dist/core/composition/compileServiceComposition.d.ts.map +1 -1
  5. package/dist/core/composition/composeBuildResources.d.ts +6 -0
  6. package/dist/core/composition/composeBuildResources.d.ts.map +1 -0
  7. package/dist/core/composition/composeDependsOn.d.ts +3 -0
  8. package/dist/core/composition/composeDependsOn.d.ts.map +1 -0
  9. package/dist/core/composition/composeEnvironment.d.ts +2 -2
  10. package/dist/core/composition/composeEnvironment.d.ts.map +1 -1
  11. package/dist/core/composition/composeHealthcheck.d.ts +3 -0
  12. package/dist/core/composition/composeHealthcheck.d.ts.map +1 -0
  13. package/dist/core/composition/composePaths.d.ts.map +1 -1
  14. package/dist/core/composition/generatedNames.d.ts +9 -0
  15. package/dist/core/composition/generatedNames.d.ts.map +1 -0
  16. package/dist/core/composition/namespaceDependencyCompose.d.ts +3 -0
  17. package/dist/core/composition/namespaceDependencyCompose.d.ts.map +1 -1
  18. package/dist/core/composition/types.d.ts +8 -3
  19. package/dist/core/composition/types.d.ts.map +1 -1
  20. package/dist/core/composition/validateComposeResourceReferences.d.ts +7 -0
  21. package/dist/core/composition/validateComposeResourceReferences.d.ts.map +1 -0
  22. package/dist/core/composition/validateDependencyCompose.d.ts.map +1 -1
  23. package/dist/core/composition/validateOverrideCompose.d.ts +3 -0
  24. package/dist/core/composition/validateOverrideCompose.d.ts.map +1 -1
  25. package/dist/core/config/pathSafety.d.ts.map +1 -1
  26. package/dist/core/mesh/checkers/checkMeshServices.d.ts.map +1 -1
  27. package/dist/core/mesh/runners/runMeshTestUnit.d.ts.map +1 -1
  28. package/dist/core/mesh/v2/compileMeshComposition.d.ts.map +1 -1
  29. package/dist/core/mesh/v2/compileMeshTester.d.ts +2 -1
  30. package/dist/core/mesh/v2/compileMeshTester.d.ts.map +1 -1
  31. package/dist/core/mesh/v2/validateMeshTestStage.d.ts +22 -0
  32. package/dist/core/mesh/v2/validateMeshTestStage.d.ts.map +1 -0
  33. package/dist/index.js +381 -93
  34. package/dist/index.js.map +1 -1
  35. package/dist/templates/policy/dockerfile/dockerfile.rego +6 -9
  36. package/dist/utils/assertUniqueHostPortMappings.d.ts.map +1 -1
  37. package/dist/utils/checkPortCollision.d.ts.map +1 -1
  38. package/dist/utils/composePublishedPort.d.ts +3 -0
  39. package/dist/utils/composePublishedPort.d.ts.map +1 -0
  40. package/package.json +1 -1
  41. package/schemas/mesh-schema.json +310 -20
  42. package/templates/policy/dockerfile/dockerfile.rego +6 -9
package/dist/index.js CHANGED
@@ -6,9 +6,9 @@ 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;
@@ -329,6 +333,34 @@ function checkYamlFiles(build, projectDir) {
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) {
@@ -642,14 +674,33 @@ function volumeShort(v, base, out) {
642
674
  if (mount?.type !== "bind" || !mount.source || /^(?:[\\/]|~|[a-z]:)/i.test(mount.source)) return v;
643
675
  return rewriteVolumeSource(v, rebase(mount.source, base, out));
644
676
  }
677
+ function isRemoteBuildContext(value) {
678
+ return /^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(value) || /^[^/@\s]+@[^:\s]+:.+/.test(value);
679
+ }
680
+ function rebaseAdditionalContext(value, base, out) {
681
+ if (value.startsWith("service:") || isRemoteBuildContext(value)) return value;
682
+ return rebase(value, base, out);
683
+ }
684
+ function rebaseAdditionalContexts(value, base, out) {
685
+ if (Array.isArray(value)) return value.map((entry) => {
686
+ if (typeof entry !== "string") return entry;
687
+ const separator = entry.indexOf("=");
688
+ if (separator < 0) return entry;
689
+ return `${entry.slice(0, separator)}=${rebaseAdditionalContext(entry.slice(separator + 1), base, out)}`;
690
+ });
691
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([name, context]) => [name, typeof context === "string" ? rebaseAdditionalContext(context, base, out) : context]));
692
+ return value;
693
+ }
645
694
  function rebaseComposePaths(document, composeFilePath, outputProjectDir) {
646
695
  const doc = structuredClone(document), base = path.dirname(composeFilePath), out = path.resolve(outputProjectDir);
647
696
  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") {
697
+ if (typeof svc.build === "string") {
698
+ if (!isRemoteBuildContext(svc.build)) svc.build = rebase(svc.build, base, out);
699
+ } else if (svc.build && typeof svc.build === "object") {
650
700
  const b = svc.build;
651
701
  const context = typeof b.context === "string" ? b.context : ".";
652
- b.context = rebase(context, base, out);
702
+ if (!isRemoteBuildContext(context)) b.context = rebase(context, base, out);
703
+ if (b.additional_contexts !== void 0) b.additional_contexts = rebaseAdditionalContexts(b.additional_contexts, base, out);
653
704
  }
654
705
  if (typeof svc.env_file === "string") svc.env_file = rebase(svc.env_file, base, out);
655
706
  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 +765,7 @@ function normalizeComposeEnvironment(value, context) {
714
765
  if (typeof item !== "string") throw new ConfigError({ configPath: context, value: item, reason: "Compose environment entries must be strings" });
715
766
  const at = item.indexOf("=");
716
767
  if (at < 0) {
717
- result[item] = process.env[item] ?? "";
768
+ result[item] = null;
718
769
  continue;
719
770
  }
720
771
  result[item.slice(0, at)] = item.slice(at + 1);
@@ -723,7 +774,10 @@ function normalizeComposeEnvironment(value, context) {
723
774
  }
724
775
  if (typeof value !== "object") throw new ConfigError({ configPath: context, value, reason: "Compose environment must be a map or list" });
725
776
  for (const [key, val] of Object.entries(value)) {
726
- if (val === null || val === void 0) continue;
777
+ if (val === null || val === void 0) {
778
+ result[key] = null;
779
+ continue;
780
+ }
727
781
  if (typeof val === "object") throw new ConfigError({ configPath: `${context}.${key}`, value: val, reason: "Compose environment value must be scalar" });
728
782
  result[key] = String(val);
729
783
  }
@@ -733,16 +787,66 @@ function mergeComposeEnvironment(service, overlay) {
733
787
  service.environment = { ...normalizeComposeEnvironment(service.environment, "service.environment"), ...overlay };
734
788
  }
735
789
 
790
+ // src/core/composition/composeBuildResources.ts
791
+ function buildObject(service) {
792
+ return service.build && typeof service.build === "object" && !Array.isArray(service.build) ? service.build : void 0;
793
+ }
794
+ function rewriteBuildSecretReferences(service, names) {
795
+ const build = buildObject(service);
796
+ if (!build || !Array.isArray(build.secrets)) return;
797
+ build.secrets = build.secrets.map((entry) => {
798
+ if (typeof entry === "string") return names.get(entry) ?? entry;
799
+ if (entry && typeof entry === "object" && typeof entry.source === "string") {
800
+ return { ...entry, source: names.get(entry.source) ?? entry.source };
801
+ }
802
+ return entry;
803
+ });
804
+ }
805
+ function collectBuildSecretReferences(service) {
806
+ const build = buildObject(service);
807
+ if (!build || !Array.isArray(build.secrets)) return [];
808
+ return build.secrets.flatMap((entry) => {
809
+ if (typeof entry === "string") return [entry];
810
+ return entry && typeof entry === "object" && typeof entry.source === "string" ? [entry.source] : [];
811
+ });
812
+ }
813
+ function assertNoServiceBuildContexts(service, configPath, sourceFile) {
814
+ const contexts = buildObject(service)?.additional_contexts;
815
+ const values = Array.isArray(contexts) ? contexts.map((entry) => typeof entry === "string" ? entry.slice(entry.indexOf("=") + 1) : entry) : contexts && typeof contexts === "object" ? Object.values(contexts) : [];
816
+ if (values.some((value) => typeof value === "string" && value.startsWith("service:"))) {
817
+ throw new ConfigError({
818
+ sourceFile,
819
+ configPath: `${configPath}.build.additional_contexts`,
820
+ reason: "Compose service-reference additional_contexts are unsupported"
821
+ });
822
+ }
823
+ }
824
+
736
825
  // src/core/composition/namespaceDependencyCompose.ts
737
826
  var entries = (obj) => obj && typeof obj === "object" && !Array.isArray(obj) ? Object.entries(obj) : [];
738
827
  function namespaceDependencyCompose(options) {
739
828
  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}`);
829
+ const originalServices = doc.services ?? {};
830
+ const usesImplicitDefault = Object.values(originalServices).some((service) => service.network_mode === void 0 && service.networks === void 0);
831
+ if (usesImplicitDefault && !Object.hasOwn(doc.networks ?? {}, "default")) doc.networks = { ...doc.networks ?? {}, default: {} };
832
+ const allocator = options.allocator ?? new GeneratedComposeNameAllocator();
833
+ const identityPrefix = options.identityPrefix ?? JSON.stringify(["dependency", options.dependencyKey, prefix]);
834
+ 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}`)]));
835
+ const serviceNameMap = make("service", Object.keys(doc.services ?? {}));
743
836
  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
837
  const rewriteKeys = (obj, map) => Object.fromEntries(entries(obj).map(([k, v]) => [map.get(k) ?? k, v]));
745
- const rewriteResourceRefs = (svc) => {
838
+ const addOriginalNetworkAliases = (name, svc) => {
839
+ if (svc.network_mode !== void 0 || svc.networks === void 0) return;
840
+ 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 } : {};
841
+ for (const [network, rawOptions] of Object.entries(attached)) {
842
+ const options2 = rawOptions && typeof rawOptions === "object" && !Array.isArray(rawOptions) ? rawOptions : {};
843
+ const aliases = Array.isArray(options2.aliases) ? options2.aliases.filter((alias) => typeof alias === "string") : [];
844
+ attached[network] = { ...options2, aliases: [.../* @__PURE__ */ new Set([...aliases, name])] };
845
+ }
846
+ svc.networks = attached;
847
+ };
848
+ const rewriteResourceRefs = (svc, originalName) => {
849
+ rewriteBuildSecretReferences(svc, secretNameMap);
746
850
  if (Array.isArray(svc.depends_on)) {
747
851
  svc.depends_on = svc.depends_on.map((v) => typeof v === "string" ? serviceNameMap.get(v) ?? v : v);
748
852
  } else if (svc.depends_on && typeof svc.depends_on === "object") svc.depends_on = rewriteKeys(svc.depends_on, serviceNameMap);
@@ -757,17 +861,14 @@ function namespaceDependencyCompose(options) {
757
861
  }
758
862
  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
863
  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 };
864
+ if (svc.networks === void 0 && svc.network_mode === void 0 && networkNameMap.has("default")) svc.networks = { default: null };
761
865
  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
866
  if (Array.isArray(svc.networks)) svc.networks = svc.networks.map((v) => typeof v === "string" ? networkNameMap.get(v) ?? v : v);
767
867
  else if (svc.networks && typeof svc.networks === "object") svc.networks = rewriteKeys(svc.networks, networkNameMap);
768
868
  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);
869
+ addOriginalNetworkAliases(originalName, svc);
769
870
  };
770
- for (const svc of Object.values(doc.services ?? {})) rewriteResourceRefs(svc);
871
+ for (const [name, svc] of Object.entries(originalServices)) rewriteResourceRefs(svc, name);
771
872
  doc.services = rewriteKeys(doc.services, serviceNameMap);
772
873
  if (doc.volumes) doc.volumes = rewriteKeys(doc.volumes, volumeNameMap);
773
874
  if (doc.networks) doc.networks = rewriteKeys(doc.networks, networkNameMap);
@@ -776,14 +877,81 @@ function namespaceDependencyCompose(options) {
776
877
  return { document: doc, serviceNameMap, volumeNameMap, networkNameMap, configNameMap, secretNameMap };
777
878
  }
778
879
 
880
+ // src/core/composition/validateComposeResourceReferences.ts
881
+ function validateComposeResourceReferences(document, context, onlyServices) {
882
+ const selected = onlyServices ? new Set(onlyServices) : void 0;
883
+ const fail = (configPath, kind, name) => {
884
+ throw new ConfigError({
885
+ sourceFile: context.sourceFile,
886
+ configPath,
887
+ ...context.stage ? { stage: context.stage } : {},
888
+ composition: context.composition,
889
+ referencedObject: name,
890
+ reason: `Compose ${kind} reference "${name}" has no top-level definition`
891
+ });
892
+ };
893
+ const exists = (kind, name) => {
894
+ const definitions = document[kind === "volume" ? "volumes" : kind === "network" ? "networks" : kind === "config" ? "configs" : "secrets"];
895
+ return Boolean(definitions && Object.hasOwn(definitions, name));
896
+ };
897
+ const check = (path20, kind, name) => {
898
+ if (kind === "network" && name === "default") return;
899
+ if (!exists(kind, name)) fail(path20, kind, name);
900
+ };
901
+ for (const [serviceName, service] of Object.entries(document.services ?? {})) {
902
+ if (selected && !selected.has(serviceName)) continue;
903
+ validateServiceResources(serviceName, service, check);
904
+ }
905
+ }
906
+ function validateServiceResources(serviceName, service, check) {
907
+ for (const mount of Array.isArray(service.volumes) ? service.volumes : []) {
908
+ const parsed = parseVolume(mount);
909
+ if (parsed?.type === "volume" && parsed.source) {
910
+ check(`services.${serviceName}.volumes`, "volume", parsed.source);
911
+ }
912
+ }
913
+ const networks = service.networks;
914
+ const networkNames = Array.isArray(networks) ? networks.filter((name) => typeof name === "string") : networks && typeof networks === "object" ? Object.keys(networks) : [];
915
+ for (const name of networkNames) {
916
+ check(`services.${serviceName}.networks`, "network", name);
917
+ }
918
+ for (const kind of ["configs", "secrets"]) {
919
+ const entries2 = service[kind];
920
+ if (!Array.isArray(entries2)) continue;
921
+ for (const entry of entries2) {
922
+ const name = typeof entry === "string" ? entry : entry && typeof entry === "object" && typeof entry.source === "string" ? entry.source : void 0;
923
+ if (name) check(`services.${serviceName}.${kind}`, kind === "configs" ? "config" : "secret", name);
924
+ }
925
+ }
926
+ for (const name of collectBuildSecretReferences(service)) {
927
+ check(`services.${serviceName}.build.secrets`, "secret", name);
928
+ }
929
+ }
930
+
931
+ // src/core/composition/composeHealthcheck.ts
932
+ function isEnabledValidComposeHealthcheck(value) {
933
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
934
+ const health = value;
935
+ if (health.disable === true) return false;
936
+ const test = health.test;
937
+ if (typeof test === "string") return test.trim().length > 0;
938
+ if (!Array.isArray(test) || !test.every((item) => typeof item === "string")) return false;
939
+ if (test[0] !== "CMD" && test[0] !== "CMD-SHELL") return false;
940
+ return test.length >= 2 && test.slice(1).some((item) => item.trim().length > 0);
941
+ }
942
+
779
943
  // src/core/composition/validateDependencyCompose.ts
780
944
  function validateDependencyCompose(dependencyKey, dependency, document, context) {
781
945
  const fail = (configPath, reason, value) => {
782
946
  throw new ConfigError({ sourceFile: context.composePath, configPath, stage: context.stage, composition: "service", ...value === void 0 ? {} : { value }, reason: `Dependency "${dependencyKey}": ${reason}` });
783
947
  };
784
948
  if (document.include !== void 0) fail("include", "Compose include is unsupported for atomic dependency implementations");
949
+ validateComposeResourceReferences(document, { sourceFile: context.composePath, stage: context.stage, composition: "service" });
785
950
  const services = document.services ?? {};
786
951
  for (const [name, svc] of Object.entries(services)) {
952
+ assertNoServiceBuildContexts(svc, `services.${name}`, context.composePath);
953
+ if (svc.profiles !== void 0) fail(`services.${name}.profiles`, "dependency Compose profiles are unsupported because a materialized dependency is atomic");
954
+ 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
955
  if (svc.ports !== void 0) fail(`services.${name}.ports`, "raw dependency ports are forbidden");
788
956
  if (svc.network_mode === "host") fail(`services.${name}.network_mode`, "host network mode is forbidden");
789
957
  if (svc.privileged === true) fail(`services.${name}.privileged`, `privileged services are forbidden`);
@@ -806,11 +974,6 @@ function validateDependencyCompose(dependencyKey, dependency, document, context)
806
974
  for (const ref of svc.volumes_from) if (typeof ref === "string") internalRefs.push(["volumes_from", ref.split(":")[0]]);
807
975
  }
808
976
  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
977
  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
978
  }
816
979
  if (!Object.keys(dependency.endpoints).length) return;
@@ -823,8 +986,7 @@ function validateDependencyCompose(dependencyKey, dependency, document, context)
823
986
  }
824
987
  for (const owner of owners) {
825
988
  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`);
989
+ if (!isEnabledValidComposeHealthcheck(services[owner].healthcheck)) fail(`services.${owner}.healthcheck`, "endpoint owner requires a valid enabled Compose healthcheck");
828
990
  }
829
991
  }
830
992
  function canonicalBuildContext(value, baseDir) {
@@ -837,10 +999,12 @@ function validateAndPrepareAppOverride(document, context) {
837
999
  const fail = (path20, reason, value) => {
838
1000
  throw new ConfigError({ sourceFile: context.file, configPath: path20, stage: context.stage, composition: "service", ...value === void 0 ? {} : { value }, reason });
839
1001
  };
1002
+ const allowedRootKeys = /* @__PURE__ */ new Set(["services", "volumes", "networks", "configs", "secrets"]);
1003
+ for (const key of Object.keys(document)) if (!key.startsWith("x-") && !allowedRootKeys.has(key)) fail(key, "unsupported override Compose top-level field");
840
1004
  const keys = Object.keys(document.services ?? {});
841
1005
  if (keys.length !== 1 || keys[0] !== "app") fail("services", "override must define exactly one service named app");
842
1006
  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");
1007
+ 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");
844
1008
  if (app.healthcheck && typeof app.healthcheck === "object") {
845
1009
  const health = app.healthcheck;
846
1010
  for (const key of Object.keys(health)) if (!["interval", "timeout", "retries", "start_period", "start_interval"].includes(key)) fail(`services.app.healthcheck.${key}`, "override may set only healthcheck timing fields");
@@ -850,8 +1014,8 @@ function validateAndPrepareAppOverride(document, context) {
850
1014
  }
851
1015
  if (app.build && typeof app.build === "object") {
852
1016
  const build = app.build;
853
- for (const key of ["target", "dockerfile"]) {
854
- if (build[key] !== void 0) {
1017
+ for (const key of Object.keys(build)) {
1018
+ if (!["args", "context"].includes(key)) {
855
1019
  fail(`services.app.build.${key}`, "override cannot change Builder-owned build configuration");
856
1020
  }
857
1021
  }
@@ -867,6 +1031,7 @@ function validateAndPrepareAppOverride(document, context) {
867
1031
  const env = normalizeComposeEnvironment(app.environment, "services.app.environment");
868
1032
  for (const k of ["EXEC_MODE", "INFRA_MODE"]) if (k in env) fail(`services.app.environment.${k}`, "override cannot set Builder-owned environment");
869
1033
  app.environment = env;
1034
+ const allocator = context.allocator ?? new GeneratedComposeNameAllocator();
870
1035
  const resourceKeys = ["volumes", "networks", "configs", "secrets"];
871
1036
  const resources = {};
872
1037
  for (const kind of resourceKeys) {
@@ -882,7 +1047,8 @@ function validateAndPrepareAppOverride(document, context) {
882
1047
  const names = /* @__PURE__ */ new Map(), mapped = {};
883
1048
  for (const [name, definition] of Object.entries(defs)) {
884
1049
  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}`;
1050
+ const prefix = context.resourceNamespace && context.resourceNamespace !== "app" ? `svc--${context.resourceNamespace}--app-override` : "app-override";
1051
+ const target = allocator.allocate(JSON.stringify(["service", context.resourceNamespace ?? "app", "override", context.stage, kind, name]), `${prefix}--${context.stage}--${kind.slice(0, -1)}--${name}`);
886
1052
  names.set(name, target);
887
1053
  mapped[target] = definition;
888
1054
  }
@@ -1004,13 +1170,14 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1004
1170
  const seed = getTemplateSeed(stage, Boolean(options.meshMode));
1005
1171
  const rawName = options.projectNameOverride ?? raw.name ?? path.basename(root);
1006
1172
  const projectName = deriveProjectName(rawName, stage);
1173
+ const nameAllocator = options.nameAllocator ?? new GeneratedComposeNameAllocator(["app", "tester", "default", options.appServiceName ?? "app"]);
1007
1174
  const namespaced = {};
1008
1175
  for (const [key, dep] of Object.entries(effective.dependencies).sort(([a], [b]) => a.localeCompare(b))) {
1009
1176
  const sourcePath = resolveInsideProject(root, dep.compose, { sourceFile: buildPath, configPath: `dependencies.${key}.compose`, stage });
1010
1177
  const document = rebaseComposePaths(loadComposeDocument(sourcePath, { sourceFile: buildPath, configPath: `dependencies.${key}.compose`, stage, composition: "service" }), sourcePath, options.composeOutputDir ?? root);
1011
1178
  validateDependencyCompose(key, dep, document, { composePath: sourcePath, stage });
1012
1179
  if (Object.keys(dep.endpoints).length) {
1013
- const ns = namespaceDependencyCompose({ namespacePrefix: options.namespacePrefix ? `${options.namespacePrefix}${key}` : `dep--${key}`, document });
1180
+ 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
1181
  namespaced[key] = { doc: ns.document, map: ns.serviceNameMap, source: sourcePath };
1015
1182
  }
1016
1183
  }
@@ -1025,7 +1192,7 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1025
1192
  const endpointOwnerMap = /* @__PURE__ */ new Map();
1026
1193
  for (const [epName, ep] of Object.entries(dep.endpoints)) endpointOwnerMap.set(epName, entry.map.get(ep.service));
1027
1194
  const endpointOwners = new Set(endpointOwnerMap.values());
1028
- materialized[key] = { key, composePath: entry.source, compose: item, serviceNameMap: entry.map, endpointOwnerMap, endpoints: {}, endpointOwners };
1195
+ materialized[key] = { key, composePath: entry.source, compose: item, serviceNameMap: entry.map, endpointOwnerMap, endpoints: {}, endpointOwners, serviceNames: new Set(Object.keys(item.services)) };
1029
1196
  }
1030
1197
  const appEndpoints = buildStandaloneAppEndpoints(effective, stage, options.appServiceName ?? "app");
1031
1198
  const depEndpoints = {};
@@ -1074,8 +1241,9 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1074
1241
  const depEnv = options.deferReferenceResolution ? dep.env : resolveEnv(dep.env, registry, `dependencies.${key}.env`);
1075
1242
  for (const svc of Object.values(materialized[key]?.compose.services ?? {})) mergeComposeEnvironment(svc, depEnv);
1076
1243
  }
1077
- const appEnv = options.deferReferenceResolution ? ownEnv(effective, stage) : resolveEnv(ownEnv(effective, stage), registry, "app.env");
1078
- let buildAppEnvironment = { ...appEnv };
1244
+ const buildJsonAppEnvironment = ownEnv(effective, stage);
1245
+ const appEnv = options.deferReferenceResolution ? buildJsonAppEnvironment : resolveEnv(buildJsonAppEnvironment, registry, "app.env");
1246
+ let overrideComposeAppEnvironment = {};
1079
1247
  const runtimeDotenv = path.join(root, `.env.${profile.runtimeStage}`);
1080
1248
  if (fs.existsSync(runtimeDotenv)) {
1081
1249
  const text = fs.readFileSync(runtimeDotenv, "utf8");
@@ -1130,13 +1298,15 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1130
1298
  file: overridePath,
1131
1299
  stage,
1132
1300
  expectedBuildContext: String(appBuild.context),
1133
- buildContextBaseDir: outputDir
1301
+ buildContextBaseDir: outputDir,
1302
+ allocator: nameAllocator,
1303
+ resourceNamespace: options.meshMode ? options.appServiceName ?? "app" : "app"
1134
1304
  });
1135
1305
  for (const section of ["volumes", "networks", "configs", "secrets"]) if (prepared.resources[section]) mergeDocument(compose, { services: {}, [section]: prepared.resources[section] }, "app override");
1136
1306
  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");
1307
+ const overrideEnv = rawOverrideEnv;
1138
1308
  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 };
1309
+ overrideComposeAppEnvironment = { ...overrideEnv };
1140
1310
  const merged = { ...app, ...prepared.app };
1141
1311
  merged.environment = { ...appEnv, ...overrideEnv, ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
1142
1312
  const overrideBuild = prepared.app.build && typeof prepared.app.build === "object" ? prepared.app.build : {};
@@ -1159,8 +1329,8 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1159
1329
  const testerEnv = options.deferReferenceResolution ? testerEnvRaw : resolveEnv(testerEnvRaw, registry, "tester.env");
1160
1330
  compose.services.tester = { build: { context: ".", ...raw.dockerfile ? { dockerfile: raw.dockerfile } : {}, target: "test-e2e" }, network_mode: "host", environment: testerEnv, depends_on: { app: { condition: "service_healthy" } } };
1161
1331
  }
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])) };
1332
+ nameAllocator.assertUnique();
1333
+ return { compose, effectiveBuild: effective, endpoints: { app: appEndpoints, dependencies: depEndpoints }, projectName, ...profile.attachTester && !options.meshMode ? { testerServiceName: "tester" } : {}, buildJsonAppEnvironment, overrideComposeAppEnvironment, builderInternalEnvironment: { ...internal }, externalAppEnvironment: { ...options.externalAppEnv ?? {} }, dependencyServiceNames: Object.fromEntries(Object.entries(materialized).map(([key, dep]) => [key, [...dep.serviceNames]])), dependencyEnvironments: Object.fromEntries(Object.entries(effective.dependencies).map(([key, dep]) => [key, dep.env])) };
1164
1334
  }
1165
1335
 
1166
1336
  // src/core/checkers/checkEffectiveServiceStages.ts
@@ -1446,18 +1616,29 @@ function applyMeshLifecycleEdges(services, edges) {
1446
1616
  }
1447
1617
  }
1448
1618
 
1619
+ // src/core/composition/composeDependsOn.ts
1620
+ function normalizeComposeDependsOn(value) {
1621
+ if (Array.isArray(value)) {
1622
+ return Object.fromEntries(value.filter((item) => typeof item === "string").map((name) => [name, {}]));
1623
+ }
1624
+ return value && typeof value === "object" ? { ...value } : {};
1625
+ }
1626
+
1449
1627
  // src/core/mesh/v2/compileMeshTester.ts
1450
1628
  function refs(svc) {
1451
- const out = [];
1629
+ const out = /* @__PURE__ */ new Set();
1452
1630
  const add = (v) => {
1453
- if (typeof v === "string") out.push(v);
1631
+ if (typeof v === "string" && v) out.add(v);
1454
1632
  };
1455
1633
  if (Array.isArray(svc.depends_on)) svc.depends_on.forEach(add);
1456
1634
  else if (svc.depends_on && typeof svc.depends_on === "object") Object.keys(svc.depends_on).forEach(add);
1457
1635
  if (Array.isArray(svc.links)) svc.links.forEach((v) => add(typeof v === "string" ? v.split(":")[0] : v));
1458
1636
  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;
1637
+ for (const property of ["network_mode", "ipc", "pid"]) {
1638
+ const value = svc[property];
1639
+ if (typeof value === "string" && value.startsWith("service:")) add(value.slice("service:".length));
1640
+ }
1641
+ return [...out];
1461
1642
  }
1462
1643
  function referencedResources(svc, doc) {
1463
1644
  const sets = { volumes: /* @__PURE__ */ new Set(), networks: /* @__PURE__ */ new Set(), configs: /* @__PURE__ */ new Set(), secrets: /* @__PURE__ */ new Set() };
@@ -1481,20 +1662,25 @@ function referencedResources(svc, doc) {
1481
1662
  if (typeof n === "string" && doc[kind]?.[n]) sets[kind].add(n);
1482
1663
  }
1483
1664
  }
1665
+ for (const name of collectBuildSecretReferences(svc)) if (doc.secrets && name in doc.secrets) sets.secrets.add(name);
1484
1666
  return sets;
1485
1667
  }
1486
- function compileMeshTester(meshDir, tester, endpointRegistry, effectiveTopLevelApps, stage, referenceContext) {
1668
+ function compileMeshTester(meshDir, tester, endpointRegistry, effectiveTopLevelApps, stage, referenceContext, nameAllocator = new GeneratedComposeNameAllocator(effectiveTopLevelApps)) {
1487
1669
  const meshPath = `${meshDir}/mesh.json`, file = resolveInsideProject(meshDir, tester.compose, { sourceFile: meshPath, configPath: "tester.compose", stage }), raw = rebaseComposePaths(loadComposeDocument(file, { sourceFile: meshPath, configPath: "tester.compose", stage, composition: "mesh" }), file, meshDir);
1488
1670
  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
1671
  const included = /* @__PURE__ */ new Set(), visit = (name) => {
1490
1672
  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" });
1673
+ const service = raw.services[name];
1674
+ if (!service) throw new ConfigError({ sourceFile: file, configPath: `services.${name}`, stage, composition: "mesh", reason: "Tester service dependency does not exist" });
1675
+ if (service.extends !== void 0) throw new ConfigError({ sourceFile: file, configPath: `services.${name}.extends`, stage, composition: "mesh", reason: "Tester Compose extends is unsupported until effective Compose inheritance can be validated before host-network rewriting" });
1492
1676
  included.add(name);
1493
- for (const ref of refs(raw.services[name])) visit(ref);
1677
+ for (const ref of refs(service)) visit(ref);
1494
1678
  };
1495
1679
  visit(tester.service);
1680
+ validateComposeResourceReferences(raw, { sourceFile: file, stage, composition: "mesh" }, included);
1496
1681
  for (const name of included) {
1497
1682
  const svc = raw.services[name];
1683
+ assertNoServiceBuildContexts(svc, `services.${name}`, file);
1498
1684
  if (name !== tester.service && svc.network_mode === "host") throw new ConfigError({ sourceFile: file, configPath: `services.${name}.network_mode`, stage, composition: "mesh", reason: "Only the selected tester runner may use host networking" });
1499
1685
  if (name === tester.service && svc.network_mode !== void 0 && svc.network_mode !== "host") throw new ConfigError({ sourceFile: file, configPath: `services.${name}.network_mode`, stage, composition: "mesh", reason: "Selected tester runner must be compatible with host networking" });
1500
1686
  if (name === tester.service && svc.networks !== void 0) throw new ConfigError({ sourceFile: file, configPath: `services.${name}.networks`, stage, composition: "mesh", reason: "Selected host-network tester runner cannot declare networks" });
@@ -1506,7 +1692,7 @@ function compileMeshTester(meshDir, tester, endpointRegistry, effectiveTopLevelA
1506
1692
  }
1507
1693
  const selected = { services: Object.fromEntries([...included].map((k) => [k, raw.services[k]])) };
1508
1694
  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 });
1695
+ const ns = namespaceDependencyCompose({ dependencyKey: "mesh-tester", namespacePrefix: "mesh-tester", document: selected, allocator: nameAllocator, identityPrefix: JSON.stringify(["mesh-tester"]) });
1510
1696
  const runner = ns.serviceNameMap.get(tester.service);
1511
1697
  const runnerSvc = ns.document.services[runner];
1512
1698
  if (runnerSvc.ports !== void 0) throw new ConfigError({ sourceFile: file, configPath: `services.${tester.service}.ports`, stage, composition: "mesh", reason: "Selected host-network tester runner cannot define ports" });
@@ -1516,25 +1702,52 @@ function compileMeshTester(meshDir, tester, endpointRegistry, effectiveTopLevelA
1516
1702
  const env = tester.env ?? {};
1517
1703
  assertMeshTesterEnvPublic(env, "tester.env");
1518
1704
  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 : {};
1705
+ const depends = normalizeComposeDependsOn(runnerSvc.depends_on);
1520
1706
  for (const app of effectiveTopLevelApps) depends[app] = { condition: "service_healthy" };
1521
1707
  runnerSvc.depends_on = depends;
1522
1708
  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
1709
  }
1710
+ function validPort(value) {
1711
+ if (!/^\d+$/.test(value)) return void 0;
1712
+ const port = Number(value);
1713
+ return Number.isInteger(port) && port >= 1 && port <= 65535 ? port : void 0;
1714
+ }
1715
+ function parsePublishedHostPort(value) {
1716
+ if (value && typeof value === "object") {
1717
+ const published = value.published;
1718
+ if (typeof published === "number" && Number.isInteger(published)) {
1719
+ return published >= 1 && published <= 65535 ? published : void 0;
1720
+ }
1721
+ if (typeof published === "string") return validPort(published);
1722
+ return void 0;
1723
+ }
1724
+ if (typeof value !== "string") return void 0;
1725
+ const mapping = value.replace(/\/(?:tcp|udp|sctp)$/i, "");
1726
+ if (/^\d+(?:-\d+)?$/.test(mapping)) return void 0;
1727
+ if (mapping.startsWith("[")) {
1728
+ const close = mapping.indexOf("]");
1729
+ if (close < 0 || isIP(mapping.slice(1, close)) !== 6) return void 0;
1730
+ const suffix = mapping.slice(close + 1);
1731
+ const match = suffix.match(/^:(\d+)(?:-\d+)?:\d+(?:-\d+)?$/);
1732
+ return match ? validPort(match[1]) : void 0;
1733
+ }
1734
+ const parts = mapping.split(":");
1735
+ if (parts.length === 2) return validPort(parts[0]);
1736
+ if (parts.length >= 3) {
1737
+ const hostIp = parts.slice(0, -2).join(":");
1738
+ if (isIP(hostIp) === 4) return validPort(parts[parts.length - 2]);
1739
+ }
1740
+ return void 0;
1741
+ }
1742
+
1743
+ // src/utils/assertUniqueHostPortMappings.ts
1524
1744
  function assertUniqueHostPortMappings(yamlConfig) {
1525
1745
  const parsed = parse(yamlConfig);
1526
1746
  const owners = /* @__PURE__ */ new Map();
1527
1747
  for (const [serviceName, service] of Object.entries(parsed?.services ?? {})) {
1528
1748
  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;
1749
+ const hostPort = parsePublishedHostPort(port);
1750
+ if (hostPort === void 0) continue;
1538
1751
  const existing = owners.get(hostPort);
1539
1752
  if (existing) {
1540
1753
  throw new ScriptError(
@@ -1563,6 +1776,26 @@ function appendPort(service, target, published) {
1563
1776
  ports.push({ target, published, host_ip: PUBLIC_HOST, protocol: "tcp" });
1564
1777
  service.ports = ports;
1565
1778
  }
1779
+ function buildMeshPortIntents(services, publication) {
1780
+ const intents = [];
1781
+ for (const name of Object.keys(services).sort((a, b) => a.localeCompare(b))) {
1782
+ const service = services[name];
1783
+ const appPublications = publication.filter((pub) => pub.ownerMeshService === name && pub.target === "app").sort((a, b) => a.endpoint.localeCompare(b.endpoint));
1784
+ for (const pub of appPublications) {
1785
+ const endpoint = service.effectiveBuild.app.endpoints[pub.endpoint];
1786
+ intents.push({ logicalPath: pub.logicalPath, requested: endpoint.publicPort });
1787
+ }
1788
+ const dependencyNames = [...new Set(publication.filter((pub) => pub.ownerMeshService === name && pub.target === "dependency").map((pub) => pub.dependency))].sort((a, b) => a.localeCompare(b));
1789
+ for (const dependency of dependencyNames) {
1790
+ const dependencyPublications = publication.filter((pub) => pub.ownerMeshService === name && pub.target === "dependency" && pub.dependency === dependency).sort((a, b) => a.endpoint.localeCompare(b.endpoint));
1791
+ for (const pub of dependencyPublications) {
1792
+ const endpoint = service.effectiveBuild.dependencies[dependency].endpoints[pub.endpoint];
1793
+ intents.push({ logicalPath: pub.logicalPath, requested: endpoint.publicPort });
1794
+ }
1795
+ }
1796
+ }
1797
+ return intents;
1798
+ }
1566
1799
  function ownerFor(pub, fragment) {
1567
1800
  return pub.target === "app" ? pub.ownerMeshService : fragment.endpoints.dependencies[pub.dependency]?.[pub.endpoint]?.networkHost ?? "";
1568
1801
  }
@@ -1570,15 +1803,20 @@ function setEnv(service, env) {
1570
1803
  const current = service.environment && typeof service.environment === "object" && !Array.isArray(service.environment) ? service.environment : {};
1571
1804
  service.environment = { ...current, ...env };
1572
1805
  }
1806
+ function attachNetworkIfCompatible(service, networkName) {
1807
+ if (service.network_mode !== void 0) return;
1808
+ service.networks = { ...normalizeNetworks(service.networks), [networkName]: null };
1809
+ }
1573
1810
  function compileMeshComposition(stage, meshDir, options = {}) {
1574
1811
  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
1812
  const rawName = raw.name ?? path.basename(meshDir), projectName = deriveProjectName(rawName, stage, meshDir);
1813
+ const nameAllocator = new GeneratedComposeNameAllocator(["mesh", "default", ...Object.keys(services), ...Object.keys(services).map((name) => `mesh--${name}`)]);
1576
1814
  const fragments = {};
1577
1815
  const compose = { name: projectName, services: {}, networks: { mesh: { driver: "bridge" } } };
1578
1816
  for (const [name, svc] of Object.entries(services).sort(([a], [b]) => a.localeCompare(b))) {
1579
1817
  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
1818
  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 });
1819
+ 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
1820
  fragments[name] = fragment;
1583
1821
  mergeFragment(compose, fragment.compose, name);
1584
1822
  const app = compose.services[name];
@@ -1592,32 +1830,17 @@ function compileMeshComposition(stage, meshDir, options = {}) {
1592
1830
  for (const ep of Object.values(fragment.endpoints.dependencies[dep] ?? {})) {
1593
1831
  const owner = ep.networkHost;
1594
1832
  const ownerService = compose.services[owner];
1595
- if (ownerService) {
1596
- const old = normalizeNetworks(ownerService.networks);
1597
- old[privateName] = null;
1598
- ownerService.networks = old;
1599
- }
1833
+ if (ownerService) attachNetworkIfCompatible(ownerService, privateName);
1600
1834
  }
1601
- for (const generated of Object.keys(fragment.compose.services).filter((k) => k.startsWith(`svc--${name}--dep--${dep}--`))) {
1835
+ for (const generated of fragment.dependencyServiceNames?.[dep] ?? []) {
1602
1836
  const ownerService = compose.services[generated];
1603
- const old = normalizeNetworks(ownerService.networks);
1604
- old[privateName] = null;
1605
- ownerService.networks = old;
1837
+ attachNetworkIfCompatible(ownerService, privateName);
1606
1838
  }
1607
1839
  }
1608
1840
  }
1609
1841
  app.networks = { ...normalizeNetworks(app.networks), ...networks };
1610
1842
  }
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));
1843
+ const publication = resolveMeshPublication(services, bindingMap, stage, meshPath), intents = buildMeshPortIntents(services, publication), ports = allocateHostPorts(meshDir, stage, intents, Boolean(options.validationMode));
1621
1844
  const endpoints = { app: {}, dependencies: {} };
1622
1845
  for (const [name, svc] of Object.entries(services)) {
1623
1846
  endpoints.app[name] = {};
@@ -1654,15 +1877,17 @@ function compileMeshComposition(stage, meshDir, options = {}) {
1654
1877
  const refContext = { services, bindings: bindingMap, endpoints, stage, meshJsonPath: meshPath };
1655
1878
  for (const [name, fragment] of Object.entries(fragments)) {
1656
1879
  const app = compose.services[name];
1657
- const buildEnv = resolveServiceBuildEnvThroughMesh(name, fragment.buildAppEnvironment ?? fragment.builderAppEnvironment ?? {}, refContext, `services.${name}.app.env`);
1880
+ const buildEnv = resolveServiceBuildEnvThroughMesh(name, fragment.buildJsonAppEnvironment ?? {}, refContext, `services.${name}.app.env`);
1658
1881
  const meshEnv = resolveMeshEnvMap(fragment.externalAppEnvironment ?? {}, refContext, `services.${name}.env`);
1659
- setEnv(app, { ...buildEnv, ...meshEnv });
1882
+ app.environment = { ...buildEnv, ...fragment.overrideComposeAppEnvironment ?? {}, ...meshEnv, ...fragment.builderInternalEnvironment ?? {} };
1660
1883
  for (const [depName, depEnv] of Object.entries(fragment.dependencyEnvironments ?? {})) {
1661
1884
  const logicalBinding = bindingMap.get(bindingKey(name, depName));
1662
1885
  if (logicalBinding) continue;
1663
1886
  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);
1887
+ for (const serviceName of fragment.dependencyServiceNames?.[depName] ?? []) {
1888
+ const service = compose.services[serviceName];
1889
+ if (service) setEnv(service, resolvedDep);
1890
+ }
1666
1891
  }
1667
1892
  }
1668
1893
  const edges = buildMeshLifecycleEdges(services, bindingMap, stage, meshPath);
@@ -1697,18 +1922,85 @@ function compileMeshComposition(stage, meshDir, options = {}) {
1697
1922
  let testerServiceName;
1698
1923
  if (stage === "e2e") {
1699
1924
  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;
1925
+ const built = raw.tester ? compileMeshTester(meshDir, raw.tester, endpoints, Object.keys(services).sort(), "e2e", refContext, nameAllocator) : void 0;
1701
1926
  if (built) {
1702
1927
  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
1928
  mergeFragment(compose, fragment, "mesh tester");
1704
1929
  testerServiceName = built.runnerServiceName;
1705
1930
  }
1706
1931
  }
1932
+ nameAllocator.assertUnique();
1707
1933
  const yaml = stringify(compose);
1708
1934
  assertUniqueHostPortMappings(yaml);
1709
1935
  return { compose, effectiveMesh: effective, loadedServices: services, endpoints, projectName, ...testerServiceName ? { testerServiceName } : {} };
1710
1936
  }
1711
1937
 
1938
+ // src/core/mesh/v2/validateMeshTestStage.ts
1939
+ function validateMeshTestStage(services, meshDir, meshPath, validationMode = false) {
1940
+ const bindings = bindingsMap(buildDependencyBindings(services, "test", meshPath));
1941
+ const publication = resolveMeshPublication(
1942
+ services,
1943
+ bindings,
1944
+ "test",
1945
+ meshPath
1946
+ );
1947
+ for (const pub of publication) {
1948
+ if (pub.target === "dependency") {
1949
+ throw new ConfigError({
1950
+ sourceFile: meshPath,
1951
+ configPath: `services.${pub.ownerMeshService}.publish`,
1952
+ stage: "test",
1953
+ composition: "mesh",
1954
+ value: pub.logicalPath,
1955
+ reason: "mesh.test is isolated; dependency endpoints are not materialized and cannot be published"
1956
+ });
1957
+ }
1958
+ }
1959
+ const appPublications = publication.filter((pub) => pub.target === "app").sort(
1960
+ (a, b) => a.ownerMeshService.localeCompare(b.ownerMeshService) || a.endpoint.localeCompare(b.endpoint)
1961
+ ).map((pub) => {
1962
+ const endpoint = services[pub.ownerMeshService].effectiveBuild.app.endpoints[pub.endpoint];
1963
+ return {
1964
+ meshService: pub.ownerMeshService,
1965
+ endpoint: pub.endpoint,
1966
+ logicalPath: pub.logicalPath,
1967
+ containerPort: endpoint.port,
1968
+ requested: endpoint.publicPort
1969
+ };
1970
+ });
1971
+ const intents = appPublications.map((pub) => ({
1972
+ logicalPath: pub.logicalPath,
1973
+ requested: pub.requested
1974
+ }));
1975
+ const allocatedPorts = allocateHostPorts(
1976
+ meshDir,
1977
+ "test",
1978
+ intents,
1979
+ validationMode
1980
+ );
1981
+ return { bindings, appPublications, allocatedPorts };
1982
+ }
1983
+ function applyTestAppPublications(validated, meshService, app, endpointRegistry) {
1984
+ for (const publication of validated.appPublications) {
1985
+ if (publication.meshService !== meshService) continue;
1986
+ const published = validated.allocatedPorts.get(publication.logicalPath);
1987
+ const ports = Array.isArray(app.ports) ? app.ports : [];
1988
+ ports.push({
1989
+ target: publication.containerPort,
1990
+ published,
1991
+ host_ip: PUBLIC_HOST,
1992
+ protocol: "tcp"
1993
+ });
1994
+ app.ports = ports;
1995
+ const endpoint = endpointRegistry[publication.endpoint];
1996
+ if (endpoint) {
1997
+ endpoint.publicHost = PUBLIC_HOST;
1998
+ endpoint.publicPort = published;
1999
+ endpoint.effectivelyPublished = true;
2000
+ }
2001
+ }
2002
+ }
2003
+
1712
2004
  // src/core/mesh/checkers/checkMeshServices.ts
1713
2005
  function checkMeshServices(mesh, meshDir) {
1714
2006
  const root = resolveProjectDir(meshDir), meshPath = path.join(root, "mesh.json");
@@ -1716,6 +2008,7 @@ function checkMeshServices(mesh, meshDir) {
1716
2008
  for (const stage of ["dev", "prod", "test", "e2e"]) {
1717
2009
  const effective = resolveMeshStage(mesh, stage, meshPath);
1718
2010
  const services = loadEffectiveMeshServices(root, effective, stage);
2011
+ if (stage === "test") validateMeshTestStage(services, root, meshPath, true);
1719
2012
  for (const [name, svc] of Object.entries(services)) {
1720
2013
  if (!checked.has(svc.absolutePath)) {
1721
2014
  console.log(pc22.cyan(`
@@ -1730,7 +2023,7 @@ function checkMeshServices(mesh, meshDir) {
1730
2023
  for (const key of ["EXEC_MODE", "INFRA_MODE", ...Object.values(svc.effectiveBuild.app.endpoints).some((ep) => ep.primary) ? ["PORT"] : []]) {
1731
2024
  if (key in svc.meshEnv) throw new ConfigError({ sourceFile: meshPath, configPath: `services.${name}.env.${key}`, stage: "test", composition: "mesh", reason: "Mesh service env cannot set Builder-owned environment" });
1732
2025
  }
1733
- resolveServiceBuildEnvThroughMesh(name, fragment.builderAppEnvironment ?? {}, ctx, `services.${name}.app.env`);
2026
+ resolveServiceBuildEnvThroughMesh(name, fragment.buildJsonAppEnvironment ?? {}, ctx, `services.${name}.app.env`);
1734
2027
  for (const [depName, depEnv] of Object.entries(fragment.dependencyEnvironments ?? {})) resolveServiceBuildEnvThroughMesh(name, depEnv, ctx, `services.${name}.dependencies.${depName}.env`);
1735
2028
  resolveMeshEnvMap(svc.meshEnv, ctx, `services.${name}.env`);
1736
2029
  }
@@ -2199,15 +2492,9 @@ function extractHostPorts(yamlConfig) {
2199
2492
  if (parsed?.services && typeof parsed.services === "object") {
2200
2493
  for (const svc of Object.values(parsed.services)) {
2201
2494
  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
- }
2495
+ for (const mapping of svc.ports) {
2496
+ const hostPort = parsePublishedHostPort(mapping);
2497
+ if (hostPort !== void 0) ports.push(hostPort);
2211
2498
  }
2212
2499
  }
2213
2500
  }
@@ -2381,7 +2668,7 @@ async function runMeshProd(options = {}) {
2381
2668
  return status;
2382
2669
  }
2383
2670
  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");
2671
+ const meshDir = resolveProjectDir(options.projectDir), meshPath = path.join(meshDir, "mesh.json"), raw = getMeshJson(meshDir), effective = resolveMeshStage(raw, "test", meshPath), services = loadEffectiveMeshServices(meshDir, effective, "test"), validated = validateMeshTestStage(services, meshDir, meshPath, Boolean(options.dryRun));
2385
2672
  console.log(pc22.bold(pc22.blue("\n[1/2] MESH SERVICE UNIT/ISOLATED TESTS\n")));
2386
2673
  for (const [name, svc] of Object.entries(services).sort(([a], [b]) => a.localeCompare(b))) {
2387
2674
  console.log(pc22.cyan(`-> Running isolated unit tests for [${name}]`));
@@ -2390,11 +2677,12 @@ async function runMeshTestUnit(options = {}) {
2390
2677
  const refCtx = { services: { [name]: svc }, bindings: /* @__PURE__ */ new Map(), endpoints, stage: "test", meshJsonPath: meshPath };
2391
2678
  const env = svc.meshEnv;
2392
2679
  for (const key of ["EXEC_MODE", "INFRA_MODE", ...Object.keys(svc.effectiveBuild.app.endpoints).some((k) => svc.effectiveBuild.app.endpoints[k]?.primary) ? ["PORT"] : []]) if (key in env) throw new ConfigError({ sourceFile: meshPath, configPath: `services.${name}.env.${key}`, stage: "test", composition: "mesh", reason: "Mesh service env cannot set Builder-owned environment" });
2393
- const resolvedBuild = resolveServiceBuildEnvThroughMesh(name, compiled.builderAppEnvironment ?? {}, refCtx, `services.${name}.app.env`);
2680
+ const resolvedBuild = resolveServiceBuildEnvThroughMesh(name, compiled.buildJsonAppEnvironment ?? {}, refCtx, `services.${name}.app.env`);
2394
2681
  for (const [depName, depEnv] of Object.entries(compiled.dependencyEnvironments ?? {})) resolveServiceBuildEnvThroughMesh(name, depEnv, refCtx, `services.${name}.dependencies.${depName}.env`);
2395
2682
  const resolved = resolveMeshEnvMap(env, refCtx, `services.${name}.env`);
2396
2683
  const app = compiled.compose.services.app;
2397
- app.environment = { ...app.environment, ...resolvedBuild, ...resolved };
2684
+ app.environment = { ...resolvedBuild, ...compiled.overrideComposeAppEnvironment ?? {}, ...resolved, ...compiled.builderInternalEnvironment ?? {} };
2685
+ applyTestAppPublications(validated, name, app, compiled.endpoints.app);
2398
2686
  const projectName = `${deriveProjectName(raw.name ?? path.basename(meshDir), "dev")}-${name}-test`;
2399
2687
  compiled.compose.name = projectName;
2400
2688
  const yaml = stringify(compiled.compose);