@solid-stack/builder 2.0.1 → 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 (43) hide show
  1. package/dist/bin.js +467 -100
  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 +2 -0
  14. package/dist/core/composition/composePaths.d.ts.map +1 -1
  15. package/dist/core/composition/generatedNames.d.ts +9 -0
  16. package/dist/core/composition/generatedNames.d.ts.map +1 -0
  17. package/dist/core/composition/namespaceDependencyCompose.d.ts +3 -0
  18. package/dist/core/composition/namespaceDependencyCompose.d.ts.map +1 -1
  19. package/dist/core/composition/types.d.ts +8 -3
  20. package/dist/core/composition/types.d.ts.map +1 -1
  21. package/dist/core/composition/validateComposeResourceReferences.d.ts +7 -0
  22. package/dist/core/composition/validateComposeResourceReferences.d.ts.map +1 -0
  23. package/dist/core/composition/validateDependencyCompose.d.ts.map +1 -1
  24. package/dist/core/composition/validateOverrideCompose.d.ts +10 -3
  25. package/dist/core/composition/validateOverrideCompose.d.ts.map +1 -1
  26. package/dist/core/config/pathSafety.d.ts.map +1 -1
  27. package/dist/core/mesh/checkers/checkMeshServices.d.ts.map +1 -1
  28. package/dist/core/mesh/runners/runMeshTestUnit.d.ts.map +1 -1
  29. package/dist/core/mesh/v2/compileMeshComposition.d.ts.map +1 -1
  30. package/dist/core/mesh/v2/compileMeshTester.d.ts +2 -1
  31. package/dist/core/mesh/v2/compileMeshTester.d.ts.map +1 -1
  32. package/dist/core/mesh/v2/validateMeshTestStage.d.ts +22 -0
  33. package/dist/core/mesh/v2/validateMeshTestStage.d.ts.map +1 -0
  34. package/dist/index.js +467 -100
  35. package/dist/index.js.map +1 -1
  36. package/dist/templates/policy/dockerfile/dockerfile.rego +6 -9
  37. package/dist/utils/assertUniqueHostPortMappings.d.ts.map +1 -1
  38. package/dist/utils/checkPortCollision.d.ts.map +1 -1
  39. package/dist/utils/composePublishedPort.d.ts +3 -0
  40. package/dist/utils/composePublishedPort.d.ts.map +1 -0
  41. package/package.json +1 -1
  42. package/schemas/mesh-schema.json +310 -20
  43. 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);
@@ -658,6 +709,52 @@ function rebaseComposePaths(document, composeFilePath, outputProjectDir) {
658
709
  for (const kind of ["configs", "secrets"]) for (const def of Object.values(doc[kind] ?? {})) if (def && typeof def === "object" && typeof def.file === "string") def.file = rebase(def.file, base, out);
659
710
  return doc;
660
711
  }
712
+ function rebaseAppOverridePaths(document, serviceProjectDir, outputProjectDir) {
713
+ const doc = structuredClone(document);
714
+ const base = path.resolve(serviceProjectDir);
715
+ const out = path.resolve(outputProjectDir);
716
+ for (const svc of Object.values(doc.services ?? {})) {
717
+ if (svc.build && typeof svc.build === "object" && !Array.isArray(svc.build)) {
718
+ const build = svc.build;
719
+ if (typeof build.context === "string") {
720
+ build.context = rebase(build.context, base, out);
721
+ }
722
+ }
723
+ if (typeof svc.env_file === "string") {
724
+ svc.env_file = rebase(svc.env_file, base, out);
725
+ } else if (Array.isArray(svc.env_file)) {
726
+ svc.env_file = svc.env_file.map((entry) => {
727
+ if (typeof entry === "string") return rebase(entry, base, out);
728
+ if (entry && typeof entry === "object") {
729
+ const value = entry;
730
+ if (typeof value.path === "string") return { ...value, path: rebase(value.path, base, out) };
731
+ }
732
+ return entry;
733
+ });
734
+ }
735
+ if (Array.isArray(svc.volumes)) {
736
+ svc.volumes = svc.volumes.map((volume) => {
737
+ if (typeof volume === "string") return volumeShort(volume, base, out);
738
+ if (volume && typeof volume === "object") {
739
+ const value = volume;
740
+ if (value.type === "bind" && typeof value.source === "string") {
741
+ return { ...value, source: rebase(value.source, base, out) };
742
+ }
743
+ }
744
+ return volume;
745
+ });
746
+ }
747
+ }
748
+ for (const kind of ["configs", "secrets"]) {
749
+ for (const definition of Object.values(doc[kind] ?? {})) {
750
+ if (definition && typeof definition === "object") {
751
+ const value = definition;
752
+ if (typeof value.file === "string") value.file = rebase(value.file, base, out);
753
+ }
754
+ }
755
+ }
756
+ return doc;
757
+ }
661
758
 
662
759
  // src/core/composition/composeEnvironment.ts
663
760
  function normalizeComposeEnvironment(value, context) {
@@ -668,7 +765,7 @@ function normalizeComposeEnvironment(value, context) {
668
765
  if (typeof item !== "string") throw new ConfigError({ configPath: context, value: item, reason: "Compose environment entries must be strings" });
669
766
  const at = item.indexOf("=");
670
767
  if (at < 0) {
671
- result[item] = process.env[item] ?? "";
768
+ result[item] = null;
672
769
  continue;
673
770
  }
674
771
  result[item.slice(0, at)] = item.slice(at + 1);
@@ -677,7 +774,10 @@ function normalizeComposeEnvironment(value, context) {
677
774
  }
678
775
  if (typeof value !== "object") throw new ConfigError({ configPath: context, value, reason: "Compose environment must be a map or list" });
679
776
  for (const [key, val] of Object.entries(value)) {
680
- if (val === null || val === void 0) continue;
777
+ if (val === null || val === void 0) {
778
+ result[key] = null;
779
+ continue;
780
+ }
681
781
  if (typeof val === "object") throw new ConfigError({ configPath: `${context}.${key}`, value: val, reason: "Compose environment value must be scalar" });
682
782
  result[key] = String(val);
683
783
  }
@@ -687,16 +787,66 @@ function mergeComposeEnvironment(service, overlay) {
687
787
  service.environment = { ...normalizeComposeEnvironment(service.environment, "service.environment"), ...overlay };
688
788
  }
689
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
+
690
825
  // src/core/composition/namespaceDependencyCompose.ts
691
826
  var entries = (obj) => obj && typeof obj === "object" && !Array.isArray(obj) ? Object.entries(obj) : [];
692
827
  function namespaceDependencyCompose(options) {
693
828
  const { document, namespacePrefix: prefix } = options, doc = structuredClone(document);
694
- const make = (kind, keys) => new Map(keys.map((k) => [k, `${prefix}--${kind}--${k}`]));
695
- const serviceNameMap = make("", Object.keys(doc.services ?? {}));
696
- 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 ?? {}));
697
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 ?? {}));
698
837
  const rewriteKeys = (obj, map) => Object.fromEntries(entries(obj).map(([k, v]) => [map.get(k) ?? k, v]));
699
- 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);
700
850
  if (Array.isArray(svc.depends_on)) {
701
851
  svc.depends_on = svc.depends_on.map((v) => typeof v === "string" ? serviceNameMap.get(v) ?? v : v);
702
852
  } else if (svc.depends_on && typeof svc.depends_on === "object") svc.depends_on = rewriteKeys(svc.depends_on, serviceNameMap);
@@ -711,17 +861,14 @@ function namespaceDependencyCompose(options) {
711
861
  }
712
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);
713
863
  if (Array.isArray(svc.volumes)) svc.volumes = svc.volumes.map((v) => namespaceVolume(v, volumeNameMap));
714
- 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 };
715
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)}`;
716
- if (svc.extends && typeof svc.extends === "object" && !svc.extends.file) {
717
- const ref = svc.extends;
718
- if (typeof ref.service === "string") ref.service = serviceNameMap.get(ref.service) ?? ref.service;
719
- }
720
866
  if (Array.isArray(svc.networks)) svc.networks = svc.networks.map((v) => typeof v === "string" ? networkNameMap.get(v) ?? v : v);
721
867
  else if (svc.networks && typeof svc.networks === "object") svc.networks = rewriteKeys(svc.networks, networkNameMap);
722
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);
723
870
  };
724
- for (const svc of Object.values(doc.services ?? {})) rewriteResourceRefs(svc);
871
+ for (const [name, svc] of Object.entries(originalServices)) rewriteResourceRefs(svc, name);
725
872
  doc.services = rewriteKeys(doc.services, serviceNameMap);
726
873
  if (doc.volumes) doc.volumes = rewriteKeys(doc.volumes, volumeNameMap);
727
874
  if (doc.networks) doc.networks = rewriteKeys(doc.networks, networkNameMap);
@@ -730,14 +877,81 @@ function namespaceDependencyCompose(options) {
730
877
  return { document: doc, serviceNameMap, volumeNameMap, networkNameMap, configNameMap, secretNameMap };
731
878
  }
732
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
+
733
943
  // src/core/composition/validateDependencyCompose.ts
734
944
  function validateDependencyCompose(dependencyKey, dependency, document, context) {
735
945
  const fail = (configPath, reason, value) => {
736
946
  throw new ConfigError({ sourceFile: context.composePath, configPath, stage: context.stage, composition: "service", ...value === void 0 ? {} : { value }, reason: `Dependency "${dependencyKey}": ${reason}` });
737
947
  };
738
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" });
739
950
  const services = document.services ?? {};
740
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");
741
955
  if (svc.ports !== void 0) fail(`services.${name}.ports`, "raw dependency ports are forbidden");
742
956
  if (svc.network_mode === "host") fail(`services.${name}.network_mode`, "host network mode is forbidden");
743
957
  if (svc.privileged === true) fail(`services.${name}.privileged`, `privileged services are forbidden`);
@@ -760,11 +974,6 @@ function validateDependencyCompose(dependencyKey, dependency, document, context)
760
974
  for (const ref of svc.volumes_from) if (typeof ref === "string") internalRefs.push(["volumes_from", ref.split(":")[0]]);
761
975
  }
762
976
  for (const key of ["ipc", "pid"]) if (typeof svc[key] === "string" && svc[key].startsWith("service:")) internalRefs.push([key, svc[key].slice(8)]);
763
- if (svc.extends && typeof svc.extends === "object") {
764
- const ref = svc.extends;
765
- if (ref.file !== void 0) fail(`services.${name}.extends.file`, "external extends is unsupported for atomic dependency implementations");
766
- if (typeof ref.service === "string") internalRefs.push(["extends.service", ref.service]);
767
- }
768
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);
769
978
  }
770
979
  if (!Object.keys(dependency.endpoints).length) return;
@@ -777,32 +986,52 @@ function validateDependencyCompose(dependencyKey, dependency, document, context)
777
986
  }
778
987
  for (const owner of owners) {
779
988
  if (services[owner].network_mode !== void 0) fail(`services.${owner}.network_mode`, `endpoint owner cannot use network_mode`);
780
- const health = services[owner].healthcheck;
781
- 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");
782
990
  }
783
991
  }
784
-
785
- // src/core/composition/validateOverrideCompose.ts
992
+ function canonicalBuildContext(value, baseDir) {
993
+ return canonicalPath(path.resolve(baseDir, value));
994
+ }
995
+ function isSameBuildContext(actual, expected, baseDir) {
996
+ return canonicalBuildContext(actual, baseDir) === canonicalBuildContext(expected, baseDir);
997
+ }
786
998
  function validateAndPrepareAppOverride(document, context) {
787
- const fail = (path19, reason, value) => {
788
- throw new ConfigError({ sourceFile: context.file, configPath: path19, stage: context.stage, composition: "service", ...{} , reason });
999
+ const fail = (path20, reason, value) => {
1000
+ throw new ConfigError({ sourceFile: context.file, configPath: path20, stage: context.stage, composition: "service", ...value === void 0 ? {} : { value }, reason });
789
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");
790
1004
  const keys = Object.keys(document.services ?? {});
791
1005
  if (keys.length !== 1 || keys[0] !== "app") fail("services", "override must define exactly one service named app");
792
1006
  const app = structuredClone(document.services.app);
793
- 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");
794
1008
  if (app.healthcheck && typeof app.healthcheck === "object") {
795
1009
  const health = app.healthcheck;
796
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");
797
1011
  }
1012
+ if (typeof app.build === "string") {
1013
+ fail("services.app.build", "override cannot replace Builder-owned app build context; use object-form build.args for build arguments", app.build);
1014
+ }
798
1015
  if (app.build && typeof app.build === "object") {
799
- const b = app.build;
800
- for (const k of ["target", "dockerfile"]) if (b[k] !== void 0) fail(`services.app.build.${k}`, "override cannot change Builder-owned build configuration");
801
- if (b.context !== void 0 && b.context !== "." && b.context !== context.expectedBuildContext) fail("services.app.build.context", "override cannot change app build context");
1016
+ const build = app.build;
1017
+ for (const key of Object.keys(build)) {
1018
+ if (!["args", "context"].includes(key)) {
1019
+ fail(`services.app.build.${key}`, "override cannot change Builder-owned build configuration");
1020
+ }
1021
+ }
1022
+ if (build.context !== void 0) {
1023
+ if (typeof build.context !== "string") {
1024
+ fail("services.app.build.context", "override app build context must be a string", build.context);
1025
+ }
1026
+ if (!isSameBuildContext(build.context, context.expectedBuildContext, context.buildContextBaseDir)) {
1027
+ fail("services.app.build.context", "override cannot change app build context", build.context);
1028
+ }
1029
+ }
802
1030
  }
803
1031
  const env = normalizeComposeEnvironment(app.environment, "services.app.environment");
804
1032
  for (const k of ["EXEC_MODE", "INFRA_MODE"]) if (k in env) fail(`services.app.environment.${k}`, "override cannot set Builder-owned environment");
805
1033
  app.environment = env;
1034
+ const allocator = context.allocator ?? new GeneratedComposeNameAllocator();
806
1035
  const resourceKeys = ["volumes", "networks", "configs", "secrets"];
807
1036
  const resources = {};
808
1037
  for (const kind of resourceKeys) {
@@ -818,7 +1047,8 @@ function validateAndPrepareAppOverride(document, context) {
818
1047
  const names = /* @__PURE__ */ new Map(), mapped = {};
819
1048
  for (const [name, definition] of Object.entries(defs)) {
820
1049
  if (!refs2.has(name)) fail(`${kind}.${name}`, "override resource must be consumed by app");
821
- 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}`);
822
1052
  names.set(name, target);
823
1053
  mapped[target] = definition;
824
1054
  }
@@ -940,13 +1170,14 @@ function compileServiceComposition(stage, projectDir, options = {}) {
940
1170
  const seed = getTemplateSeed(stage, Boolean(options.meshMode));
941
1171
  const rawName = options.projectNameOverride ?? raw.name ?? path.basename(root);
942
1172
  const projectName = deriveProjectName(rawName, stage);
1173
+ const nameAllocator = options.nameAllocator ?? new GeneratedComposeNameAllocator(["app", "tester", "default", options.appServiceName ?? "app"]);
943
1174
  const namespaced = {};
944
1175
  for (const [key, dep] of Object.entries(effective.dependencies).sort(([a], [b]) => a.localeCompare(b))) {
945
1176
  const sourcePath = resolveInsideProject(root, dep.compose, { sourceFile: buildPath, configPath: `dependencies.${key}.compose`, stage });
946
1177
  const document = rebaseComposePaths(loadComposeDocument(sourcePath, { sourceFile: buildPath, configPath: `dependencies.${key}.compose`, stage, composition: "service" }), sourcePath, options.composeOutputDir ?? root);
947
1178
  validateDependencyCompose(key, dep, document, { composePath: sourcePath, stage });
948
1179
  if (Object.keys(dep.endpoints).length) {
949
- 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]) });
950
1181
  namespaced[key] = { doc: ns.document, map: ns.serviceNameMap, source: sourcePath };
951
1182
  }
952
1183
  }
@@ -961,7 +1192,7 @@ function compileServiceComposition(stage, projectDir, options = {}) {
961
1192
  const endpointOwnerMap = /* @__PURE__ */ new Map();
962
1193
  for (const [epName, ep] of Object.entries(dep.endpoints)) endpointOwnerMap.set(epName, entry.map.get(ep.service));
963
1194
  const endpointOwners = new Set(endpointOwnerMap.values());
964
- 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)) };
965
1196
  }
966
1197
  const appEndpoints = buildStandaloneAppEndpoints(effective, stage, options.appServiceName ?? "app");
967
1198
  const depEndpoints = {};
@@ -1010,8 +1241,9 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1010
1241
  const depEnv = options.deferReferenceResolution ? dep.env : resolveEnv(dep.env, registry, `dependencies.${key}.env`);
1011
1242
  for (const svc of Object.values(materialized[key]?.compose.services ?? {})) mergeComposeEnvironment(svc, depEnv);
1012
1243
  }
1013
- const appEnv = options.deferReferenceResolution ? ownEnv(effective, stage) : resolveEnv(ownEnv(effective, stage), registry, "app.env");
1014
- let buildAppEnvironment = { ...appEnv };
1244
+ const buildJsonAppEnvironment = ownEnv(effective, stage);
1245
+ const appEnv = options.deferReferenceResolution ? buildJsonAppEnvironment : resolveEnv(buildJsonAppEnvironment, registry, "app.env");
1246
+ let overrideComposeAppEnvironment = {};
1015
1247
  const runtimeDotenv = path.join(root, `.env.${profile.runtimeStage}`);
1016
1248
  if (fs.existsSync(runtimeDotenv)) {
1017
1249
  const text = fs.readFileSync(runtimeDotenv, "utf8");
@@ -1050,14 +1282,31 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1050
1282
  for (const [epName, ep] of Object.entries(depEndpoints[key])) dependency.endpoints[epName] = ep;
1051
1283
  }
1052
1284
  if (effective.overrideCompose) {
1053
- const overridePath = resolveInsideProject(root, effective.overrideCompose, { sourceFile: buildPath, configPath: "override-compose", stage });
1054
- const odoc = rebaseComposePaths(loadComposeDocument(overridePath, { sourceFile: buildPath, configPath: "override-compose", stage, composition: "service" }), overridePath, options.composeOutputDir ?? root);
1055
- const prepared = validateAndPrepareAppOverride(odoc, { file: overridePath, stage, expectedBuildContext: options.meshMode ? path.relative(options.composeOutputDir ?? root, root).replace(/\\/g, "/") || "." : "." });
1285
+ const overridePath = resolveInsideProject(root, effective.overrideCompose, {
1286
+ sourceFile: buildPath,
1287
+ configPath: "override-compose",
1288
+ stage
1289
+ });
1290
+ const loadedOverride = loadComposeDocument(overridePath, {
1291
+ sourceFile: buildPath,
1292
+ configPath: "override-compose",
1293
+ stage,
1294
+ composition: "service"
1295
+ });
1296
+ const overrideDocument = rebaseAppOverridePaths(loadedOverride, root, outputDir);
1297
+ const prepared = validateAndPrepareAppOverride(overrideDocument, {
1298
+ file: overridePath,
1299
+ stage,
1300
+ expectedBuildContext: String(appBuild.context),
1301
+ buildContextBaseDir: outputDir,
1302
+ allocator: nameAllocator,
1303
+ resourceNamespace: options.meshMode ? options.appServiceName ?? "app" : "app"
1304
+ });
1056
1305
  for (const section of ["volumes", "networks", "configs", "secrets"]) if (prepared.resources[section]) mergeDocument(compose, { services: {}, [section]: prepared.resources[section] }, "app override");
1057
1306
  const rawOverrideEnv = normalizeComposeEnvironment(prepared.app.environment, "override-compose.services.app.environment");
1058
- const overrideEnv = options.deferReferenceResolution ? rawOverrideEnv : resolveEnv(rawOverrideEnv, registry, "override-compose.services.app.environment");
1307
+ const overrideEnv = rawOverrideEnv;
1059
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" });
1060
- buildAppEnvironment = { ...appEnv, ...overrideEnv };
1309
+ overrideComposeAppEnvironment = { ...overrideEnv };
1061
1310
  const merged = { ...app, ...prepared.app };
1062
1311
  merged.environment = { ...appEnv, ...overrideEnv, ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
1063
1312
  const overrideBuild = prepared.app.build && typeof prepared.app.build === "object" ? prepared.app.build : {};
@@ -1080,8 +1329,8 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1080
1329
  const testerEnv = options.deferReferenceResolution ? testerEnvRaw : resolveEnv(testerEnvRaw, registry, "tester.env");
1081
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" } } };
1082
1331
  }
1083
- const builderAppEnvironment = { ...buildAppEnvironment, ...options.externalAppEnv ?? {} };
1084
- 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])) };
1085
1334
  }
1086
1335
 
1087
1336
  // src/core/checkers/checkEffectiveServiceStages.ts
@@ -1367,18 +1616,29 @@ function applyMeshLifecycleEdges(services, edges) {
1367
1616
  }
1368
1617
  }
1369
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
+
1370
1627
  // src/core/mesh/v2/compileMeshTester.ts
1371
1628
  function refs(svc) {
1372
- const out = [];
1629
+ const out = /* @__PURE__ */ new Set();
1373
1630
  const add = (v) => {
1374
- if (typeof v === "string") out.push(v);
1631
+ if (typeof v === "string" && v) out.add(v);
1375
1632
  };
1376
1633
  if (Array.isArray(svc.depends_on)) svc.depends_on.forEach(add);
1377
1634
  else if (svc.depends_on && typeof svc.depends_on === "object") Object.keys(svc.depends_on).forEach(add);
1378
1635
  if (Array.isArray(svc.links)) svc.links.forEach((v) => add(typeof v === "string" ? v.split(":")[0] : v));
1379
1636
  if (Array.isArray(svc.volumes_from)) svc.volumes_from.forEach((v) => add(typeof v === "string" ? v.split(":")[0] : v));
1380
- if (typeof svc.network_mode === "string" && svc.network_mode.startsWith("service:")) out.push(svc.network_mode.slice(8));
1381
- 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];
1382
1642
  }
1383
1643
  function referencedResources(svc, doc) {
1384
1644
  const sets = { volumes: /* @__PURE__ */ new Set(), networks: /* @__PURE__ */ new Set(), configs: /* @__PURE__ */ new Set(), secrets: /* @__PURE__ */ new Set() };
@@ -1402,20 +1662,25 @@ function referencedResources(svc, doc) {
1402
1662
  if (typeof n === "string" && doc[kind]?.[n]) sets[kind].add(n);
1403
1663
  }
1404
1664
  }
1665
+ for (const name of collectBuildSecretReferences(svc)) if (doc.secrets && name in doc.secrets) sets.secrets.add(name);
1405
1666
  return sets;
1406
1667
  }
1407
- function compileMeshTester(meshDir, tester, endpointRegistry, effectiveTopLevelApps, stage, referenceContext) {
1668
+ function compileMeshTester(meshDir, tester, endpointRegistry, effectiveTopLevelApps, stage, referenceContext, nameAllocator = new GeneratedComposeNameAllocator(effectiveTopLevelApps)) {
1408
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);
1409
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" });
1410
1671
  const included = /* @__PURE__ */ new Set(), visit = (name) => {
1411
1672
  if (included.has(name)) return;
1412
- 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" });
1413
1676
  included.add(name);
1414
- for (const ref of refs(raw.services[name])) visit(ref);
1677
+ for (const ref of refs(service)) visit(ref);
1415
1678
  };
1416
1679
  visit(tester.service);
1680
+ validateComposeResourceReferences(raw, { sourceFile: file, stage, composition: "mesh" }, included);
1417
1681
  for (const name of included) {
1418
1682
  const svc = raw.services[name];
1683
+ assertNoServiceBuildContexts(svc, `services.${name}`, file);
1419
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" });
1420
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" });
1421
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" });
@@ -1427,7 +1692,7 @@ function compileMeshTester(meshDir, tester, endpointRegistry, effectiveTopLevelA
1427
1692
  }
1428
1693
  const selected = { services: Object.fromEntries([...included].map((k) => [k, raw.services[k]])) };
1429
1694
  for (const k of Object.keys(res)) if (res[k].size) selected[k] = Object.fromEntries([...res[k]].map((n) => [n, raw[k]?.[n]]));
1430
- 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"]) });
1431
1696
  const runner = ns.serviceNameMap.get(tester.service);
1432
1697
  const runnerSvc = ns.document.services[runner];
1433
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" });
@@ -1437,25 +1702,52 @@ function compileMeshTester(meshDir, tester, endpointRegistry, effectiveTopLevelA
1437
1702
  const env = tester.env ?? {};
1438
1703
  assertMeshTesterEnvPublic(env, "tester.env");
1439
1704
  runnerSvc.environment = { ...normalizeComposeEnvironment(runnerSvc.environment, "tester runner environment"), ...resolveMeshEnvMap(env, meshCtx, "tester.env") };
1440
- 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);
1441
1706
  for (const app of effectiveTopLevelApps) depends[app] = { condition: "service_healthy" };
1442
1707
  runnerSvc.depends_on = depends;
1443
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 };
1444
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
1445
1744
  function assertUniqueHostPortMappings(yamlConfig) {
1446
1745
  const parsed = parse(yamlConfig);
1447
1746
  const owners = /* @__PURE__ */ new Map();
1448
1747
  for (const [serviceName, service] of Object.entries(parsed?.services ?? {})) {
1449
1748
  for (const port of service?.ports ?? []) {
1450
- let hostPort = null;
1451
- if (typeof port === "string") {
1452
- const parts = port.split(":");
1453
- if (parts.length === 2) hostPort = Number(parts[0]);
1454
- if (parts.length === 3) hostPort = Number(parts[1]);
1455
- } else if (port && typeof port === "object" && "published" in port) {
1456
- hostPort = Number(port.published);
1457
- }
1458
- if (!hostPort || !Number.isInteger(hostPort)) continue;
1749
+ const hostPort = parsePublishedHostPort(port);
1750
+ if (hostPort === void 0) continue;
1459
1751
  const existing = owners.get(hostPort);
1460
1752
  if (existing) {
1461
1753
  throw new ScriptError(
@@ -1484,6 +1776,26 @@ function appendPort(service, target, published) {
1484
1776
  ports.push({ target, published, host_ip: PUBLIC_HOST, protocol: "tcp" });
1485
1777
  service.ports = ports;
1486
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
+ }
1487
1799
  function ownerFor(pub, fragment) {
1488
1800
  return pub.target === "app" ? pub.ownerMeshService : fragment.endpoints.dependencies[pub.dependency]?.[pub.endpoint]?.networkHost ?? "";
1489
1801
  }
@@ -1491,15 +1803,20 @@ function setEnv(service, env) {
1491
1803
  const current = service.environment && typeof service.environment === "object" && !Array.isArray(service.environment) ? service.environment : {};
1492
1804
  service.environment = { ...current, ...env };
1493
1805
  }
1806
+ function attachNetworkIfCompatible(service, networkName) {
1807
+ if (service.network_mode !== void 0) return;
1808
+ service.networks = { ...normalizeNetworks(service.networks), [networkName]: null };
1809
+ }
1494
1810
  function compileMeshComposition(stage, meshDir, options = {}) {
1495
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);
1496
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}`)]);
1497
1814
  const fragments = {};
1498
1815
  const compose = { name: projectName, services: {}, networks: { mesh: { driver: "bridge" } } };
1499
1816
  for (const [name, svc] of Object.entries(services).sort(([a], [b]) => a.localeCompare(b))) {
1500
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" });
1501
1818
  const suppress = new Set(Object.keys(svc.dependencyBindings));
1502
- 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 });
1503
1820
  fragments[name] = fragment;
1504
1821
  mergeFragment(compose, fragment.compose, name);
1505
1822
  const app = compose.services[name];
@@ -1513,32 +1830,17 @@ function compileMeshComposition(stage, meshDir, options = {}) {
1513
1830
  for (const ep of Object.values(fragment.endpoints.dependencies[dep] ?? {})) {
1514
1831
  const owner = ep.networkHost;
1515
1832
  const ownerService = compose.services[owner];
1516
- if (ownerService) {
1517
- const old = normalizeNetworks(ownerService.networks);
1518
- old[privateName] = null;
1519
- ownerService.networks = old;
1520
- }
1833
+ if (ownerService) attachNetworkIfCompatible(ownerService, privateName);
1521
1834
  }
1522
- 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] ?? []) {
1523
1836
  const ownerService = compose.services[generated];
1524
- const old = normalizeNetworks(ownerService.networks);
1525
- old[privateName] = null;
1526
- ownerService.networks = old;
1837
+ attachNetworkIfCompatible(ownerService, privateName);
1527
1838
  }
1528
1839
  }
1529
1840
  }
1530
1841
  app.networks = { ...normalizeNetworks(app.networks), ...networks };
1531
1842
  }
1532
- const publication = resolveMeshPublication(services, bindingMap, stage, meshPath), intents = [];
1533
- 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))) {
1534
- const ep = services[name].effectiveBuild.app.endpoints[pub.endpoint];
1535
- intents.push({ logicalPath: pub.logicalPath, requested: ep.publicPort });
1536
- }
1537
- 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}`))) {
1538
- const ep = services[name].effectiveBuild.dependencies[pub.dependency].endpoints[pub.endpoint];
1539
- intents.push({ logicalPath: pub.logicalPath, requested: ep.publicPort });
1540
- }
1541
- 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));
1542
1844
  const endpoints = { app: {}, dependencies: {} };
1543
1845
  for (const [name, svc] of Object.entries(services)) {
1544
1846
  endpoints.app[name] = {};
@@ -1575,15 +1877,17 @@ function compileMeshComposition(stage, meshDir, options = {}) {
1575
1877
  const refContext = { services, bindings: bindingMap, endpoints, stage, meshJsonPath: meshPath };
1576
1878
  for (const [name, fragment] of Object.entries(fragments)) {
1577
1879
  const app = compose.services[name];
1578
- 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`);
1579
1881
  const meshEnv = resolveMeshEnvMap(fragment.externalAppEnvironment ?? {}, refContext, `services.${name}.env`);
1580
- setEnv(app, { ...buildEnv, ...meshEnv });
1882
+ app.environment = { ...buildEnv, ...fragment.overrideComposeAppEnvironment ?? {}, ...meshEnv, ...fragment.builderInternalEnvironment ?? {} };
1581
1883
  for (const [depName, depEnv] of Object.entries(fragment.dependencyEnvironments ?? {})) {
1582
1884
  const logicalBinding = bindingMap.get(bindingKey(name, depName));
1583
1885
  if (logicalBinding) continue;
1584
1886
  const resolvedDep = resolveServiceBuildEnvThroughMesh(name, depEnv, refContext, `services.${name}.dependencies.${depName}.env`);
1585
- const prefix = `svc--${name}--dep--${depName}--`;
1586
- 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
+ }
1587
1891
  }
1588
1892
  }
1589
1893
  const edges = buildMeshLifecycleEdges(services, bindingMap, stage, meshPath);
@@ -1618,18 +1922,85 @@ function compileMeshComposition(stage, meshDir, options = {}) {
1618
1922
  let testerServiceName;
1619
1923
  if (stage === "e2e") {
1620
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? }" });
1621
- 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;
1622
1926
  if (built) {
1623
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 } : {} };
1624
1928
  mergeFragment(compose, fragment, "mesh tester");
1625
1929
  testerServiceName = built.runnerServiceName;
1626
1930
  }
1627
1931
  }
1932
+ nameAllocator.assertUnique();
1628
1933
  const yaml = stringify(compose);
1629
1934
  assertUniqueHostPortMappings(yaml);
1630
1935
  return { compose, effectiveMesh: effective, loadedServices: services, endpoints, projectName, ...testerServiceName ? { testerServiceName } : {} };
1631
1936
  }
1632
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
+
1633
2004
  // src/core/mesh/checkers/checkMeshServices.ts
1634
2005
  function checkMeshServices(mesh, meshDir) {
1635
2006
  const root = resolveProjectDir(meshDir), meshPath = path.join(root, "mesh.json");
@@ -1637,6 +2008,7 @@ function checkMeshServices(mesh, meshDir) {
1637
2008
  for (const stage of ["dev", "prod", "test", "e2e"]) {
1638
2009
  const effective = resolveMeshStage(mesh, stage, meshPath);
1639
2010
  const services = loadEffectiveMeshServices(root, effective, stage);
2011
+ if (stage === "test") validateMeshTestStage(services, root, meshPath, true);
1640
2012
  for (const [name, svc] of Object.entries(services)) {
1641
2013
  if (!checked.has(svc.absolutePath)) {
1642
2014
  console.log(pc22.cyan(`
@@ -1651,7 +2023,7 @@ function checkMeshServices(mesh, meshDir) {
1651
2023
  for (const key of ["EXEC_MODE", "INFRA_MODE", ...Object.values(svc.effectiveBuild.app.endpoints).some((ep) => ep.primary) ? ["PORT"] : []]) {
1652
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" });
1653
2025
  }
1654
- resolveServiceBuildEnvThroughMesh(name, fragment.builderAppEnvironment ?? {}, ctx, `services.${name}.app.env`);
2026
+ resolveServiceBuildEnvThroughMesh(name, fragment.buildJsonAppEnvironment ?? {}, ctx, `services.${name}.app.env`);
1655
2027
  for (const [depName, depEnv] of Object.entries(fragment.dependencyEnvironments ?? {})) resolveServiceBuildEnvThroughMesh(name, depEnv, ctx, `services.${name}.dependencies.${depName}.env`);
1656
2028
  resolveMeshEnvMap(svc.meshEnv, ctx, `services.${name}.env`);
1657
2029
  }
@@ -2120,15 +2492,9 @@ function extractHostPorts(yamlConfig) {
2120
2492
  if (parsed?.services && typeof parsed.services === "object") {
2121
2493
  for (const svc of Object.values(parsed.services)) {
2122
2494
  if (Array.isArray(svc?.ports)) {
2123
- for (const p of svc.ports) {
2124
- if (typeof p === "string") {
2125
- const parts = p.split(":");
2126
- const hostPort = parts.length > 1 ? parseInt(parts[0], 10) : parseInt(p, 10);
2127
- if (!isNaN(hostPort)) ports.push(hostPort);
2128
- } else if (typeof p === "object" && p.published) {
2129
- const hostPort = parseInt(p.published, 10);
2130
- if (!isNaN(hostPort)) ports.push(hostPort);
2131
- }
2495
+ for (const mapping of svc.ports) {
2496
+ const hostPort = parsePublishedHostPort(mapping);
2497
+ if (hostPort !== void 0) ports.push(hostPort);
2132
2498
  }
2133
2499
  }
2134
2500
  }
@@ -2302,7 +2668,7 @@ async function runMeshProd(options = {}) {
2302
2668
  return status;
2303
2669
  }
2304
2670
  async function runMeshTestUnit(options = {}) {
2305
- 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));
2306
2672
  console.log(pc22.bold(pc22.blue("\n[1/2] MESH SERVICE UNIT/ISOLATED TESTS\n")));
2307
2673
  for (const [name, svc] of Object.entries(services).sort(([a], [b]) => a.localeCompare(b))) {
2308
2674
  console.log(pc22.cyan(`-> Running isolated unit tests for [${name}]`));
@@ -2311,11 +2677,12 @@ async function runMeshTestUnit(options = {}) {
2311
2677
  const refCtx = { services: { [name]: svc }, bindings: /* @__PURE__ */ new Map(), endpoints, stage: "test", meshJsonPath: meshPath };
2312
2678
  const env = svc.meshEnv;
2313
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" });
2314
- const resolvedBuild = resolveServiceBuildEnvThroughMesh(name, compiled.builderAppEnvironment ?? {}, refCtx, `services.${name}.app.env`);
2680
+ const resolvedBuild = resolveServiceBuildEnvThroughMesh(name, compiled.buildJsonAppEnvironment ?? {}, refCtx, `services.${name}.app.env`);
2315
2681
  for (const [depName, depEnv] of Object.entries(compiled.dependencyEnvironments ?? {})) resolveServiceBuildEnvThroughMesh(name, depEnv, refCtx, `services.${name}.dependencies.${depName}.env`);
2316
2682
  const resolved = resolveMeshEnvMap(env, refCtx, `services.${name}.env`);
2317
2683
  const app = compiled.compose.services.app;
2318
- app.environment = { ...app.environment, ...resolvedBuild, ...resolved };
2684
+ app.environment = { ...resolvedBuild, ...compiled.overrideComposeAppEnvironment ?? {}, ...resolved, ...compiled.builderInternalEnvironment ?? {} };
2685
+ applyTestAppPublications(validated, name, app, compiled.endpoints.app);
2319
2686
  const projectName = `${deriveProjectName(raw.name ?? path.basename(meshDir), "dev")}-${name}-test`;
2320
2687
  compiled.compose.name = projectName;
2321
2688
  const yaml = stringify(compiled.compose);