@solid-stack/builder 1.2.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +59 -200
- package/dist/bin.js +1689 -2591
- package/dist/bin.js.map +1 -1
- package/dist/commands/mesh/commands/down/handler.d.ts.map +1 -1
- package/dist/commands/mesh/commands/up/command.d.ts.map +1 -1
- package/dist/commands/service/commands/export/command.d.ts.map +1 -1
- package/dist/commands/service/commands/up/command.d.ts.map +1 -1
- package/dist/core/buildSchema.d.ts +1029 -110
- package/dist/core/buildSchema.d.ts.map +1 -1
- package/dist/core/checkers/checkDockerfile.d.ts.map +1 -1
- package/dist/core/checkers/checkDockerfileContract.d.ts +1 -1
- package/dist/core/checkers/checkDockerfileContract.d.ts.map +1 -1
- package/dist/core/checkers/checkEffectiveServiceStages.d.ts +2 -0
- package/dist/core/checkers/checkEffectiveServiceStages.d.ts.map +1 -0
- package/dist/core/checkers/checkYamlFiles.d.ts +1 -1
- package/dist/core/checkers/checkYamlFiles.d.ts.map +1 -1
- package/dist/core/checkers/getDeclaredYamlFiles.d.ts +3 -1
- package/dist/core/checkers/getDeclaredYamlFiles.d.ts.map +1 -1
- package/dist/core/compileEnvironment.d.ts +1 -1
- package/dist/core/compileEnvironment.d.ts.map +1 -1
- package/dist/core/composition/compileServiceComposition.d.ts +18 -0
- package/dist/core/composition/compileServiceComposition.d.ts.map +1 -0
- package/dist/core/composition/composeEnvironment.d.ts +4 -0
- package/dist/core/composition/composeEnvironment.d.ts.map +1 -0
- package/dist/core/composition/composePaths.d.ts +3 -0
- package/dist/core/composition/composePaths.d.ts.map +1 -0
- package/dist/core/composition/dependencyLifecycle.d.ts +4 -0
- package/dist/core/composition/dependencyLifecycle.d.ts.map +1 -0
- package/dist/core/composition/loadCompose.d.ts +8 -0
- package/dist/core/composition/loadCompose.d.ts.map +1 -0
- package/dist/core/composition/namespaceDependencyCompose.d.ts +15 -0
- package/dist/core/composition/namespaceDependencyCompose.d.ts.map +1 -0
- package/dist/core/composition/serviceEndpoints.d.ts +5 -0
- package/dist/core/composition/serviceEndpoints.d.ts.map +1 -0
- package/dist/core/composition/types.d.ts +64 -0
- package/dist/core/composition/types.d.ts.map +1 -0
- package/dist/core/composition/validateDependencyCompose.d.ts +8 -0
- package/dist/core/composition/validateDependencyCompose.d.ts.map +1 -0
- package/dist/core/composition/validateOverrideCompose.d.ts +11 -0
- package/dist/core/composition/validateOverrideCompose.d.ts.map +1 -0
- package/dist/core/config/constants.d.ts +13 -0
- package/dist/core/config/constants.d.ts.map +1 -0
- package/dist/core/config/endpointProperties.d.ts +16 -0
- package/dist/core/config/endpointProperties.d.ts.map +1 -0
- package/dist/core/config/hostPorts.d.ts +10 -0
- package/dist/core/config/hostPorts.d.ts.map +1 -0
- package/dist/core/config/lifecycleGraph.d.ts +7 -0
- package/dist/core/config/lifecycleGraph.d.ts.map +1 -0
- package/dist/core/config/pathSafety.d.ts +6 -0
- package/dist/core/config/pathSafety.d.ts.map +1 -0
- package/dist/core/config/references.d.ts +15 -0
- package/dist/core/config/references.d.ts.map +1 -0
- package/dist/core/config/resolveBuildStage.d.ts +4 -0
- package/dist/core/config/resolveBuildStage.d.ts.map +1 -0
- package/dist/core/config/resolveMeshStage.d.ts +4 -0
- package/dist/core/config/resolveMeshStage.d.ts.map +1 -0
- package/dist/core/config/stageMerge.d.ts +4 -0
- package/dist/core/config/stageMerge.d.ts.map +1 -0
- package/dist/core/config/types.d.ts +44 -0
- package/dist/core/config/types.d.ts.map +1 -0
- package/dist/core/mesh/MeshRunOptions.d.ts +0 -1
- package/dist/core/mesh/MeshRunOptions.d.ts.map +1 -1
- package/dist/core/mesh/checkers/checkMeshJson.d.ts +1 -1
- package/dist/core/mesh/checkers/checkMeshJson.d.ts.map +1 -1
- package/dist/core/mesh/checkers/checkMeshServices.d.ts +1 -1
- package/dist/core/mesh/checkers/checkMeshServices.d.ts.map +1 -1
- package/dist/core/mesh/checkers/checkMeshTester.d.ts +1 -1
- package/dist/core/mesh/checkers/checkMeshTester.d.ts.map +1 -1
- package/dist/core/mesh/compileMeshEnvironment.d.ts +1 -3
- package/dist/core/mesh/compileMeshEnvironment.d.ts.map +1 -1
- package/dist/core/mesh/getMeshJson.d.ts.map +1 -1
- package/dist/core/mesh/meshSchema.d.ts +267 -334
- package/dist/core/mesh/meshSchema.d.ts.map +1 -1
- package/dist/core/mesh/runners/runMeshDev.d.ts.map +1 -1
- package/dist/core/mesh/runners/runMeshProd.d.ts.map +1 -1
- package/dist/core/mesh/runners/runMeshTest.d.ts.map +1 -1
- package/dist/core/mesh/runners/runMeshTestE2e.d.ts.map +1 -1
- package/dist/core/mesh/runners/runMeshTestUnit.d.ts.map +1 -1
- package/dist/core/mesh/types.d.ts +34 -40
- package/dist/core/mesh/types.d.ts.map +1 -1
- package/dist/core/mesh/v2/compileMeshComposition.d.ts +6 -0
- package/dist/core/mesh/v2/compileMeshComposition.d.ts.map +1 -0
- package/dist/core/mesh/v2/compileMeshTester.d.ts +14 -0
- package/dist/core/mesh/v2/compileMeshTester.d.ts.map +1 -0
- package/dist/core/mesh/v2/lifecycle.d.ts +10 -0
- package/dist/core/mesh/v2/lifecycle.d.ts.map +1 -0
- package/dist/core/mesh/v2/loadMeshServices.d.ts +5 -0
- package/dist/core/mesh/v2/loadMeshServices.d.ts.map +1 -0
- package/dist/core/mesh/v2/meshReferences.d.ts +15 -0
- package/dist/core/mesh/v2/meshReferences.d.ts.map +1 -0
- package/dist/core/mesh/v2/publication.d.ts +3 -0
- package/dist/core/mesh/v2/publication.d.ts.map +1 -0
- package/dist/core/mesh/v2/substitution.d.ts +5 -0
- package/dist/core/mesh/v2/substitution.d.ts.map +1 -0
- package/dist/core/mesh/v2/types.d.ts +40 -0
- package/dist/core/mesh/v2/types.d.ts.map +1 -0
- package/dist/core/runners/runTestE2e.d.ts.map +1 -1
- package/dist/core/runners/runTestUnit.d.ts.map +1 -1
- package/dist/core/templates.d.ts +1 -0
- package/dist/core/templates.d.ts.map +1 -1
- package/dist/errors/ConfigError.d.ts +15 -0
- package/dist/errors/ConfigError.d.ts.map +1 -0
- package/dist/errors/PortConflictError.d.ts +8 -0
- package/dist/errors/PortConflictError.d.ts.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1691 -2593
- package/dist/index.js.map +1 -1
- package/dist/templates/docker/docker-compose.base.yml +4 -4
- package/dist/templates/docker/docker-compose.dev.yml +1 -5
- package/dist/templates/docker/docker-compose.e2e.yml +9 -8
- package/dist/templates/docker/docker-compose.prod.yml +1 -6
- package/dist/templates/docker/docker-compose.test.yml +3 -8
- package/dist/templates/policy/dockerfile/dockerfile.rego +64 -0
- package/dist/types/index.d.ts +60 -50
- package/dist/types/index.d.ts.map +1 -1
- package/dist/utils/checkPortCollision.d.ts.map +1 -1
- package/dist/utils/getBuildJson.d.ts.map +1 -1
- package/dist/utils/runState.d.ts.map +1 -1
- package/package.json +4 -2
- package/schemas/build-schema.json +620 -101
- package/schemas/mesh-schema.json +225 -133
- package/templates/docker/docker-compose.base.yml +4 -4
- package/templates/docker/docker-compose.dev.yml +1 -5
- package/templates/docker/docker-compose.e2e.yml +9 -8
- package/templates/docker/docker-compose.prod.yml +1 -6
- package/templates/docker/docker-compose.test.yml +3 -8
- package/templates/policy/dockerfile/dockerfile.rego +64 -0
- package/dist/core/checkers/checkComposeContract.d.ts +0 -3
- package/dist/core/checkers/checkComposeContract.d.ts.map +0 -1
- package/dist/templates/docker/docker-compose.standalone.yml +0 -5
- package/dist/utils/dependencyPorts.d.ts +0 -10
- package/dist/utils/dependencyPorts.d.ts.map +0 -1
- package/dist/utils/extractBuildDeps.d.ts +0 -3
- package/dist/utils/extractBuildDeps.d.ts.map +0 -1
- package/dist/utils/extractOverrides.d.ts +0 -3
- package/dist/utils/extractOverrides.d.ts.map +0 -1
- package/dist/utils/ymlMods/addDependenciesToAppService.d.ts +0 -3
- package/dist/utils/ymlMods/addDependenciesToAppService.d.ts.map +0 -1
- package/dist/utils/ymlMods/makeE2eDependOnApp.d.ts +0 -2
- package/dist/utils/ymlMods/makeE2eDependOnApp.d.ts.map +0 -1
- package/dist/utils/ymlMods/renameServicesWithDependencies.d.ts +0 -3
- package/dist/utils/ymlMods/renameServicesWithDependencies.d.ts.map +0 -1
- package/templates/docker/docker-compose.standalone.yml +0 -5
package/dist/index.js
CHANGED
|
@@ -1,25 +1,19 @@
|
|
|
1
1
|
import { Command, Argument } from 'commander';
|
|
2
2
|
import pc22 from 'picocolors';
|
|
3
|
-
import fs, { existsSync, readFileSync, mkdirSync, writeFileSync,
|
|
4
|
-
import
|
|
5
|
-
import { spawnSync, spawn } from 'child_process';
|
|
6
|
-
import { parse, stringify, parseAllDocuments } from 'yaml';
|
|
3
|
+
import fs, { existsSync, readFileSync, mkdirSync, writeFileSync, renameSync, statSync, unlinkSync } from 'fs';
|
|
4
|
+
import path4 from 'path';
|
|
7
5
|
import { z } from 'zod';
|
|
8
|
-
import '
|
|
6
|
+
import { spawnSync, spawn } from 'child_process';
|
|
7
|
+
import { fileURLToPath } from 'url';
|
|
8
|
+
import { stringify, parse, parseAllDocuments } from 'yaml';
|
|
9
|
+
import crypto from 'crypto';
|
|
9
10
|
import os from 'os';
|
|
10
11
|
import net from 'net';
|
|
11
|
-
import { fileURLToPath } from 'url';
|
|
12
12
|
import { createInterface } from 'readline/promises';
|
|
13
13
|
import { createRequire } from 'module';
|
|
14
14
|
|
|
15
15
|
// src/types/index.ts
|
|
16
|
-
var SERVICE_STAGES = [
|
|
17
|
-
"dev",
|
|
18
|
-
"prod",
|
|
19
|
-
"test",
|
|
20
|
-
"test-unit",
|
|
21
|
-
"test-e2e"
|
|
22
|
-
];
|
|
16
|
+
var SERVICE_STAGES = ["dev", "prod", "test", "test-unit", "test-e2e"];
|
|
23
17
|
|
|
24
18
|
// src/errors/ScriptError.ts
|
|
25
19
|
var ScriptError = class extends Error {
|
|
@@ -39,6 +33,43 @@ var NotFoundError = class extends ScriptError {
|
|
|
39
33
|
}
|
|
40
34
|
};
|
|
41
35
|
|
|
36
|
+
// src/errors/ConfigError.ts
|
|
37
|
+
var ConfigError = class extends ScriptError {
|
|
38
|
+
context;
|
|
39
|
+
constructor(context, options) {
|
|
40
|
+
const details = [context.sourceFile ? `source=${context.sourceFile}` : void 0, context.configPath ? `path=${context.configPath}` : void 0, context.stage ? `stage=${context.stage}` : void 0, context.composition ? `composition=${context.composition}` : void 0, context.referencedObject ? `reference=${context.referencedObject}` : void 0, context.value !== void 0 ? `value=${JSON.stringify(context.value)}` : void 0].filter(Boolean);
|
|
41
|
+
super(`${context.reason}${details.length ? ` (${details.join(", ")})` : ""}`, options);
|
|
42
|
+
this.name = "ConfigError";
|
|
43
|
+
this.context = context;
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
// src/core/config/constants.ts
|
|
48
|
+
var BUILDER_IDENTIFIER_PATTERN = /^[a-z][a-z0-9-]*$/;
|
|
49
|
+
var ENDPOINT_SCHEME_PATTERN = /^[A-Za-z][A-Za-z0-9+.-]*$/;
|
|
50
|
+
var DEPENDENCY_REFERENCE_PATTERN = /^dependencies\.([a-z][a-z0-9-]*)$/;
|
|
51
|
+
var ENDPOINT_PROPERTIES = ["network_host", "network_port", "network_address", "network_url", "public_host", "public_port", "public_address", "public_url"];
|
|
52
|
+
var PUBLIC_ENDPOINT_PROPERTIES = /* @__PURE__ */ new Set(["public_host", "public_port", "public_address", "public_url"]);
|
|
53
|
+
var RESERVED_MESH_SERVICE_NAMES = /* @__PURE__ */ new Set(["app", "dependencies", "tester", "services", "dev", "prod", "test", "e2e"]);
|
|
54
|
+
var PUBLIC_HOST = "127.0.0.1";
|
|
55
|
+
var AUTO_PORT_CACHE_VERSION = 1;
|
|
56
|
+
var AUTO_PORT_CACHE_RELATIVE_PATH = ".builder/ports-v2.json";
|
|
57
|
+
var AUTO_PORT_SCAN_START = 2e4;
|
|
58
|
+
|
|
59
|
+
// src/core/buildSchema.ts
|
|
60
|
+
var identifierSchema = z.string().regex(BUILDER_IDENTIFIER_PATTERN, "must match ^[a-z][a-z0-9-]*$");
|
|
61
|
+
var envSchema = z.record(z.string(), z.string());
|
|
62
|
+
var portSchema = z.number().int().min(1).max(65535);
|
|
63
|
+
var publicPortSchema = z.union([portSchema, z.literal("AUTO")]);
|
|
64
|
+
var appEndpointSchema = z.object({ port: portSchema, publicPort: publicPortSchema.optional(), primary: z.boolean().optional(), scheme: z.string().regex(ENDPOINT_SCHEME_PATTERN).optional() }).strict();
|
|
65
|
+
var dependencyEndpointSchema = appEndpointSchema.extend({ service: z.string().min(1) }).strict();
|
|
66
|
+
var dependencySchema = z.object({ compose: z.string().min(1), env: envSchema.optional(), endpoints: z.record(identifierSchema, dependencyEndpointSchema).optional(), dependsOn: z.array(z.string()).optional() }).strict();
|
|
67
|
+
var appStageEndpointSchema = appEndpointSchema.partial().strict();
|
|
68
|
+
var dependencyStageEndpointSchema = dependencyEndpointSchema.partial().strict();
|
|
69
|
+
var dependencyStageSchema = z.object({ compose: z.string().min(1).optional(), env: envSchema.optional(), endpoints: z.record(identifierSchema, dependencyStageEndpointSchema).optional(), dependsOn: z.array(z.string()).optional() }).strict();
|
|
70
|
+
var buildStageSchema = z.object({ "override-compose": z.string().min(1).optional(), app: z.object({ env: envSchema.optional(), endpoints: z.record(identifierSchema, appStageEndpointSchema).optional() }).strict().optional(), dependencies: z.record(identifierSchema, dependencyStageSchema).optional() }).strict();
|
|
71
|
+
var buildJsonSchema = z.object({ $schema: z.string().optional(), name: z.string().optional(), dockerfile: z.string().min(1).optional(), app: z.object({ env: envSchema.optional(), endpoints: z.record(identifierSchema, appEndpointSchema).optional() }).strict(), dependencies: z.record(identifierSchema, dependencySchema).optional(), tester: z.object({ env: envSchema.optional() }).strict().optional(), dev: buildStageSchema.optional(), prod: buildStageSchema.optional(), test: buildStageSchema.optional(), e2e: buildStageSchema.optional() }).strict();
|
|
72
|
+
|
|
42
73
|
// src/utils/errorMessage.ts
|
|
43
74
|
function errorMessage(err) {
|
|
44
75
|
if (err instanceof Error) {
|
|
@@ -50,96 +81,37 @@ function errorMessage(err) {
|
|
|
50
81
|
return String(err);
|
|
51
82
|
}
|
|
52
83
|
function resolveProjectDir(projectDir) {
|
|
53
|
-
return
|
|
54
|
-
}
|
|
55
|
-
function toComposePath(baseDir, targetPath) {
|
|
56
|
-
const absBase = path13.resolve(baseDir);
|
|
57
|
-
const absTarget = path13.resolve(absBase, targetPath);
|
|
58
|
-
let rel = path13.relative(absBase, absTarget);
|
|
59
|
-
if (!rel || rel === ".") {
|
|
60
|
-
return ".";
|
|
61
|
-
}
|
|
62
|
-
rel = rel.replace(/\\/g, "/");
|
|
63
|
-
if (path13.isAbsolute(rel) || /^[a-zA-Z]:\//.test(rel)) {
|
|
64
|
-
return rel;
|
|
65
|
-
}
|
|
66
|
-
if (rel.startsWith("./") || rel.startsWith("../") || rel.startsWith("/")) {
|
|
67
|
-
return rel;
|
|
68
|
-
}
|
|
69
|
-
return `./${rel}`;
|
|
70
|
-
}
|
|
71
|
-
function isBindMount(source) {
|
|
72
|
-
if (!source) return false;
|
|
73
|
-
if (source.startsWith(".") || source.startsWith("/") || source.startsWith("~")) {
|
|
74
|
-
return true;
|
|
75
|
-
}
|
|
76
|
-
if (/^[a-zA-Z]:[\\/]/.test(source)) {
|
|
77
|
-
return true;
|
|
78
|
-
}
|
|
79
|
-
return false;
|
|
84
|
+
return path4.resolve(projectDir ?? process.cwd());
|
|
80
85
|
}
|
|
81
86
|
function isPathInside(parentDir, childPath) {
|
|
82
|
-
const absParent =
|
|
83
|
-
const absChild =
|
|
84
|
-
const rel =
|
|
85
|
-
return rel !== ".." && !rel.startsWith(".." +
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
// src/utils/ymlMods/normalizeDependsOn.ts
|
|
89
|
-
function normalizeDependsOn(service) {
|
|
90
|
-
if (!service || typeof service !== "object" || !service.depends_on) {
|
|
91
|
-
return;
|
|
92
|
-
}
|
|
93
|
-
if (Array.isArray(service.depends_on)) {
|
|
94
|
-
const obj = {};
|
|
95
|
-
for (const dep of service.depends_on) {
|
|
96
|
-
if (typeof dep === "string") {
|
|
97
|
-
obj[dep] = { condition: "service_started" };
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
service.depends_on = obj;
|
|
101
|
-
}
|
|
87
|
+
const absParent = path4.resolve(parentDir);
|
|
88
|
+
const absChild = path4.resolve(absParent, childPath);
|
|
89
|
+
const rel = path4.relative(absParent, absChild);
|
|
90
|
+
return rel !== ".." && !rel.startsWith(".." + path4.sep) && !rel.startsWith("../") && !path4.isAbsolute(rel);
|
|
102
91
|
}
|
|
103
92
|
|
|
104
93
|
// src/utils/getBuildJson.ts
|
|
105
94
|
var getBuildJson = (projectDir = process.cwd()) => {
|
|
106
|
-
const absProjectDir = resolveProjectDir(projectDir);
|
|
107
|
-
|
|
108
|
-
if (!existsSync(buildJsonPath)) {
|
|
109
|
-
throw new NotFoundError(
|
|
110
|
-
`Build JSON file not found at ${buildJsonPath}. Please make sure build.json exists in the project root.`
|
|
111
|
-
);
|
|
112
|
-
}
|
|
95
|
+
const absProjectDir = resolveProjectDir(projectDir), buildJsonPath = path4.join(absProjectDir, "build.json");
|
|
96
|
+
if (!existsSync(buildJsonPath)) throw new NotFoundError(`Build JSON file not found at ${buildJsonPath}. Please make sure build.json exists in the project root.`);
|
|
113
97
|
let rawData;
|
|
114
98
|
try {
|
|
115
99
|
rawData = readFileSync(buildJsonPath, "utf-8");
|
|
116
100
|
} catch (error) {
|
|
117
|
-
throw new ScriptError(
|
|
118
|
-
`Failed to read build.json at ${buildJsonPath}: ${errorMessage(error)}`
|
|
119
|
-
);
|
|
101
|
+
throw new ScriptError(`Failed to read build.json at ${buildJsonPath}: ${errorMessage(error)}`);
|
|
120
102
|
}
|
|
121
|
-
let
|
|
103
|
+
let parsed;
|
|
122
104
|
try {
|
|
123
|
-
|
|
105
|
+
parsed = JSON.parse(rawData);
|
|
124
106
|
} catch (error) {
|
|
125
|
-
throw new ScriptError(
|
|
126
|
-
`Failed to parse build.json at ${buildJsonPath}: ${errorMessage(error)}`
|
|
127
|
-
);
|
|
128
|
-
}
|
|
129
|
-
if (!buildJson || typeof buildJson !== "object" || Array.isArray(buildJson)) {
|
|
130
|
-
throw new ScriptError(
|
|
131
|
-
`Invalid build.json at ${buildJsonPath}: root must be a JSON object.`
|
|
132
|
-
);
|
|
107
|
+
throw new ScriptError(`Failed to parse build.json at ${buildJsonPath}: ${errorMessage(error)}`);
|
|
133
108
|
}
|
|
134
|
-
const
|
|
135
|
-
if (
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
normalizeDependsOn(serviceConfig);
|
|
139
|
-
}
|
|
140
|
-
}
|
|
109
|
+
const result = buildJsonSchema.safeParse(parsed);
|
|
110
|
+
if (!result.success) {
|
|
111
|
+
const reason = result.error.issues.map((issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`).join("; ");
|
|
112
|
+
throw new ConfigError({ sourceFile: buildJsonPath, configPath: "<root>", composition: "service", reason: `Invalid build.json: ${reason}` });
|
|
141
113
|
}
|
|
142
|
-
return
|
|
114
|
+
return result.data;
|
|
143
115
|
};
|
|
144
116
|
|
|
145
117
|
// src/core/checkers/constants.ts
|
|
@@ -185,22 +157,14 @@ ${ctx.detail}`);
|
|
|
185
157
|
// src/core/checkers/checkDockerfile.ts
|
|
186
158
|
function checkDockerfile(buildJson, projectDir) {
|
|
187
159
|
const dockerfileRel = buildJson.dockerfile || "Dockerfile";
|
|
188
|
-
const dockerfilePath =
|
|
160
|
+
const dockerfilePath = path4.resolve(projectDir, dockerfileRel);
|
|
189
161
|
if (!isPathInside(projectDir, dockerfilePath)) {
|
|
190
162
|
throw new ScriptError(
|
|
191
163
|
`Security error: Dockerfile path "${dockerfileRel}" escapes the project directory.`
|
|
192
164
|
);
|
|
193
165
|
}
|
|
194
166
|
if (!existsSync(dockerfilePath)) {
|
|
195
|
-
|
|
196
|
-
throw new ScriptError(
|
|
197
|
-
`Dockerfile declared in build.json not found at: ${dockerfilePath}`
|
|
198
|
-
);
|
|
199
|
-
}
|
|
200
|
-
console.log(
|
|
201
|
-
pc22.yellow(`\u26A0\uFE0F No ${dockerfileRel} found in project directory. Skipping Dockerfile checks.`)
|
|
202
|
-
);
|
|
203
|
-
return;
|
|
167
|
+
throw new ConfigError({ sourceFile: path4.join(projectDir, "build.json"), configPath: "dockerfile", value: dockerfileRel, composition: "service", reason: `Application Dockerfile not found at ${dockerfilePath}` });
|
|
204
168
|
}
|
|
205
169
|
const content = readFileSync(dockerfilePath, "utf-8");
|
|
206
170
|
console.log(pc22.cyan(`
|
|
@@ -212,171 +176,846 @@ function checkDockerfile(buildJson, projectDir) {
|
|
|
212
176
|
{ stepName: "Dockerfile Linting", targetFile: dockerfileRel, input: content }
|
|
213
177
|
);
|
|
214
178
|
}
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
const
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
throw new ScriptError(
|
|
223
|
-
`Security error: Dockerfile path "${dockerfileRel}" escapes the project directory.`
|
|
224
|
-
);
|
|
179
|
+
var cachedTemplatesDir = null;
|
|
180
|
+
var lastEnvTemplatesDir = void 0;
|
|
181
|
+
function getTemplatesDir() {
|
|
182
|
+
const envVal = process.env.BUILDER_TEMPLATES_DIR;
|
|
183
|
+
if (envVal !== lastEnvTemplatesDir) {
|
|
184
|
+
cachedTemplatesDir = null;
|
|
185
|
+
lastEnvTemplatesDir = envVal;
|
|
225
186
|
}
|
|
226
|
-
if (
|
|
227
|
-
|
|
187
|
+
if (envVal) {
|
|
188
|
+
const envDir = path4.resolve(envVal);
|
|
189
|
+
if (!fs.existsSync(envDir) || !fs.existsSync(path4.join(envDir, "docker"))) {
|
|
190
|
+
throw new ScriptError(
|
|
191
|
+
`BUILDER_TEMPLATES_DIR is set to "${envVal}" but directory does not exist or lacks a "docker/" subdirectory (resolved: "${envDir}").`
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
return envDir;
|
|
228
195
|
}
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
196
|
+
if (cachedTemplatesDir && fs.existsSync(cachedTemplatesDir)) {
|
|
197
|
+
return cachedTemplatesDir;
|
|
198
|
+
}
|
|
199
|
+
const currentDir = typeof __dirname !== "undefined" ? __dirname : path4.dirname(fileURLToPath(import.meta.url));
|
|
200
|
+
const candidates = [
|
|
201
|
+
// When executing compiled output in dist/ (e.g. dist/templates)
|
|
202
|
+
path4.resolve(currentDir, "templates"),
|
|
203
|
+
path4.resolve(currentDir, "../templates"),
|
|
204
|
+
// When executing from src/ (e.g. src/core/templates.ts -> ../../templates)
|
|
205
|
+
path4.resolve(currentDir, "../../templates"),
|
|
206
|
+
// Fallback relative to cwd
|
|
207
|
+
path4.resolve(process.cwd(), "templates")
|
|
208
|
+
];
|
|
209
|
+
for (const cand of candidates) {
|
|
210
|
+
if (fs.existsSync(cand) && fs.existsSync(path4.join(cand, "docker"))) {
|
|
211
|
+
cachedTemplatesDir = cand;
|
|
212
|
+
return cand;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
throw new ScriptError(
|
|
216
|
+
`Templates directory not found. Searched candidates:
|
|
217
|
+
${candidates.join("\n")}`
|
|
250
218
|
);
|
|
251
219
|
}
|
|
252
|
-
function
|
|
220
|
+
function getDockerComposeTemplate(filename) {
|
|
221
|
+
const templatesDir = getTemplatesDir();
|
|
222
|
+
const filePath = path4.join(templatesDir, "docker", filename);
|
|
223
|
+
if (!fs.existsSync(filePath)) {
|
|
224
|
+
throw new ScriptError(`Docker compose template not found: ${filePath}`);
|
|
225
|
+
}
|
|
226
|
+
return filePath;
|
|
227
|
+
}
|
|
228
|
+
function getDockerfilePolicyDir() {
|
|
229
|
+
const policyDir = path4.join(getTemplatesDir(), "policy", "dockerfile");
|
|
230
|
+
if (!fs.existsSync(path4.join(policyDir, "dockerfile.rego"))) throw new ScriptError(`Builder Dockerfile policy not found: ${policyDir}`);
|
|
231
|
+
return policyDir;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// src/core/checkers/checkDockerfileContract.ts
|
|
235
|
+
function checkDockerfileContract(build, projectDir) {
|
|
236
|
+
const root = resolveProjectDir(projectDir);
|
|
237
|
+
const relative = build.dockerfile ?? "Dockerfile";
|
|
238
|
+
const dockerfile = path4.resolve(root, relative);
|
|
239
|
+
if (!isPathInside(root, dockerfile) || !existsSync(dockerfile)) throw new ConfigError({ sourceFile: path4.join(root, "build.json"), configPath: "dockerfile", value: relative, composition: "service", reason: "Application Dockerfile missing or outside project" });
|
|
240
|
+
const policyDir = getDockerfilePolicyDir();
|
|
241
|
+
console.log(pc22.cyan(`
|
|
242
|
+
\u{1F50D} Validating Builder Dockerfile contract (${relative})...`));
|
|
243
|
+
runStep("docker", ["run", "--rm", "--network", "none", "--mount", `type=bind,src=${root},dst=/project,readonly`, "--mount", `type=bind,src=${policyDir},dst=/builder-policy,readonly`, "-w", "/project", CONFTEST_IMAGE, "test", relative, "-p", "/builder-policy"], root, { stepName: "Dockerfile Contract", targetFile: relative });
|
|
244
|
+
}
|
|
245
|
+
function resolveInsideProject(projectDir, relativePath, context) {
|
|
246
|
+
if (!relativePath.trim()) throw new ConfigError({ ...context, value: relativePath, reason: "Path must not be empty" });
|
|
247
|
+
const resolved = path4.resolve(projectDir, relativePath);
|
|
248
|
+
if (!isPathInside(projectDir, relativePath)) throw new ConfigError({ ...context, value: relativePath, reason: "Path escapes the project directory" });
|
|
249
|
+
return resolved;
|
|
250
|
+
}
|
|
251
|
+
function loadComposeDocument(absolutePath, context) {
|
|
252
|
+
const fail = (reason, value) => {
|
|
253
|
+
throw new ConfigError({ ...context, sourceFile: absolutePath, ...{} , reason });
|
|
254
|
+
};
|
|
255
|
+
if (!existsSync(absolutePath) || !statSync(absolutePath).isFile()) fail("Compose file does not exist or is not a regular file");
|
|
256
|
+
let text = "";
|
|
257
|
+
try {
|
|
258
|
+
text = readFileSync(absolutePath, "utf8");
|
|
259
|
+
} catch (e) {
|
|
260
|
+
fail(`Failed to read Compose file: ${String(e)}`);
|
|
261
|
+
}
|
|
262
|
+
let docs = [];
|
|
263
|
+
try {
|
|
264
|
+
docs = parseAllDocuments(text, { prettyErrors: true });
|
|
265
|
+
} catch (e) {
|
|
266
|
+
fail(`Invalid Compose YAML: ${String(e)}`);
|
|
267
|
+
}
|
|
268
|
+
if (docs.length !== 1) fail("Compose file must contain exactly one YAML document");
|
|
269
|
+
const errors = docs[0].errors;
|
|
270
|
+
if (errors.length) fail(`Invalid Compose YAML: ${errors.map((e) => e.message).join("; ")}`);
|
|
271
|
+
let parsed;
|
|
272
|
+
try {
|
|
273
|
+
parsed = parse(text);
|
|
274
|
+
} catch (e) {
|
|
275
|
+
fail(`Invalid Compose YAML: ${String(e)}`);
|
|
276
|
+
}
|
|
277
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) fail("Compose root must be an object");
|
|
278
|
+
return parsed;
|
|
279
|
+
}
|
|
280
|
+
function getDeclaredYamlFiles(build, projectDir) {
|
|
253
281
|
const files = [];
|
|
254
282
|
const seen = /* @__PURE__ */ new Set();
|
|
255
|
-
const
|
|
256
|
-
const
|
|
257
|
-
if (seen.has(
|
|
258
|
-
seen.add(
|
|
259
|
-
files.push({
|
|
260
|
-
relativePath: relPath,
|
|
261
|
-
absolutePath: path13.resolve(projectDir, relPath),
|
|
262
|
-
source
|
|
263
|
-
});
|
|
283
|
+
const add = (relativePath, source, kind, stage) => {
|
|
284
|
+
const absolutePath = path4.resolve(projectDir, relativePath);
|
|
285
|
+
if (seen.has(absolutePath)) return;
|
|
286
|
+
seen.add(absolutePath);
|
|
287
|
+
files.push({ relativePath, absolutePath, source, kind, ...stage ? { stage } : {} });
|
|
264
288
|
};
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
289
|
+
for (const [name, dep] of Object.entries(build.dependencies ?? {})) add(dep.compose, `dependencies.${name}.compose`, "dependency-compose");
|
|
290
|
+
for (const stage of ["dev", "prod", "test", "e2e"]) {
|
|
291
|
+
const overlay = build[stage];
|
|
292
|
+
if (overlay?.["override-compose"]) add(overlay["override-compose"], `${stage}.override-compose`, "override-compose", stage);
|
|
293
|
+
for (const [name, dep] of Object.entries(overlay?.dependencies ?? {})) if (dep.compose) add(dep.compose, `${stage}.dependencies.${name}.compose`, "dependency-compose", stage);
|
|
294
|
+
}
|
|
295
|
+
return files;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// src/core/checkers/checkYamlFiles.ts
|
|
299
|
+
function checkYamlFiles(build, projectDir) {
|
|
300
|
+
const root = resolveProjectDir(projectDir);
|
|
301
|
+
const files = getDeclaredYamlFiles(build, root);
|
|
302
|
+
if (files.length) console.log(pc22.cyan(`
|
|
303
|
+
\u{1F50D} Validating ${files.length} declared V2 Compose file(s)...`));
|
|
304
|
+
for (const file of files) {
|
|
305
|
+
const absolutePath = resolveInsideProject(root, file.relativePath, { sourceFile: `${root}/build.json`, configPath: file.source, ...file.stage ? { stage: file.stage } : {} });
|
|
306
|
+
loadComposeDocument(absolutePath, { sourceFile: `${root}/build.json`, configPath: file.source, stage: file.stage ?? "base", composition: "service" });
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// src/core/config/endpointProperties.ts
|
|
311
|
+
function resolveEndpointProperty(endpoint, property, context) {
|
|
312
|
+
const published = () => {
|
|
313
|
+
if (!endpoint.effectivelyPublished || endpoint.publicHost === void 0 || endpoint.publicPort === void 0) throw new ConfigError({ ...context, configPath: context.configPath, referencedObject: endpoint.logicalPath, reason: `Endpoint property ${property} requires effective publication` });
|
|
314
|
+
};
|
|
315
|
+
const scheme = () => {
|
|
316
|
+
if (!endpoint.scheme) throw new ConfigError({ ...context, referencedObject: endpoint.logicalPath, reason: `Endpoint property ${property} requires an endpoint scheme` });
|
|
317
|
+
return endpoint.scheme;
|
|
318
|
+
};
|
|
319
|
+
switch (property) {
|
|
320
|
+
case "network_host":
|
|
321
|
+
return endpoint.networkHost;
|
|
322
|
+
case "network_port":
|
|
323
|
+
return String(endpoint.networkPort);
|
|
324
|
+
case "network_address":
|
|
325
|
+
return `${endpoint.networkHost}:${endpoint.networkPort}`;
|
|
326
|
+
case "network_url":
|
|
327
|
+
return `${scheme()}://${endpoint.networkHost}:${endpoint.networkPort}`;
|
|
328
|
+
case "public_host":
|
|
329
|
+
published();
|
|
330
|
+
return endpoint.publicHost;
|
|
331
|
+
case "public_port":
|
|
332
|
+
published();
|
|
333
|
+
return String(endpoint.publicPort);
|
|
334
|
+
case "public_address":
|
|
335
|
+
published();
|
|
336
|
+
return `${endpoint.publicHost}:${endpoint.publicPort}`;
|
|
337
|
+
case "public_url":
|
|
338
|
+
published();
|
|
339
|
+
return `${scheme()}://${endpoint.publicHost}:${endpoint.publicPort}`;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
function assertPrimaryEndpointInvariant(endpoints, context) {
|
|
343
|
+
const primaries = Object.entries(endpoints).filter(([, e]) => e.primary === true);
|
|
344
|
+
if (Object.keys(endpoints).length && primaries.length !== 1) throw new ConfigError({ ...context, value: primaries.map(([n]) => n), reason: `Expected exactly one primary endpoint; found ${primaries.length}` });
|
|
345
|
+
}
|
|
346
|
+
function getPrimaryEndpoint(endpoints) {
|
|
347
|
+
return Object.entries(endpoints).find(([, endpoint]) => endpoint.primary === true);
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// src/core/config/lifecycleGraph.ts
|
|
351
|
+
function assertAcyclicGraph(graph, context) {
|
|
352
|
+
const visiting = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set(), stack = [];
|
|
353
|
+
const visit = (node) => {
|
|
354
|
+
if (visiting.has(node)) {
|
|
355
|
+
const start = stack.indexOf(node);
|
|
356
|
+
const cycle = [...stack.slice(start), node];
|
|
357
|
+
throw new ConfigError({ ...context, configPath: "dependsOn", referencedObject: cycle.join(" -> "), reason: `Lifecycle cycle detected: ${cycle.join(" -> ")}` });
|
|
358
|
+
}
|
|
359
|
+
if (visited.has(node)) return;
|
|
360
|
+
visiting.add(node);
|
|
361
|
+
stack.push(node);
|
|
362
|
+
for (const next of graph.get(node) ?? []) visit(next);
|
|
363
|
+
stack.pop();
|
|
364
|
+
visiting.delete(node);
|
|
365
|
+
visited.add(node);
|
|
366
|
+
};
|
|
367
|
+
for (const node of graph.keys()) visit(node);
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// src/core/config/stageMerge.ts
|
|
371
|
+
function unionStable(base = [], overlay = []) {
|
|
372
|
+
return [.../* @__PURE__ */ new Set([...base, ...overlay])];
|
|
373
|
+
}
|
|
374
|
+
function mergeStringMap(base, overlay) {
|
|
375
|
+
return { ...base ?? {}, ...overlay ?? {} };
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// src/core/config/resolveBuildStage.ts
|
|
379
|
+
function resolveBuildStage(build, stage, sourceFile) {
|
|
380
|
+
const overlay = build[stage] ?? {};
|
|
381
|
+
const appEndpoints = structuredClone(build.app.endpoints ?? {});
|
|
382
|
+
for (const [name, endpoint] of Object.entries(overlay.app?.endpoints ?? {})) appEndpoints[name] = { ...appEndpoints[name] ?? {}, ...endpoint };
|
|
383
|
+
const dependencies = {};
|
|
384
|
+
for (const [name, dep] of Object.entries(build.dependencies ?? {})) dependencies[name] = { ...dep, env: { ...dep.env ?? {} }, endpoints: structuredClone(dep.endpoints ?? {}), dependsOn: [...dep.dependsOn ?? []] };
|
|
385
|
+
for (const [name, patch] of Object.entries(overlay.dependencies ?? {})) {
|
|
386
|
+
const prior = dependencies[name] ?? { compose: void 0, env: {}, endpoints: {}, dependsOn: [] };
|
|
387
|
+
prior.compose = patch.compose ?? prior.compose;
|
|
388
|
+
prior.env = mergeStringMap(prior.env, patch.env);
|
|
389
|
+
for (const [ep, epPatch] of Object.entries(patch.endpoints ?? {})) prior.endpoints[ep] = { ...prior.endpoints[ep] ?? {}, ...epPatch };
|
|
390
|
+
prior.dependsOn = unionStable(prior.dependsOn, patch.dependsOn);
|
|
391
|
+
dependencies[name] = prior;
|
|
392
|
+
}
|
|
393
|
+
const effective = { ...build, app: { env: mergeStringMap(build.app.env, overlay.app?.env), endpoints: appEndpoints }, dependencies, tester: build.tester ? { env: { ...build.tester.env ?? {} } } : void 0, overrideCompose: overlay["override-compose"] };
|
|
394
|
+
delete effective.dev;
|
|
395
|
+
delete effective.prod;
|
|
396
|
+
delete effective.test;
|
|
397
|
+
delete effective.e2e;
|
|
398
|
+
const context = (configPath, value, reason, referencedObject) => new ConfigError({ sourceFile, configPath, stage, composition: "service", value, ...referencedObject ? { referencedObject } : {}, reason });
|
|
399
|
+
for (const [name, ep] of Object.entries(appEndpoints)) if (!Number.isInteger(ep.port) || ep.port < 1 || ep.port > 65535) throw context(`app.endpoints.${name}.port`, ep.port, "Effective endpoint requires a port in 1..65535");
|
|
400
|
+
assertPrimaryEndpointInvariant(appEndpoints, { sourceFile, configPath: "app.endpoints", stage });
|
|
401
|
+
const graph = /* @__PURE__ */ new Map();
|
|
402
|
+
for (const [name, dep] of Object.entries(dependencies)) {
|
|
403
|
+
if (typeof dep.compose !== "string" || !dep.compose.trim()) throw context(`dependencies.${name}.compose`, dep.compose, "Effective dependency requires compose");
|
|
404
|
+
const endpoints = Object.entries(dep.endpoints);
|
|
405
|
+
for (const [epName, ep] of endpoints) if (!ep.service || !Number.isInteger(ep.port) || ep.port < 1 || ep.port > 65535) throw context(`dependencies.${name}.endpoints.${epName}`, ep, "Effective dependency endpoint requires service and port");
|
|
406
|
+
assertPrimaryEndpointInvariant(dep.endpoints, { sourceFile, configPath: `dependencies.${name}.endpoints`, stage });
|
|
407
|
+
const node = `dependencies.${name}`;
|
|
408
|
+
graph.set(node, /* @__PURE__ */ new Set());
|
|
409
|
+
for (const ref of dep.dependsOn) {
|
|
410
|
+
const match = DEPENDENCY_REFERENCE_PATTERN.exec(ref);
|
|
411
|
+
if (!match) throw context(`dependencies.${name}.dependsOn`, ref, "Expected dependencies.<name> lifecycle reference", ref);
|
|
412
|
+
const targetName = match[1];
|
|
413
|
+
if (targetName === name) throw context(`dependencies.${name}.dependsOn`, ref, "Dependency cannot depend on itself", ref);
|
|
414
|
+
const target = dependencies[targetName];
|
|
415
|
+
if (!target) throw context(`dependencies.${name}.dependsOn`, ref, "Unknown dependency", ref);
|
|
416
|
+
if (!Object.keys(target.endpoints).length) throw context(`dependencies.${name}.dependsOn`, ref, "Lifecycle target is inert and has no endpoints", ref);
|
|
417
|
+
graph.get(node).add(`dependencies.${targetName}`);
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
assertAcyclicGraph(graph, { sourceFile, stage, composition: "service" });
|
|
421
|
+
return effective;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
// src/core/config/references.ts
|
|
425
|
+
var BUILD_APP = /^app\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
|
|
426
|
+
var BUILD_DEP = /^dependencies\.([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
|
|
427
|
+
var MESH_APP = /^([a-z][a-z0-9-]*)\.app\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
|
|
428
|
+
var MESH_DEP = /^([a-z][a-z0-9-]*)\.dependencies\.([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
|
|
429
|
+
function parse2(raw, scope, sourcePath) {
|
|
430
|
+
let m;
|
|
431
|
+
if (scope === "build" && (m = BUILD_APP.exec(raw))) return valid({ raw, scope, target: "app", endpoint: m[1], property: m[2] }, sourcePath);
|
|
432
|
+
if (scope === "build" && (m = BUILD_DEP.exec(raw))) return valid({ raw, scope, target: "dependency", dependency: m[1], endpoint: m[2], property: m[3] }, sourcePath);
|
|
433
|
+
if (scope === "mesh" && (m = MESH_APP.exec(raw))) return valid({ raw, scope, meshService: m[1], target: "app", endpoint: m[2], property: m[3] }, sourcePath);
|
|
434
|
+
if (scope === "mesh" && (m = MESH_DEP.exec(raw))) return valid({ raw, scope, meshService: m[1], target: "dependency", dependency: m[2], endpoint: m[3], property: m[4] }, sourcePath);
|
|
435
|
+
throw new ConfigError({ configPath: sourcePath, value: raw, reason: `Invalid ${scope} endpoint reference` });
|
|
436
|
+
}
|
|
437
|
+
function valid(ref, sourcePath) {
|
|
438
|
+
if (!ENDPOINT_PROPERTIES.includes(ref.property)) throw new ConfigError({ configPath: sourcePath, value: ref.property, reason: "Unknown endpoint property" });
|
|
439
|
+
return ref;
|
|
440
|
+
}
|
|
441
|
+
function collectBuilderReferences(value, scope, sourcePath) {
|
|
442
|
+
const protectedValue = value.replace(/\$\$/g, "\0DOLLAR\0"), refs2 = [];
|
|
443
|
+
for (const match of protectedValue.matchAll(/\$\{([^}]*)\}/g)) refs2.push(parse2(match[1], scope, sourcePath));
|
|
444
|
+
return refs2;
|
|
445
|
+
}
|
|
446
|
+
function interpolateBuilderReferences(value, scope, resolve) {
|
|
447
|
+
const sentinel = "\0DOLLAR\0";
|
|
448
|
+
return value.replace(/\$\$/g, sentinel).replace(/\$\{([^}]*)\}/g, (whole, body) => resolve(parse2(body, scope, "environment"))).replaceAll(sentinel, "$");
|
|
449
|
+
}
|
|
450
|
+
function assertTesterReferencesArePublic(env, scope, sourcePrefix) {
|
|
451
|
+
for (const [key, value] of Object.entries(env)) for (const ref of collectBuilderReferences(value, scope, `${sourcePrefix}.${key}`)) if (!PUBLIC_ENDPOINT_PROPERTIES.has(ref.property)) throw new ConfigError({ configPath: `${sourcePrefix}.${key}`, value: ref.raw, reason: "Tester references may use only public endpoint properties" });
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// src/errors/PortConflictError.ts
|
|
455
|
+
var PortConflictError = class extends ConfigError {
|
|
456
|
+
port;
|
|
457
|
+
firstOwner;
|
|
458
|
+
secondOwner;
|
|
459
|
+
constructor(port, firstOwner, secondOwner, stage) {
|
|
460
|
+
super({ sourceFile: "Builder effective composition", configPath: "publicPort", value: port, stage, reason: `Host port ${port} is claimed by both ${firstOwner} and ${secondOwner}. Builder does not remap fixed public ports.` });
|
|
461
|
+
this.name = "PortConflictError";
|
|
462
|
+
this.port = port;
|
|
463
|
+
this.firstOwner = firstOwner;
|
|
464
|
+
this.secondOwner = secondOwner;
|
|
465
|
+
}
|
|
466
|
+
};
|
|
467
|
+
|
|
468
|
+
// src/core/config/hostPorts.ts
|
|
469
|
+
function isHostPortAvailableSync(port) {
|
|
470
|
+
const script = `const net=require('node:net');const s=net.createServer();s.once('error',()=>process.exit(1));s.listen(${port},'${PUBLIC_HOST}',()=>s.close(()=>process.exit(0)));`;
|
|
471
|
+
const result = spawnSync(process.execPath, ["-e", script], { stdio: "ignore", timeout: 3e3 });
|
|
472
|
+
return result.status === 0;
|
|
473
|
+
}
|
|
474
|
+
function allocateHostPorts(projectDir, stage, intentsInDeterministicOrder, validationMode = false) {
|
|
475
|
+
const reserved = /* @__PURE__ */ new Map(), allocated = /* @__PURE__ */ new Map();
|
|
476
|
+
for (const intent of intentsInDeterministicOrder) if (typeof intent.requested === "number") {
|
|
477
|
+
const owner = reserved.get(intent.requested);
|
|
478
|
+
if (owner) throw new PortConflictError(intent.requested, owner, intent.logicalPath, stage);
|
|
479
|
+
reserved.set(intent.requested, intent.logicalPath);
|
|
480
|
+
allocated.set(intent.logicalPath, intent.requested);
|
|
481
|
+
}
|
|
482
|
+
if (validationMode) {
|
|
483
|
+
let placeholder = 6e4;
|
|
484
|
+
for (const intent of intentsInDeterministicOrder) if (intent.requested === "AUTO") {
|
|
485
|
+
while (reserved.has(placeholder)) placeholder--;
|
|
486
|
+
if (placeholder < 1) throw new ConfigError({ configPath: intent.logicalPath, stage, reason: "No validation placeholder port is available" });
|
|
487
|
+
reserved.set(placeholder, intent.logicalPath);
|
|
488
|
+
allocated.set(intent.logicalPath, placeholder--);
|
|
489
|
+
}
|
|
490
|
+
return allocated;
|
|
491
|
+
}
|
|
492
|
+
const cachePath = path4.join(projectDir, AUTO_PORT_CACHE_RELATIVE_PATH);
|
|
493
|
+
let cached = {};
|
|
494
|
+
try {
|
|
495
|
+
if (existsSync(cachePath)) {
|
|
496
|
+
const parsed = JSON.parse(readFileSync(cachePath, "utf8"));
|
|
497
|
+
if (parsed && typeof parsed === "object" && parsed.version === AUTO_PORT_CACHE_VERSION && parsed.allocations && typeof parsed.allocations === "object") cached = parsed.allocations;
|
|
270
498
|
}
|
|
499
|
+
} catch {
|
|
500
|
+
cached = {};
|
|
271
501
|
}
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
502
|
+
const nextCache = { ...cached };
|
|
503
|
+
for (const intent of intentsInDeterministicOrder) if (intent.requested === "AUTO") {
|
|
504
|
+
const prior = cached[intent.logicalPath];
|
|
505
|
+
let selected = typeof prior === "number" && Number.isInteger(prior) && prior >= 1 && prior <= 65535 && !reserved.has(prior) && isHostPortAvailableSync(prior) ? prior : void 0;
|
|
506
|
+
if (selected === void 0) {
|
|
507
|
+
const scan = [...Array(65536 - AUTO_PORT_SCAN_START).keys()].map((i) => i + AUTO_PORT_SCAN_START).concat([...Array(19999 - 1024 + 1).keys()].map((i) => i + 1024));
|
|
508
|
+
selected = scan.find((p) => !reserved.has(p) && isHostPortAvailableSync(p));
|
|
277
509
|
}
|
|
510
|
+
if (selected === void 0) throw new ConfigError({ sourceFile: "Builder effective composition", configPath: intent.logicalPath, stage, reason: "No available host port could be allocated" });
|
|
511
|
+
reserved.set(selected, intent.logicalPath);
|
|
512
|
+
allocated.set(intent.logicalPath, selected);
|
|
513
|
+
nextCache[intent.logicalPath] = selected;
|
|
278
514
|
}
|
|
279
|
-
if (
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
515
|
+
if (intentsInDeterministicOrder.some((i) => i.requested === "AUTO")) {
|
|
516
|
+
mkdirSync(path4.dirname(cachePath), { recursive: true });
|
|
517
|
+
const temp = `${cachePath}.${process.pid}.tmp`;
|
|
518
|
+
writeFileSync(temp, JSON.stringify({ version: AUTO_PORT_CACHE_VERSION, allocations: nextCache }, null, 2));
|
|
519
|
+
renameSync(temp, cachePath);
|
|
520
|
+
}
|
|
521
|
+
return allocated;
|
|
522
|
+
}
|
|
523
|
+
function normalizeProjectName(name, projectDir) {
|
|
524
|
+
let normalized = name.toLowerCase().replace(/[^a-z0-9_-]/g, "-").replace(/^[-_]+/, "").replace(/[-_]+$/, "");
|
|
525
|
+
if (!normalized || !/^[a-z0-9]/.test(normalized)) {
|
|
526
|
+
if (projectDir) {
|
|
527
|
+
const hash = crypto.createHash("sha1").update(path4.resolve(projectDir)).digest("hex").slice(0, 7);
|
|
528
|
+
return `project-${hash}`;
|
|
284
529
|
}
|
|
530
|
+
return "project";
|
|
285
531
|
}
|
|
286
|
-
return
|
|
532
|
+
return normalized;
|
|
287
533
|
}
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
if (declaredFiles.length === 0) {
|
|
294
|
-
return;
|
|
534
|
+
function deriveProjectName(name, stage, projectDir, options = {}) {
|
|
535
|
+
let base = normalizeProjectName(name, projectDir);
|
|
536
|
+
if (options.hash && projectDir) {
|
|
537
|
+
const hash = crypto.createHash("sha1").update(path4.resolve(projectDir)).digest("hex").slice(0, 7);
|
|
538
|
+
base = `${base}-${hash}`;
|
|
295
539
|
}
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
540
|
+
if (!stage) {
|
|
541
|
+
return base;
|
|
542
|
+
}
|
|
543
|
+
const s = stage.toLowerCase();
|
|
544
|
+
if (s === "dev") {
|
|
545
|
+
return base;
|
|
546
|
+
}
|
|
547
|
+
if (s === "prod") {
|
|
548
|
+
return `${base}-prod`;
|
|
549
|
+
}
|
|
550
|
+
if (s === "test" || s === "test-unit") {
|
|
551
|
+
return `${base}-test`;
|
|
552
|
+
}
|
|
553
|
+
if (s === "e2e" || s === "test-e2e") {
|
|
554
|
+
return `${base}-e2e`;
|
|
555
|
+
}
|
|
556
|
+
return `${base}-${s}`;
|
|
557
|
+
}
|
|
558
|
+
var posix = (p) => p.replace(/\\/g, "/");
|
|
559
|
+
function rebase(p, base, out) {
|
|
560
|
+
if (path4.isAbsolute(p) || /^[A-Za-z]:[\\/]/.test(p)) return posix(path4.normalize(p));
|
|
561
|
+
const abs = path4.resolve(base, p);
|
|
562
|
+
const rel = path4.relative(out, abs);
|
|
563
|
+
const result = posix(isPathInside(out, rel) ? rel || "." : abs);
|
|
564
|
+
return result !== "." && !result.startsWith(".") && !path4.isAbsolute(result) ? `./${result}` : result;
|
|
565
|
+
}
|
|
566
|
+
function volumeShort(v, base, out) {
|
|
567
|
+
const parts = v.split(":");
|
|
568
|
+
if (parts.length < 2) return v;
|
|
569
|
+
const source = parts[0];
|
|
570
|
+
if (source === "" || source.startsWith("/") || source.startsWith("~") || /^[A-Za-z]:[\\/]/.test(source)) return v;
|
|
571
|
+
if (source.startsWith(".") || source.includes("/") || source.includes("\\")) parts[0] = rebase(source, base, out);
|
|
572
|
+
return parts.join(":");
|
|
573
|
+
}
|
|
574
|
+
function rebaseComposePaths(document, composeFilePath, outputProjectDir) {
|
|
575
|
+
const doc = structuredClone(document), base = path4.dirname(composeFilePath), out = path4.resolve(outputProjectDir);
|
|
576
|
+
for (const svc of Object.values(doc.services ?? {})) {
|
|
577
|
+
if (typeof svc.build === "string") svc.build = rebase(svc.build, base, out);
|
|
578
|
+
else if (svc.build && typeof svc.build === "object") {
|
|
579
|
+
const b = svc.build;
|
|
580
|
+
const context = typeof b.context === "string" ? b.context : ".";
|
|
581
|
+
b.context = rebase(context, base, out);
|
|
582
|
+
}
|
|
583
|
+
if (typeof svc.env_file === "string") svc.env_file = rebase(svc.env_file, base, out);
|
|
584
|
+
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);
|
|
585
|
+
if (Array.isArray(svc.volumes)) svc.volumes = svc.volumes.map((v) => typeof v === "string" ? volumeShort(v, base, out) : v && typeof v === "object" && v.type === "bind" && typeof v.source === "string" ? { ...v, source: rebase(v.source, base, out) } : v);
|
|
586
|
+
}
|
|
587
|
+
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);
|
|
588
|
+
return doc;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
// src/core/composition/composeEnvironment.ts
|
|
592
|
+
function normalizeComposeEnvironment(value, context) {
|
|
593
|
+
const result = {};
|
|
594
|
+
if (value == null) return result;
|
|
595
|
+
if (Array.isArray(value)) {
|
|
596
|
+
for (const item of value) {
|
|
597
|
+
if (typeof item !== "string") throw new ConfigError({ configPath: context, value: item, reason: "Compose environment entries must be strings" });
|
|
598
|
+
const at = item.indexOf("=");
|
|
599
|
+
if (at < 0) {
|
|
600
|
+
result[item] = process.env[item] ?? "";
|
|
601
|
+
continue;
|
|
319
602
|
}
|
|
320
|
-
|
|
321
|
-
const msg = errorMessage(err);
|
|
322
|
-
errors.push(
|
|
323
|
-
`YAML Syntax Error in "${file.relativePath}" (${file.source}): ${msg}`
|
|
324
|
-
);
|
|
603
|
+
result[item.slice(0, at)] = item.slice(at + 1);
|
|
325
604
|
}
|
|
605
|
+
return result;
|
|
326
606
|
}
|
|
327
|
-
if (
|
|
328
|
-
|
|
607
|
+
if (typeof value !== "object") throw new ConfigError({ configPath: context, value, reason: "Compose environment must be a map or list" });
|
|
608
|
+
for (const [key, val] of Object.entries(value)) {
|
|
609
|
+
if (val === null || val === void 0) continue;
|
|
610
|
+
if (typeof val === "object") throw new ConfigError({ configPath: `${context}.${key}`, value: val, reason: "Compose environment value must be scalar" });
|
|
611
|
+
result[key] = String(val);
|
|
329
612
|
}
|
|
613
|
+
return result;
|
|
330
614
|
}
|
|
331
|
-
function
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
615
|
+
function mergeComposeEnvironment(service, overlay) {
|
|
616
|
+
service.environment = { ...normalizeComposeEnvironment(service.environment, "service.environment"), ...overlay };
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
// src/core/composition/namespaceDependencyCompose.ts
|
|
620
|
+
var entries = (obj) => obj && typeof obj === "object" && !Array.isArray(obj) ? Object.entries(obj) : [];
|
|
621
|
+
function namespaceDependencyCompose(options) {
|
|
622
|
+
const { document, namespacePrefix: prefix } = options, doc = structuredClone(document);
|
|
623
|
+
const make = (kind, keys) => new Map(keys.map((k) => [k, `${prefix}--${kind}--${k}`]));
|
|
624
|
+
const serviceNameMap = make("", Object.keys(doc.services ?? {}));
|
|
625
|
+
for (const [k, v] of serviceNameMap) serviceNameMap.set(k, `${prefix}--${k}`);
|
|
626
|
+
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 ?? {}));
|
|
627
|
+
const rewriteKeys = (obj, map) => Object.fromEntries(entries(obj).map(([k, v]) => [map.get(k) ?? k, v]));
|
|
628
|
+
const rewriteResourceRefs = (svc) => {
|
|
629
|
+
if (Array.isArray(svc.depends_on)) {
|
|
630
|
+
svc.depends_on = svc.depends_on.map((v) => typeof v === "string" ? serviceNameMap.get(v) ?? v : v);
|
|
631
|
+
} else if (svc.depends_on && typeof svc.depends_on === "object") svc.depends_on = rewriteKeys(svc.depends_on, serviceNameMap);
|
|
632
|
+
if (Array.isArray(svc.links)) svc.links = svc.links.map((v) => {
|
|
633
|
+
if (typeof v !== "string") return v;
|
|
634
|
+
const [name, ...rest] = v.split(":");
|
|
635
|
+
return [serviceNameMap.get(name) ?? name, ...rest].join(":");
|
|
636
|
+
});
|
|
637
|
+
if (typeof svc.network_mode === "string" && svc.network_mode.startsWith("service:")) {
|
|
638
|
+
const key = svc.network_mode.slice(8);
|
|
639
|
+
svc.network_mode = `service:${serviceNameMap.get(key) ?? key}`;
|
|
640
|
+
}
|
|
641
|
+
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);
|
|
642
|
+
if (Array.isArray(svc.volumes)) svc.volumes = svc.volumes.map((v) => {
|
|
643
|
+
if (typeof v !== "string") return v;
|
|
644
|
+
const [src, ...rest] = v.split(":");
|
|
645
|
+
const mapped = volumeNameMap.get(src);
|
|
646
|
+
return mapped ? [mapped, ...rest].join(":") : v;
|
|
647
|
+
});
|
|
648
|
+
if (svc.volumes && Array.isArray(svc.volumes)) svc.volumes = svc.volumes.map((v) => v && typeof v === "object" && v.type === "volume" ? { ...v, source: volumeNameMap.get(v.source) ?? v.source } : v);
|
|
649
|
+
if (Array.isArray(svc.networks)) svc.networks = svc.networks.map((v) => typeof v === "string" ? networkNameMap.get(v) ?? v : v);
|
|
650
|
+
else if (svc.networks && typeof svc.networks === "object") svc.networks = rewriteKeys(svc.networks, networkNameMap);
|
|
651
|
+
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);
|
|
652
|
+
};
|
|
653
|
+
for (const svc of Object.values(doc.services ?? {})) rewriteResourceRefs(svc);
|
|
654
|
+
doc.services = rewriteKeys(doc.services, serviceNameMap);
|
|
655
|
+
if (doc.volumes) doc.volumes = rewriteKeys(doc.volumes, volumeNameMap);
|
|
656
|
+
if (doc.networks) doc.networks = rewriteKeys(doc.networks, networkNameMap);
|
|
657
|
+
if (doc.configs) doc.configs = rewriteKeys(doc.configs, configNameMap);
|
|
658
|
+
if (doc.secrets) doc.secrets = rewriteKeys(doc.secrets, secretNameMap);
|
|
659
|
+
return { document: doc, serviceNameMap, volumeNameMap, networkNameMap, configNameMap, secretNameMap };
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
// src/core/composition/validateDependencyCompose.ts
|
|
663
|
+
function validateDependencyCompose(dependencyKey, dependency, document, context) {
|
|
664
|
+
const fail = (configPath, reason, value) => {
|
|
665
|
+
throw new ConfigError({ sourceFile: context.composePath, configPath, stage: context.stage, composition: "service", ...value === void 0 ? {} : { value }, reason: `Dependency "${dependencyKey}": ${reason}` });
|
|
666
|
+
};
|
|
667
|
+
if (document.include !== void 0) fail("include", "Compose include is unsupported for atomic dependency implementations");
|
|
668
|
+
const services = document.services ?? {};
|
|
669
|
+
for (const [name, svc] of Object.entries(services)) {
|
|
670
|
+
if (svc.ports !== void 0) fail(`services.${name}.ports`, "raw dependency ports are forbidden");
|
|
671
|
+
if (svc.network_mode === "host") fail(`services.${name}.network_mode`, "host network mode is forbidden");
|
|
672
|
+
if (svc.privileged === true) fail(`services.${name}.privileged`, `privileged services are forbidden`);
|
|
673
|
+
if (svc.container_name !== void 0) fail(`services.${name}.container_name`, `fixed container_name is forbidden`);
|
|
674
|
+
for (const v of Array.isArray(svc.volumes) ? svc.volumes : []) {
|
|
675
|
+
const source = typeof v === "string" ? v.split(":")[0] : v && typeof v === "object" ? v.source : void 0;
|
|
676
|
+
if (typeof source === "string" && source.replaceAll("\\", "/") === "/") fail(`services.${name}.volumes`, `host root bind mounts are forbidden`, v);
|
|
677
|
+
}
|
|
678
|
+
const internalRefs = [];
|
|
679
|
+
if (Array.isArray(svc.depends_on)) {
|
|
680
|
+
for (const ref of svc.depends_on) if (typeof ref === "string") internalRefs.push(["depends_on", ref]);
|
|
681
|
+
} else if (svc.depends_on && typeof svc.depends_on === "object") {
|
|
682
|
+
for (const ref of Object.keys(svc.depends_on)) internalRefs.push(["depends_on", ref]);
|
|
683
|
+
}
|
|
684
|
+
if (Array.isArray(svc.links)) {
|
|
685
|
+
for (const ref of svc.links) if (typeof ref === "string") internalRefs.push(["links", ref.split(":")[0]]);
|
|
686
|
+
}
|
|
687
|
+
if (typeof svc.network_mode === "string" && svc.network_mode.startsWith("service:")) internalRefs.push(["network_mode", svc.network_mode.slice(8)]);
|
|
688
|
+
if (Array.isArray(svc.volumes_from)) {
|
|
689
|
+
for (const ref of svc.volumes_from) if (typeof ref === "string") internalRefs.push(["volumes_from", ref.split(":")[0]]);
|
|
690
|
+
}
|
|
691
|
+
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);
|
|
336
692
|
}
|
|
337
|
-
|
|
338
|
-
if (!
|
|
339
|
-
|
|
693
|
+
if (!Object.keys(dependency.endpoints).length) return;
|
|
694
|
+
if (!Object.keys(services).length) fail("services", "endpoint-bearing dependency Compose must define services");
|
|
695
|
+
const owners = /* @__PURE__ */ new Set();
|
|
696
|
+
for (const [endpoint, definition] of Object.entries(dependency.endpoints)) {
|
|
697
|
+
const owner = definition.service;
|
|
698
|
+
if (!services[owner]) fail(`endpoints.${endpoint}.service`, `declared endpoint owner "${owner}" does not exist`, owner);
|
|
699
|
+
owners.add(owner);
|
|
340
700
|
}
|
|
341
|
-
const
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
701
|
+
for (const owner of owners) {
|
|
702
|
+
if (services[owner].network_mode !== void 0) fail(`services.${owner}.network_mode`, `endpoint owner cannot use network_mode`);
|
|
703
|
+
const health = services[owner].healthcheck;
|
|
704
|
+
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`);
|
|
345
705
|
}
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
// src/core/composition/validateOverrideCompose.ts
|
|
709
|
+
function validateAndPrepareAppOverride(document, context) {
|
|
710
|
+
const fail = (path20, reason, value) => {
|
|
711
|
+
throw new ConfigError({ sourceFile: context.file, configPath: path20, stage: context.stage, composition: "service", ...{} , reason });
|
|
712
|
+
};
|
|
713
|
+
const keys = Object.keys(document.services ?? {});
|
|
714
|
+
if (keys.length !== 1 || keys[0] !== "app") fail("services", "override must define exactly one service named app");
|
|
715
|
+
const app = structuredClone(document.services.app);
|
|
716
|
+
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");
|
|
717
|
+
if (app.healthcheck && typeof app.healthcheck === "object") {
|
|
718
|
+
const health = app.healthcheck;
|
|
719
|
+
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");
|
|
720
|
+
}
|
|
721
|
+
if (app.build && typeof app.build === "object") {
|
|
722
|
+
const b = app.build;
|
|
723
|
+
for (const k of ["target", "dockerfile"]) if (b[k] !== void 0) fail(`services.app.build.${k}`, "override cannot change Builder-owned build configuration");
|
|
724
|
+
if (b.context !== void 0 && b.context !== "." && b.context !== context.expectedBuildContext) fail("services.app.build.context", "override cannot change app build context");
|
|
725
|
+
}
|
|
726
|
+
const env = normalizeComposeEnvironment(app.environment, "services.app.environment");
|
|
727
|
+
for (const k of ["EXEC_MODE", "INFRA_MODE"]) if (k in env) fail(`services.app.environment.${k}`, "override cannot set Builder-owned environment");
|
|
728
|
+
app.environment = env;
|
|
729
|
+
const resourceKeys = ["volumes", "networks", "configs", "secrets"];
|
|
730
|
+
const resources = {};
|
|
731
|
+
for (const kind of resourceKeys) {
|
|
732
|
+
const defs = document[kind] ?? {};
|
|
733
|
+
const refs2 = /* @__PURE__ */ new Set();
|
|
734
|
+
const refsVal = app[kind];
|
|
735
|
+
if (Array.isArray(refsVal)) for (const v of refsVal) {
|
|
736
|
+
if (typeof v === "string") refs2.add(v);
|
|
737
|
+
else if (v && typeof v === "object" && typeof v.source === "string") refs2.add(v.source);
|
|
738
|
+
}
|
|
739
|
+
else if (refsVal && typeof refsVal === "object") for (const [k, v] of Object.entries(refsVal)) {
|
|
740
|
+
refs2.add(k);
|
|
741
|
+
if (v && typeof v === "object" && typeof v.source === "string") refs2.add(v.source);
|
|
742
|
+
}
|
|
743
|
+
const mapped = {};
|
|
744
|
+
for (const [name, def] of Object.entries(defs)) {
|
|
745
|
+
if (!refs2.has(name)) fail(`${kind}.${name}`, "override resource must be consumed by app");
|
|
746
|
+
const target = `app-override--${context.stage}--${kind.slice(0, -1)}--${name}`;
|
|
747
|
+
mapped[target] = def;
|
|
748
|
+
for (const ref of refs2) if (ref === name) ;
|
|
749
|
+
}
|
|
750
|
+
if (Object.keys(mapped).length) resources[kind] = mapped;
|
|
751
|
+
if (app[kind] && typeof app[kind] === "object" && !Array.isArray(app[kind])) app[kind] = Object.fromEntries(Object.entries(app[kind]).map(([k, v]) => [`app-override--${context.stage}--${kind.slice(0, -1)}--${k}`, v]));
|
|
752
|
+
else if (Array.isArray(app[kind])) app[kind] = app[kind].map((v) => typeof v === "string" ? `app-override--${context.stage}--${kind.slice(0, -1)}--${v}` : v && typeof v === "object" ? { ...v, source: `app-override--${context.stage}--${kind.slice(0, -1)}--${v.source}` } : v);
|
|
753
|
+
}
|
|
754
|
+
return { app, resources };
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
// src/core/composition/dependencyLifecycle.ts
|
|
758
|
+
function asMap(value) {
|
|
759
|
+
if (Array.isArray(value)) return Object.fromEntries(value.filter((v) => typeof v === "string").map((v) => [v, {}]));
|
|
760
|
+
if (value && typeof value === "object") return value;
|
|
761
|
+
return {};
|
|
762
|
+
}
|
|
763
|
+
function healthyMerge(target, owners) {
|
|
764
|
+
const current = asMap(target.depends_on);
|
|
765
|
+
for (const owner of owners) {
|
|
766
|
+
const old = current[owner];
|
|
767
|
+
const cond = old && typeof old === "object" ? old.condition : void 0;
|
|
768
|
+
current[owner] = { ...old && typeof old === "object" ? old : {}, condition: cond === "service_healthy" ? cond : "service_healthy" };
|
|
769
|
+
}
|
|
770
|
+
target.depends_on = current;
|
|
771
|
+
}
|
|
772
|
+
function applyDependencyLifecycle(app, materialized, effectiveBuild) {
|
|
773
|
+
const appOwners = /* @__PURE__ */ new Set();
|
|
774
|
+
for (const dep of Object.values(materialized)) for (const owner of dep.endpointOwners) appOwners.add(owner);
|
|
775
|
+
healthyMerge(app, appOwners);
|
|
776
|
+
for (const [key, dep] of Object.entries(materialized)) {
|
|
777
|
+
const config = effectiveBuild.dependencies[key];
|
|
778
|
+
if (!config) continue;
|
|
779
|
+
for (const raw of config.dependsOn) {
|
|
780
|
+
const match = DEPENDENCY_REFERENCE_PATTERN.exec(raw);
|
|
781
|
+
if (!match) continue;
|
|
782
|
+
const target = materialized[match[1]];
|
|
783
|
+
if (!target) continue;
|
|
784
|
+
for (const sourceOwner of dep.endpointOwners) {
|
|
785
|
+
const source = dep.compose.services[sourceOwner];
|
|
786
|
+
if (source) healthyMerge(source, target.endpointOwners);
|
|
787
|
+
}
|
|
351
788
|
}
|
|
352
789
|
}
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
// src/core/composition/serviceEndpoints.ts
|
|
793
|
+
function buildStandaloneAppEndpoints(build, stage, host = "app") {
|
|
794
|
+
const out = {};
|
|
795
|
+
for (const [name, e] of Object.entries(build.app.endpoints)) out[name] = { logicalPath: `app.endpoints.${name}`, networkHost: host, networkPort: e.port, ...e.scheme ? { scheme: e.scheme } : {}, ...e.publicPort !== void 0 ? { publicHost: PUBLIC_HOST } : {}, effectivelyPublished: e.publicPort !== void 0 };
|
|
796
|
+
return out;
|
|
797
|
+
}
|
|
798
|
+
function buildStandaloneDependencyEndpoints(key, build, serviceNames, materialized) {
|
|
799
|
+
const out = {};
|
|
800
|
+
for (const [name, e] of Object.entries(build.dependencies[key]?.endpoints ?? {})) {
|
|
801
|
+
const host = serviceNames.get(e.service) ?? e.service;
|
|
802
|
+
out[name] = { logicalPath: `dependencies.${key}.endpoints.${name}`, networkHost: host, networkPort: e.port, ...e.scheme ? { scheme: e.scheme } : {}, ...materialized && e.publicPort !== void 0 ? { publicHost: PUBLIC_HOST } : {}, effectivelyPublished: materialized && e.publicPort !== void 0 };
|
|
803
|
+
}
|
|
804
|
+
return out;
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
// src/core/composition/compileServiceComposition.ts
|
|
808
|
+
function getExecutionProfile(stage, full) {
|
|
809
|
+
switch (stage) {
|
|
810
|
+
case "dev":
|
|
811
|
+
return { configStage: "dev", appTarget: "dev", runtimeStage: "dev", integrated: full, attachTester: false };
|
|
812
|
+
case "prod":
|
|
813
|
+
return { configStage: "prod", appTarget: "prod", runtimeStage: "prod", integrated: true, attachTester: false };
|
|
814
|
+
case "test":
|
|
815
|
+
return { configStage: "test", appTarget: "test", runtimeStage: "test", integrated: false, attachTester: false };
|
|
816
|
+
case "e2e":
|
|
817
|
+
return { configStage: "e2e", appTarget: "prod", runtimeStage: "e2e", integrated: true, attachTester: true, testerTarget: "test-e2e" };
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
function mergeDocument(target, source, context) {
|
|
821
|
+
for (const section of ["services", "volumes", "networks", "configs", "secrets"]) {
|
|
822
|
+
const src = source[section];
|
|
823
|
+
if (!src) continue;
|
|
824
|
+
const dst = target[section] ??= {};
|
|
825
|
+
for (const [key, value] of Object.entries(src)) {
|
|
826
|
+
if (key in dst) throw new ConfigError({ configPath: `${section}.${key}`, referencedObject: context, reason: "Internal Compose namespace collision" });
|
|
827
|
+
dst[key] = value;
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
function getTemplateSeed(stage, meshMode) {
|
|
832
|
+
const base = parse(fs.readFileSync(getDockerComposeTemplate("docker-compose.base.yml"), "utf8"));
|
|
833
|
+
const stageName = stage === "e2e" ? "e2e" : stage;
|
|
834
|
+
const overlay = parse(fs.readFileSync(getDockerComposeTemplate(`docker-compose.${stageName}.yml`), "utf8"));
|
|
835
|
+
const merged = { ...base, services: { ...base.services ?? {} } };
|
|
836
|
+
for (const [name, svc] of Object.entries(overlay.services ?? {})) merged.services[name] = { ...merged.services[name] ?? {}, ...svc, build: { ...merged.services[name]?.build ?? {}, ...svc.build ?? {} } };
|
|
837
|
+
if (meshMode) delete merged.services.tester;
|
|
838
|
+
return merged;
|
|
839
|
+
}
|
|
840
|
+
function ownEnv(build, stage) {
|
|
841
|
+
const env = { ...build.app.env };
|
|
842
|
+
const reserved = ["EXEC_MODE", "INFRA_MODE", ...getPrimaryEndpoint(build.app.endpoints) ? ["PORT"] : []];
|
|
843
|
+
for (const key of reserved) if (key in env) throw new ConfigError({ sourceFile: "build.json", configPath: "app.env", stage, composition: "service", value: key, reason: "Application env cannot set a Builder-owned key" });
|
|
844
|
+
return env;
|
|
845
|
+
}
|
|
846
|
+
function resolveEnv(input, registry, source) {
|
|
847
|
+
const out = {};
|
|
848
|
+
for (const [key, value] of Object.entries(input)) {
|
|
849
|
+
collectBuilderReferences(value, "build", `${source}.${key}`);
|
|
850
|
+
out[key] = interpolateBuilderReferences(value, "build", registry).replace(/\$/g, "$$$$");
|
|
851
|
+
}
|
|
852
|
+
return out;
|
|
853
|
+
}
|
|
854
|
+
function addPorts(service, endpointPairs) {
|
|
855
|
+
for (const [ep, hostPort] of endpointPairs) {
|
|
856
|
+
const ports = Array.isArray(service.ports) ? service.ports : [];
|
|
857
|
+
if (ports.some((p) => p && typeof p === "object" && p.published === hostPort)) throw new ConfigError({ configPath: ep.logicalPath, stage: "service", value: hostPort, reason: "Duplicate host port publication" });
|
|
858
|
+
ports.push({ target: ep.networkPort, published: hostPort, host_ip: PUBLIC_HOST, protocol: "tcp" });
|
|
859
|
+
service.ports = ports;
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
function compileServiceComposition(stage, projectDir, options = {}) {
|
|
863
|
+
const root = resolveProjectDir(projectDir), buildPath = path4.join(root, "build.json"), raw = getBuildJson(root), effective = resolveBuildStage(raw, stage, buildPath), profile = getExecutionProfile(stage, Boolean(options.full));
|
|
864
|
+
resolveInsideProject(root, raw.dockerfile ?? "Dockerfile", { sourceFile: buildPath, configPath: "dockerfile", stage });
|
|
865
|
+
const seed = getTemplateSeed(stage, Boolean(options.meshMode));
|
|
866
|
+
const rawName = options.projectNameOverride ?? raw.name ?? path4.basename(root);
|
|
867
|
+
const projectName = deriveProjectName(rawName, stage);
|
|
868
|
+
const namespaced = {};
|
|
869
|
+
for (const [key, dep] of Object.entries(effective.dependencies).sort(([a], [b]) => a.localeCompare(b))) {
|
|
870
|
+
const sourcePath = resolveInsideProject(root, dep.compose, { sourceFile: buildPath, configPath: `dependencies.${key}.compose`, stage });
|
|
871
|
+
const document = rebaseComposePaths(loadComposeDocument(sourcePath, { sourceFile: buildPath, configPath: `dependencies.${key}.compose`, stage, composition: "service" }), sourcePath, options.composeOutputDir ?? root);
|
|
872
|
+
validateDependencyCompose(key, dep, document, { composePath: sourcePath, stage });
|
|
873
|
+
if (Object.keys(dep.endpoints).length) {
|
|
874
|
+
const ns = namespaceDependencyCompose({ namespacePrefix: options.namespacePrefix ? `${options.namespacePrefix}${key}` : `dep--${key}`, document });
|
|
875
|
+
namespaced[key] = { doc: ns.document, map: ns.serviceNameMap, source: sourcePath };
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
const materialized = {};
|
|
879
|
+
const compose = { ...seed, ...options.meshMode ? {} : { name: projectName }, services: { ...seed.services } };
|
|
880
|
+
let app = compose.services.app ?? (compose.services.app = { build: { context: "." } });
|
|
881
|
+
if (profile.integrated) for (const [key, entry] of Object.entries(namespaced)) {
|
|
882
|
+
if (options.suppressDependencies?.has(key)) continue;
|
|
883
|
+
const dep = effective.dependencies[key];
|
|
884
|
+
const item = structuredClone(entry.doc);
|
|
885
|
+
mergeDocument(compose, item, `dependency ${key}`);
|
|
886
|
+
const endpointOwnerMap = /* @__PURE__ */ new Map();
|
|
887
|
+
for (const [epName, ep] of Object.entries(dep.endpoints)) endpointOwnerMap.set(epName, entry.map.get(ep.service));
|
|
888
|
+
const endpointOwners = new Set(endpointOwnerMap.values());
|
|
889
|
+
materialized[key] = { key, composePath: entry.source, compose: item, serviceNameMap: entry.map, endpointOwnerMap, endpoints: {}, endpointOwners };
|
|
890
|
+
}
|
|
891
|
+
const appEndpoints = buildStandaloneAppEndpoints(effective, stage, options.appServiceName ?? "app");
|
|
892
|
+
const depEndpoints = {};
|
|
893
|
+
for (const [key, dep] of Object.entries(effective.dependencies)) {
|
|
894
|
+
depEndpoints[key] = buildStandaloneDependencyEndpoints(key, effective, namespaced[key]?.map ?? /* @__PURE__ */ new Map(), Boolean(materialized[key]));
|
|
895
|
+
if (options.meshMode) for (const ep of Object.values(depEndpoints[key])) {
|
|
896
|
+
ep.effectivelyPublished = false;
|
|
897
|
+
delete ep.publicHost;
|
|
898
|
+
delete ep.publicPort;
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
if (options.meshMode) for (const ep of Object.values(appEndpoints)) {
|
|
902
|
+
ep.effectivelyPublished = false;
|
|
903
|
+
delete ep.publicHost;
|
|
904
|
+
delete ep.publicPort;
|
|
905
|
+
}
|
|
906
|
+
const intents = [];
|
|
907
|
+
if (!options.meshMode) {
|
|
908
|
+
for (const [name, e] of Object.entries(effective.app.endpoints).sort(([a], [b]) => a.localeCompare(b))) if (e.publicPort !== void 0) intents.push({ logicalPath: `app.endpoints.${name}`, requested: e.publicPort });
|
|
909
|
+
for (const [key, dep] of Object.entries(effective.dependencies).sort(([a], [b]) => a.localeCompare(b))) if (materialized[key]) {
|
|
910
|
+
for (const [name, e] of Object.entries(dep.endpoints).sort(([a], [b]) => a.localeCompare(b))) if (e.publicPort !== void 0) intents.push({ logicalPath: `dependencies.${key}.endpoints.${name}`, requested: e.publicPort });
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
const allocation = allocateHostPorts(root, stage, intents, Boolean(options.validationMode));
|
|
914
|
+
for (const [name, ep] of Object.entries(appEndpoints)) if (allocation.has(ep.logicalPath)) {
|
|
915
|
+
ep.publicHost = PUBLIC_HOST;
|
|
916
|
+
ep.publicPort = allocation.get(ep.logicalPath);
|
|
917
|
+
ep.effectivelyPublished = true;
|
|
918
|
+
}
|
|
919
|
+
for (const [key, eps] of Object.entries(depEndpoints)) for (const [name, ep] of Object.entries(eps)) if (allocation.has(ep.logicalPath)) {
|
|
920
|
+
ep.publicHost = PUBLIC_HOST;
|
|
921
|
+
ep.publicPort = allocation.get(ep.logicalPath);
|
|
922
|
+
ep.effectivelyPublished = true;
|
|
923
|
+
}
|
|
924
|
+
const registry = (ref) => {
|
|
925
|
+
if (ref.target === "app") {
|
|
926
|
+
const ep2 = appEndpoints[ref.endpoint];
|
|
927
|
+
if (!ep2) throw new ConfigError({ sourceFile: buildPath, configPath: ref.raw, stage, composition: "service", referencedObject: ref.raw, reason: "Unknown app endpoint reference" });
|
|
928
|
+
return resolveEndpointProperty(ep2, ref.property, { sourceFile: buildPath, configPath: ref.raw, stage });
|
|
929
|
+
}
|
|
930
|
+
const ep = depEndpoints[ref.dependency]?.[ref.endpoint];
|
|
931
|
+
if (!ep) throw new ConfigError({ sourceFile: buildPath, configPath: ref.raw, stage, composition: "service", referencedObject: ref.raw, reason: "Unknown dependency endpoint reference" });
|
|
932
|
+
return resolveEndpointProperty(ep, ref.property, { sourceFile: buildPath, configPath: ref.raw, stage });
|
|
933
|
+
};
|
|
934
|
+
for (const [key, dep] of Object.entries(effective.dependencies)) {
|
|
935
|
+
const depEnv = options.deferReferenceResolution ? dep.env : resolveEnv(dep.env, registry, `dependencies.${key}.env`);
|
|
936
|
+
for (const svc of Object.values(materialized[key]?.compose.services ?? {})) mergeComposeEnvironment(svc, depEnv);
|
|
937
|
+
}
|
|
938
|
+
const appEnv = options.deferReferenceResolution ? ownEnv(effective, stage) : resolveEnv(ownEnv(effective, stage), registry, "app.env");
|
|
939
|
+
let buildAppEnvironment = { ...appEnv };
|
|
940
|
+
const runtimeDotenv = path4.join(root, `.env.${profile.runtimeStage}`);
|
|
941
|
+
if (fs.existsSync(runtimeDotenv)) {
|
|
942
|
+
const text = fs.readFileSync(runtimeDotenv, "utf8");
|
|
943
|
+
for (const line of text.split(/\r?\n/)) {
|
|
944
|
+
const match = line.match(/^\s*(?:export\s+)?(EXEC_MODE|INFRA_MODE|PORT)\s*=/);
|
|
945
|
+
if (match && (match[1] !== "PORT" || getPrimaryEndpoint(effective.app.endpoints))) throw new ConfigError({ sourceFile: runtimeDotenv, configPath: match[1], stage, composition: "service", reason: "Dotenv file cannot define Builder-owned environment" });
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
const internal = { EXEC_MODE: profile.runtimeStage, INFRA_MODE: profile.integrated ? "integrated" : "isolated", ...getPrimaryEndpoint(effective.app.endpoints) ? { PORT: String(getPrimaryEndpoint(effective.app.endpoints)[1].port) } : {} };
|
|
949
|
+
const appBuild = app.build && typeof app.build === "object" ? app.build : { context: "." };
|
|
950
|
+
const outputDir = options.composeOutputDir ? path4.resolve(options.composeOutputDir) : root;
|
|
951
|
+
const serviceContext = path4.relative(outputDir, root).replace(/\\/g, "/") || ".";
|
|
952
|
+
appBuild.context = options.meshMode ? serviceContext : ".";
|
|
953
|
+
if (raw.dockerfile) appBuild.dockerfile = raw.dockerfile;
|
|
954
|
+
else delete appBuild.dockerfile;
|
|
955
|
+
appBuild.target = profile.appTarget;
|
|
956
|
+
app.build = appBuild;
|
|
957
|
+
app.env_file = [{ path: options.meshMode ? path4.posix.join(serviceContext, `.env.${profile.runtimeStage}`) : `.env.${profile.runtimeStage}`, required: false }];
|
|
958
|
+
app.environment = { ...appEnv, ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
|
|
959
|
+
if (stage === "dev") app.volumes = [`${options.meshMode && serviceContext !== "." ? `./${serviceContext}` : "."}:/app`, "/app/node_modules"];
|
|
960
|
+
for (const [name, ep] of Object.entries(appEndpoints)) if (!options.meshMode && ep.effectivelyPublished) addPorts(app, [[ep, ep.publicPort]]);
|
|
961
|
+
for (const [key, dependency] of Object.entries(materialized)) {
|
|
962
|
+
for (const [epName, owner] of dependency.endpointOwnerMap.entries()) {
|
|
963
|
+
const endpoint = depEndpoints[key][epName];
|
|
964
|
+
if (!options.meshMode && endpoint.effectivelyPublished) addPorts(compose.services[owner], [[endpoint, endpoint.publicPort]]);
|
|
965
|
+
}
|
|
966
|
+
for (const owner of dependency.endpointOwners) {
|
|
967
|
+
const svc = compose.services[owner];
|
|
968
|
+
if (!options.meshMode && svc.networks !== void 0) {
|
|
969
|
+
const nets = svc.networks;
|
|
970
|
+
if (Array.isArray(nets)) {
|
|
971
|
+
if (!nets.includes("default")) nets.push("default");
|
|
972
|
+
} else if (nets && typeof nets === "object") nets.default = null;
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
for (const [epName, ep] of Object.entries(depEndpoints[key])) dependency.endpoints[epName] = ep;
|
|
976
|
+
}
|
|
977
|
+
if (effective.overrideCompose) {
|
|
978
|
+
const overridePath = resolveInsideProject(root, effective.overrideCompose, { sourceFile: buildPath, configPath: "override-compose", stage });
|
|
979
|
+
const odoc = rebaseComposePaths(loadComposeDocument(overridePath, { sourceFile: buildPath, configPath: "override-compose", stage, composition: "service" }), overridePath, options.composeOutputDir ?? root);
|
|
980
|
+
const prepared = validateAndPrepareAppOverride(odoc, { file: overridePath, stage, expectedBuildContext: options.meshMode ? path4.relative(options.composeOutputDir ?? root, root).replace(/\\/g, "/") || "." : "." });
|
|
981
|
+
for (const section of ["volumes", "networks", "configs", "secrets"]) if (prepared.resources[section]) mergeDocument(compose, { services: {}, [section]: prepared.resources[section] }, "app override");
|
|
982
|
+
const rawOverrideEnv = normalizeComposeEnvironment(prepared.app.environment, "override-compose.services.app.environment");
|
|
983
|
+
const overrideEnv = options.deferReferenceResolution ? rawOverrideEnv : resolveEnv(rawOverrideEnv, registry, "override-compose.services.app.environment");
|
|
984
|
+
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" });
|
|
985
|
+
buildAppEnvironment = { ...appEnv, ...overrideEnv };
|
|
986
|
+
const merged = { ...app, ...prepared.app };
|
|
987
|
+
merged.environment = { ...appEnv, ...overrideEnv, ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
|
|
988
|
+
const overrideBuild = prepared.app.build && typeof prepared.app.build === "object" ? prepared.app.build : {};
|
|
989
|
+
if (overrideBuild.args !== void 0) appBuild.args = overrideBuild.args;
|
|
990
|
+
merged.build = appBuild;
|
|
991
|
+
merged.env_file = app.env_file;
|
|
992
|
+
merged.depends_on = app.depends_on;
|
|
993
|
+
merged.networks = { default: null, ...app.networks ?? {}, ...prepared.app.networks ?? {} };
|
|
994
|
+
compose.services.app = merged;
|
|
995
|
+
app = merged;
|
|
996
|
+
}
|
|
997
|
+
if (options.meshMode && options.appServiceName && options.appServiceName !== "app") {
|
|
998
|
+
delete compose.services.app;
|
|
999
|
+
compose.services[options.appServiceName] = app;
|
|
1000
|
+
}
|
|
1001
|
+
if (profile.integrated) applyDependencyLifecycle(app, materialized, effective);
|
|
1002
|
+
if (profile.attachTester && !options.meshMode) {
|
|
1003
|
+
const testerEnvRaw = effective.tester?.env ?? {};
|
|
1004
|
+
assertTesterReferencesArePublic(testerEnvRaw, "build", "tester.env");
|
|
1005
|
+
const testerEnv = options.deferReferenceResolution ? testerEnvRaw : resolveEnv(testerEnvRaw, registry, "tester.env");
|
|
1006
|
+
compose.services.tester = { build: { context: ".", ...raw.dockerfile ? { dockerfile: raw.dockerfile } : {}, target: "test-e2e" }, network_mode: "host", environment: testerEnv, depends_on: { app: { condition: "service_healthy" } } };
|
|
1007
|
+
}
|
|
1008
|
+
const builderAppEnvironment = { ...buildAppEnvironment, ...options.externalAppEnv ?? {} };
|
|
1009
|
+
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])) };
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
// src/core/checkers/checkEffectiveServiceStages.ts
|
|
1013
|
+
function checkAllEffectiveServiceStages(projectDir) {
|
|
1014
|
+
compileServiceComposition("dev", projectDir, { validationMode: true });
|
|
1015
|
+
compileServiceComposition("dev", projectDir, { full: true, validationMode: true });
|
|
1016
|
+
compileServiceComposition("prod", projectDir, { validationMode: true });
|
|
1017
|
+
compileServiceComposition("test", projectDir, { validationMode: true });
|
|
1018
|
+
compileServiceComposition("e2e", projectDir, { validationMode: true });
|
|
380
1019
|
}
|
|
381
1020
|
|
|
382
1021
|
// src/core/checkers/checkInfra.ts
|
|
@@ -386,8 +1025,8 @@ function checkInfra(projectDir = process.cwd()) {
|
|
|
386
1025
|
checkDockerfile(buildJson, absProjectDir);
|
|
387
1026
|
checkDockerfileContract(buildJson, absProjectDir);
|
|
388
1027
|
checkYamlFiles(buildJson, absProjectDir);
|
|
389
|
-
|
|
390
|
-
console.log(pc22.green("\n\u2705 All infrastructure and contract checks passed.\n"));
|
|
1028
|
+
checkAllEffectiveServiceStages(absProjectDir);
|
|
1029
|
+
console.log(pc22.green("\n\u2705 All V2 service infrastructure and contract checks passed.\n"));
|
|
391
1030
|
}
|
|
392
1031
|
function checkComposeAvailability() {
|
|
393
1032
|
const composeCheck = spawnSync(
|
|
@@ -471,326 +1110,489 @@ Examples:
|
|
|
471
1110
|
}
|
|
472
1111
|
});
|
|
473
1112
|
};
|
|
474
|
-
var
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
interval: z.string().optional(),
|
|
482
|
-
timeout: z.string().optional(),
|
|
483
|
-
retries: z.number().optional(),
|
|
484
|
-
start_period: z.string().optional(),
|
|
485
|
-
disable: z.boolean().optional()
|
|
486
|
-
}).passthrough()
|
|
487
|
-
]);
|
|
488
|
-
var meshServiceSchema = z.object({
|
|
489
|
-
path: z.string({ required_error: 'Service "path" is required' }).describe("Relative path to service directory containing build.json"),
|
|
490
|
-
port: z.union([z.number(), z.string()]).optional().describe("Public host port mapped to internal port 3000"),
|
|
491
|
-
preservePort: z.boolean().optional().describe("If true, use the port declared in build.json"),
|
|
492
|
-
provideDependency: z.record(z.string(), z.string()).optional().describe("Map consumer dependency key to fellow mesh service provider"),
|
|
493
|
-
replaceMocks: z.record(z.string(), z.string()).optional().describe("Alias for provideDependency"),
|
|
494
|
-
envOverrides: z.record(z.string(), z.string()).optional().describe("Environment variable overrides with URL templating"),
|
|
495
|
-
healthcheck: meshHealthcheckSchema.optional()
|
|
496
|
-
}).strict();
|
|
497
|
-
var meshTesterSchema = z.object({
|
|
498
|
-
path: z.string({ required_error: 'Tester "path" is required' }).describe("Relative path to E2E tester directory"),
|
|
499
|
-
compose: z.string().optional().describe("Tester compose file (defaults to 'docker-compose.yml')"),
|
|
500
|
-
dockerfile: z.string().optional().describe("Tester Dockerfile (defaults to 'Dockerfile')"),
|
|
501
|
-
envOverrides: z.record(z.string(), z.string()).optional().describe(
|
|
502
|
-
"Environment variable overrides for global tester with URL templating"
|
|
503
|
-
),
|
|
504
|
-
policy: z.object({
|
|
505
|
-
dockerfile: z.string().optional(),
|
|
506
|
-
compose: z.string().optional()
|
|
507
|
-
}).strict().optional()
|
|
508
|
-
}).strict();
|
|
509
|
-
var meshServiceNameRegex = /^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/;
|
|
510
|
-
var meshSchema = z.object({
|
|
511
|
-
$schema: z.string().optional(),
|
|
512
|
-
name: z.string().optional(),
|
|
513
|
-
services: z.record(
|
|
514
|
-
z.string().regex(meshServiceNameRegex, {
|
|
515
|
-
message: "Service name must start with a lowercase letter or digit and contain only lowercase letters, digits, '-', '_', or '.'"
|
|
516
|
-
}),
|
|
517
|
-
meshServiceSchema
|
|
518
|
-
).refine((services) => Object.keys(services).length > 0, {
|
|
519
|
-
message: 'At least one service must be defined in "services".'
|
|
520
|
-
}),
|
|
521
|
-
dependencies: z.record(
|
|
522
|
-
z.string(),
|
|
523
|
-
z.object({
|
|
524
|
-
path: z.string(),
|
|
525
|
-
service: z.string().optional()
|
|
526
|
-
}).strict()
|
|
527
|
-
).optional(),
|
|
528
|
-
tester: meshTesterSchema.optional()
|
|
529
|
-
}).strict();
|
|
530
|
-
|
|
531
|
-
// src/core/mesh/checkers/checkMeshJson.ts
|
|
532
|
-
function checkMeshJson(mesh) {
|
|
533
|
-
const result = meshSchema.safeParse(mesh);
|
|
534
|
-
if (!result.success) {
|
|
535
|
-
const errorDetails = result.error.issues.map(
|
|
536
|
-
(issue) => issue.path.length > 0 ? `${issue.path.join(".")}: ${issue.message}` : issue.message
|
|
537
|
-
).join("; ");
|
|
538
|
-
throw new ScriptError(`Invalid mesh.json: ${errorDetails}`);
|
|
539
|
-
}
|
|
540
|
-
const services = result.data.services;
|
|
541
|
-
const serviceKeys = new Set(Object.keys(services));
|
|
542
|
-
const graph = /* @__PURE__ */ new Map();
|
|
543
|
-
for (const sName of serviceKeys) {
|
|
544
|
-
graph.set(sName, /* @__PURE__ */ new Set());
|
|
545
|
-
}
|
|
546
|
-
for (const [serviceName, serviceConfig] of Object.entries(services)) {
|
|
547
|
-
const provideMap = {
|
|
548
|
-
...serviceConfig.replaceMocks || {},
|
|
549
|
-
...serviceConfig.provideDependency || {}
|
|
550
|
-
};
|
|
551
|
-
for (const [depKey, targetSvc] of Object.entries(provideMap)) {
|
|
552
|
-
if (!serviceKeys.has(targetSvc)) {
|
|
553
|
-
throw new ScriptError(
|
|
554
|
-
`Invalid mesh.json: Service "${serviceName}" maps dependency "${depKey}" to nonexistent service "${targetSvc}".`
|
|
555
|
-
);
|
|
556
|
-
}
|
|
557
|
-
graph.get(serviceName).add(targetSvc);
|
|
558
|
-
}
|
|
559
|
-
}
|
|
560
|
-
const visited = /* @__PURE__ */ new Map();
|
|
561
|
-
function dfs(node, pathStack) {
|
|
562
|
-
visited.set(node, "visiting");
|
|
563
|
-
pathStack.push(node);
|
|
564
|
-
const neighbors = graph.get(node) || /* @__PURE__ */ new Set();
|
|
565
|
-
for (const neighbor of neighbors) {
|
|
566
|
-
const state = visited.get(neighbor);
|
|
567
|
-
if (state === "visiting") {
|
|
568
|
-
const cycleStart = pathStack.indexOf(neighbor);
|
|
569
|
-
const cycle = [...pathStack.slice(cycleStart), neighbor];
|
|
570
|
-
throw new ScriptError(
|
|
571
|
-
`Dependency cycle detected in mesh.json: ${cycle.join(" -> ")}`
|
|
572
|
-
);
|
|
573
|
-
}
|
|
574
|
-
if (!state) {
|
|
575
|
-
dfs(neighbor, pathStack);
|
|
576
|
-
}
|
|
577
|
-
}
|
|
578
|
-
pathStack.pop();
|
|
579
|
-
visited.set(node, "visited");
|
|
580
|
-
}
|
|
581
|
-
for (const sName of serviceKeys) {
|
|
582
|
-
if (!visited.has(sName)) {
|
|
583
|
-
dfs(sName, []);
|
|
584
|
-
}
|
|
585
|
-
}
|
|
586
|
-
}
|
|
1113
|
+
var identifierSchema2 = z.string().regex(BUILDER_IDENTIFIER_PATTERN, "must match ^[a-z][a-z0-9-]*$");
|
|
1114
|
+
var serviceNameSchema = identifierSchema2.refine((name) => !RESERVED_MESH_SERVICE_NAMES.has(name), { message: "is reserved and cannot be used as a mesh service name" });
|
|
1115
|
+
var envSchema2 = z.record(z.string(), z.string());
|
|
1116
|
+
var meshServiceSchema = z.object({ path: z.string().min(1), env: envSchema2.optional(), dependencies: z.record(identifierSchema2, serviceNameSchema).optional(), dependsOn: z.array(serviceNameSchema).optional(), publish: z.array(z.string()).optional() }).strict();
|
|
1117
|
+
var meshServiceStageOverlaySchema = z.object({ path: z.string().min(1).optional(), env: envSchema2.optional(), dependencies: z.record(identifierSchema2, serviceNameSchema).optional(), dependsOn: z.array(serviceNameSchema).optional(), publish: z.array(z.string()).optional() }).strict();
|
|
1118
|
+
var meshStageSchema = z.object({ services: z.record(serviceNameSchema, meshServiceStageOverlaySchema).optional() }).strict();
|
|
1119
|
+
var meshSchema = z.object({ $schema: z.string().optional(), name: z.string().optional(), tester: z.object({ compose: z.string().min(1), service: z.string().min(1), env: envSchema2.optional() }).strict().optional(), services: z.record(serviceNameSchema, meshServiceSchema), dev: meshStageSchema.optional(), prod: meshStageSchema.optional(), test: meshStageSchema.optional(), e2e: meshStageSchema.optional() }).strict();
|
|
587
1120
|
|
|
588
1121
|
// src/core/mesh/getMeshJson.ts
|
|
589
1122
|
function getMeshJson(projectDir = process.cwd()) {
|
|
590
|
-
const absDir = resolveProjectDir(projectDir);
|
|
591
|
-
|
|
592
|
-
if (!existsSync(meshPath)) {
|
|
593
|
-
throw new NotFoundError(`mesh.json not found in directory: ${absDir}`);
|
|
594
|
-
}
|
|
1123
|
+
const absDir = resolveProjectDir(projectDir), meshPath = path4.resolve(absDir, "mesh.json");
|
|
1124
|
+
if (!existsSync(meshPath)) throw new NotFoundError(`mesh.json not found in directory: ${absDir}`);
|
|
595
1125
|
let content;
|
|
596
1126
|
try {
|
|
597
1127
|
content = readFileSync(meshPath, "utf-8");
|
|
598
1128
|
} catch (err) {
|
|
599
|
-
throw new ScriptError(
|
|
600
|
-
`Failed to read mesh.json at ${meshPath}: ${errorMessage(err)}`
|
|
601
|
-
);
|
|
1129
|
+
throw new ScriptError(`Failed to read mesh.json at ${meshPath}: ${errorMessage(err)}`);
|
|
602
1130
|
}
|
|
603
1131
|
let parsed;
|
|
604
1132
|
try {
|
|
605
1133
|
parsed = JSON.parse(content);
|
|
606
1134
|
} catch (err) {
|
|
607
|
-
throw new ScriptError(
|
|
608
|
-
`Failed to parse mesh.json at ${meshPath}: ${errorMessage(err)}`
|
|
609
|
-
);
|
|
1135
|
+
throw new ScriptError(`Failed to parse mesh.json at ${meshPath}: ${errorMessage(err)}`);
|
|
610
1136
|
}
|
|
611
|
-
|
|
612
|
-
|
|
1137
|
+
const result = meshSchema.safeParse(parsed);
|
|
1138
|
+
if (!result.success) {
|
|
1139
|
+
const reason = result.error.issues.map((issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`).join("; ");
|
|
1140
|
+
throw new ConfigError({ sourceFile: meshPath, configPath: "<root>", composition: "mesh", reason: `Invalid mesh.json: ${reason}` });
|
|
613
1141
|
}
|
|
614
|
-
|
|
615
|
-
checkMeshJson(meshConfig);
|
|
616
|
-
return meshConfig;
|
|
1142
|
+
return result.data;
|
|
617
1143
|
}
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
);
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
if (!
|
|
632
|
-
|
|
1144
|
+
|
|
1145
|
+
// src/core/config/resolveMeshStage.ts
|
|
1146
|
+
function resolveMeshStage(mesh, stage, sourceFile) {
|
|
1147
|
+
const overlays = mesh[stage]?.services ?? {}, names = /* @__PURE__ */ new Set([...Object.keys(mesh.services), ...Object.keys(overlays)]), services = {};
|
|
1148
|
+
for (const name of names) {
|
|
1149
|
+
const base = mesh.services[name], patch = overlays[name];
|
|
1150
|
+
const merged = { path: patch?.path ?? base?.path, env: mergeStringMap(base?.env, patch?.env), dependencies: { ...base?.dependencies ?? {}, ...patch?.dependencies ?? {} }, dependsOn: unionStable(base?.dependsOn, patch?.dependsOn), publish: unionStable(base?.publish, patch?.publish) };
|
|
1151
|
+
if (!merged.path) throw new ConfigError({ sourceFile, configPath: `services.${name}.path`, stage, composition: "mesh", reason: "Effective mesh service requires path" });
|
|
1152
|
+
services[name] = merged;
|
|
1153
|
+
}
|
|
1154
|
+
if (!Object.keys(services).length) throw new ConfigError({ sourceFile, configPath: "services", stage, composition: "mesh", reason: "At least one effective mesh service is required" });
|
|
1155
|
+
const graph = /* @__PURE__ */ new Map();
|
|
1156
|
+
for (const [name, service] of Object.entries(services)) {
|
|
1157
|
+
if (!BUILDER_IDENTIFIER_PATTERN.test(name) || RESERVED_MESH_SERVICE_NAMES.has(name)) throw new ConfigError({ sourceFile, configPath: `services.${name}`, stage, composition: "mesh", value: name, reason: "Invalid or reserved mesh service name" });
|
|
1158
|
+
graph.set(name, /* @__PURE__ */ new Set());
|
|
1159
|
+
for (const target of service.dependsOn) {
|
|
1160
|
+
if (target === name) throw new ConfigError({ sourceFile, configPath: `services.${name}.dependsOn`, stage, composition: "mesh", referencedObject: target, reason: "Mesh service cannot depend on itself" });
|
|
1161
|
+
if (!services[target]) throw new ConfigError({ sourceFile, configPath: `services.${name}.dependsOn`, stage, composition: "mesh", referencedObject: target, reason: "Unknown mesh lifecycle target" });
|
|
1162
|
+
graph.get(name).add(target);
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
assertAcyclicGraph(graph, { sourceFile, stage, composition: "mesh" });
|
|
1166
|
+
const result = { ...mesh, services };
|
|
1167
|
+
delete result.dev;
|
|
1168
|
+
delete result.prod;
|
|
1169
|
+
delete result.test;
|
|
1170
|
+
delete result.e2e;
|
|
1171
|
+
return result;
|
|
1172
|
+
}
|
|
1173
|
+
function loadEffectiveMeshServices(meshDir, effectiveMesh, stage) {
|
|
1174
|
+
const out = {};
|
|
1175
|
+
for (const [name, svc] of Object.entries(effectiveMesh.services).sort(([a], [b]) => a.localeCompare(b))) {
|
|
1176
|
+
const abs = resolveInsideProject(meshDir, svc.path, { sourceFile: path4.join(meshDir, "mesh.json"), configPath: `services.${name}.path`, stage });
|
|
1177
|
+
if (!fs.existsSync(abs) || !fs.statSync(abs).isDirectory()) throw new ConfigError({ sourceFile: path4.join(meshDir, "mesh.json"), configPath: `services.${name}.path`, stage, composition: "mesh", value: svc.path, reason: "Mesh service directory does not exist" });
|
|
1178
|
+
const buildJsonPath = path4.join(abs, "build.json"), build = getBuildJson(abs), effectiveBuild = resolveBuildStage(build, stage, buildJsonPath);
|
|
1179
|
+
out[name] = { name, path: svc.path, absolutePath: abs, buildJsonPath, effectiveBuild, meshEnv: { ...svc.env ?? {} }, dependencyBindings: { ...svc.dependencies ?? {} }, dependsOn: [...svc.dependsOn ?? []], publish: [...svc.publish ?? []] };
|
|
1180
|
+
}
|
|
1181
|
+
return out;
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
// src/core/mesh/v2/substitution.ts
|
|
1185
|
+
function buildDependencyBindings(services, stage, meshJsonPath) {
|
|
1186
|
+
const out = [];
|
|
1187
|
+
for (const service of Object.values(services)) {
|
|
1188
|
+
for (const [logicalDependency, providerService] of Object.entries(service.dependencyBindings)) {
|
|
1189
|
+
if (!service.effectiveBuild.dependencies[logicalDependency]) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${service.name}.dependencies.${logicalDependency}`, stage, composition: "mesh", value: providerService, reason: `Unknown logical dependency slot on consumer ${service.name}` });
|
|
1190
|
+
if (!services[providerService]) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${service.name}.dependencies.${logicalDependency}`, stage, composition: "mesh", value: providerService, reason: "Dependency provider is not an effective top-level mesh service" });
|
|
1191
|
+
out.push({ consumerService: service.name, logicalDependency, providerService });
|
|
633
1192
|
}
|
|
634
|
-
const serviceDir = path13.resolve(absMeshDir, serviceConfig.path);
|
|
635
|
-
if (!isPathInside(absMeshDir, serviceDir)) {
|
|
636
|
-
throw new ScriptError(
|
|
637
|
-
`Security error: Service "${serviceName}" directory escapes the mesh directory: ${serviceDir}`
|
|
638
|
-
);
|
|
639
|
-
}
|
|
640
|
-
if (!existsSync(serviceDir)) {
|
|
641
|
-
throw new ScriptError(
|
|
642
|
-
`Service "${serviceName}" directory does not exist: ${serviceDir} (declared path: "${serviceConfig.path}")`
|
|
643
|
-
);
|
|
644
|
-
}
|
|
645
|
-
if (!statSync(serviceDir).isDirectory()) {
|
|
646
|
-
throw new ScriptError(
|
|
647
|
-
`Service "${serviceName}" path is not a directory: ${serviceDir}`
|
|
648
|
-
);
|
|
649
|
-
}
|
|
650
|
-
const buildJsonPath = path13.resolve(serviceDir, "build.json");
|
|
651
|
-
if (!existsSync(buildJsonPath)) {
|
|
652
|
-
throw new ScriptError(
|
|
653
|
-
`Service "${serviceName}" is missing a valid build.json at: ${buildJsonPath}`
|
|
654
|
-
);
|
|
655
|
-
}
|
|
656
|
-
console.log(
|
|
657
|
-
pc22.bold(pc22.blue(`
|
|
658
|
-
--- Validating Infrastructure for [${serviceName}] ---`))
|
|
659
|
-
);
|
|
660
|
-
checkInfra(serviceDir);
|
|
661
1193
|
}
|
|
1194
|
+
return out;
|
|
662
1195
|
}
|
|
663
|
-
function
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
1196
|
+
function bindingKey(consumer, dependency) {
|
|
1197
|
+
return `${consumer}::${dependency}`;
|
|
1198
|
+
}
|
|
1199
|
+
function bindingsMap(bindings) {
|
|
1200
|
+
return new Map(bindings.map((b) => [bindingKey(b.consumerService, b.logicalDependency), b.providerService]));
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
// src/core/mesh/v2/publication.ts
|
|
1204
|
+
var APP = /^app\.endpoints\.([a-z][a-z0-9-]*)$/;
|
|
1205
|
+
var DEP = /^dependencies\.([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)$/;
|
|
1206
|
+
function resolveMeshPublication(services, bindings, stage, meshJsonPath) {
|
|
1207
|
+
const out = [];
|
|
1208
|
+
for (const svc of Object.values(services).sort((a, b) => a.name.localeCompare(b.name))) for (const raw of svc.publish) {
|
|
1209
|
+
let m;
|
|
1210
|
+
if (m = APP.exec(raw)) {
|
|
1211
|
+
const ep = m[1], endpoint = svc.effectiveBuild.app.endpoints[ep];
|
|
1212
|
+
if (!endpoint) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${svc.name}.publish`, stage, composition: "mesh", value: raw, reason: "Published app endpoint does not exist" });
|
|
1213
|
+
if (endpoint.publicPort === void 0) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${svc.name}.publish`, stage, composition: "mesh", value: raw, reason: "Published endpoint requires publicPort in build.json" });
|
|
1214
|
+
out.push({ logicalPath: `${svc.name}.app.endpoints.${ep}`, ownerMeshService: svc.name, target: "app", endpoint: ep });
|
|
1215
|
+
continue;
|
|
669
1216
|
}
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
1217
|
+
if (m = DEP.exec(raw)) {
|
|
1218
|
+
const dependency = m[1], endpoint = m[2], dep = svc.effectiveBuild.dependencies[dependency];
|
|
1219
|
+
if (!dep || !dep.endpoints[endpoint]) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${svc.name}.publish`, stage, composition: "mesh", value: raw, reason: "Published dependency endpoint does not exist" });
|
|
1220
|
+
if (!Object.keys(dep.endpoints).length) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${svc.name}.publish`, stage, composition: "mesh", value: raw, reason: "Dependency endpoint is inert" });
|
|
1221
|
+
if (bindings.has(bindingKey(svc.name, dependency))) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${svc.name}.publish`, stage, composition: "mesh", value: raw, referencedObject: `${bindings.get(bindingKey(svc.name, dependency))}.publish -> app.endpoints.${endpoint}`, reason: "A substituted dependency endpoint cannot be published by its consumer; publish the provider app endpoint instead" });
|
|
1222
|
+
if (dep.endpoints[endpoint].publicPort === void 0) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${svc.name}.publish`, stage, composition: "mesh", value: raw, reason: "Published dependency endpoint requires publicPort in build.json" });
|
|
1223
|
+
out.push({ logicalPath: `${svc.name}.dependencies.${dependency}.endpoints.${endpoint}`, ownerMeshService: svc.name, target: "dependency", dependency, endpoint });
|
|
1224
|
+
continue;
|
|
1225
|
+
}
|
|
1226
|
+
throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${svc.name}.publish`, stage, composition: "mesh", value: raw, reason: "Invalid publish target; expected app.endpoints.<name> or dependencies.<name>.endpoints.<name>" });
|
|
678
1227
|
}
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
1228
|
+
return out;
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
// src/core/mesh/v2/meshReferences.ts
|
|
1232
|
+
function resolveMesh(ref, ctx, source) {
|
|
1233
|
+
const name = ref.meshService;
|
|
1234
|
+
if (!ctx.services[name]) throw new ConfigError({ sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage, composition: "mesh", referencedObject: ref.raw, reason: `Unknown mesh service reference "${name}"` });
|
|
1235
|
+
const provider = ref.target === "dependency" ? ctx.bindings.get(bindingKey(name, ref.dependency)) : void 0;
|
|
1236
|
+
const ep = ref.target === "app" ? ctx.endpoints.app[name]?.[ref.endpoint] : provider ? ctx.endpoints.app[provider]?.[ref.endpoint] : ctx.endpoints.dependencies[name]?.[ref.dependency]?.[ref.endpoint];
|
|
1237
|
+
if (!ep) throw new ConfigError({ sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage, composition: "mesh", referencedObject: ref.raw, reason: "Referenced endpoint does not exist" });
|
|
1238
|
+
return resolveEndpointProperty(ep, ref.property, { sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage });
|
|
1239
|
+
}
|
|
1240
|
+
function resolveBuild(ref, consumer, ctx, source) {
|
|
1241
|
+
const provider = ref.target === "dependency" ? ctx.bindings.get(bindingKey(consumer, ref.dependency)) : void 0;
|
|
1242
|
+
const ep = ref.target === "app" ? ctx.endpoints.app[consumer]?.[ref.endpoint] : provider ? ctx.endpoints.app[provider]?.[ref.endpoint] : ctx.endpoints.dependencies[consumer]?.[ref.dependency]?.[ref.endpoint];
|
|
1243
|
+
if (!ep) throw new ConfigError({ sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage, composition: "mesh", referencedObject: ref.raw, reason: provider ? `Provider "${provider}" does not expose endpoint "${ref.endpoint}"` : "Referenced endpoint does not exist" });
|
|
1244
|
+
try {
|
|
1245
|
+
return resolveEndpointProperty(ep, ref.property, { sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage });
|
|
1246
|
+
} catch (error) {
|
|
1247
|
+
if (provider && error instanceof ConfigError) throw new ConfigError({ sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage, composition: "mesh", referencedObject: `${consumer}.dependencies.${ref.dependency}.endpoints.${ref.endpoint}.${ref.property} -> ${provider}.app.endpoints.${ref.endpoint}.${ref.property}`, reason: error.message });
|
|
1248
|
+
throw error;
|
|
684
1249
|
}
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
1250
|
+
}
|
|
1251
|
+
function interpolate(value, scope, resolve, source) {
|
|
1252
|
+
const sentinel = "\0DOLLAR\0";
|
|
1253
|
+
return value.replace(/\$\$/g, sentinel).replace(/\$\{([^}]*)\}/g, (_whole, body) => {
|
|
1254
|
+
const ref = collectBuilderReferences(`\${${body}}`, scope, source)[0];
|
|
1255
|
+
return resolve(ref);
|
|
1256
|
+
}).replaceAll(sentinel, "$").replace(/\$/g, "$$$$");
|
|
1257
|
+
}
|
|
1258
|
+
function resolveMeshEnvMap(env, ctx, sourcePrefix) {
|
|
1259
|
+
return Object.fromEntries(Object.entries(env).map(([key, value]) => [key, interpolate(value, "mesh", (ref) => resolveMesh(ref, ctx, `${sourcePrefix}.${key}`), `${sourcePrefix}.${key}`)]));
|
|
1260
|
+
}
|
|
1261
|
+
function resolveServiceBuildEnvThroughMesh(consumer, env, ctx, sourcePrefix) {
|
|
1262
|
+
return Object.fromEntries(Object.entries(env).map(([key, value]) => [key, interpolate(value, "build", (ref) => resolveBuild(ref, consumer, ctx, `${sourcePrefix}.${key}`), `${sourcePrefix}.${key}`)]));
|
|
1263
|
+
}
|
|
1264
|
+
function assertMeshTesterEnvPublic(env, source) {
|
|
1265
|
+
assertTesterReferencesArePublic(env, "mesh", source);
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
// src/core/mesh/v2/lifecycle.ts
|
|
1269
|
+
function buildMeshLifecycleEdges(services, bindings, stage, meshJsonPath) {
|
|
1270
|
+
const result = [];
|
|
1271
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1272
|
+
for (const svc of Object.values(services)) for (const provider of [...svc.dependsOn, ...Object.entries(svc.dependencyBindings).map(([dep]) => bindings.get(bindingKey(svc.name, dep))).filter(Boolean)]) {
|
|
1273
|
+
if (provider === svc.name) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${svc.name}.dependsOn`, stage, composition: "mesh", referencedObject: provider, reason: "Mesh service cannot depend on itself" });
|
|
1274
|
+
const source = svc.dependsOn.includes(provider) ? "dependsOn" : "dependency-binding";
|
|
1275
|
+
const id = `${svc.name}\0${provider}`;
|
|
1276
|
+
if (!seen.has(id)) {
|
|
1277
|
+
seen.add(id);
|
|
1278
|
+
result.push({ consumer: svc.name, provider, source });
|
|
1279
|
+
}
|
|
689
1280
|
}
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
1281
|
+
const graph = new Map(Object.keys(services).map((name) => [name, /* @__PURE__ */ new Set()]));
|
|
1282
|
+
for (const edge of result) graph.get(edge.consumer).add(edge.provider);
|
|
1283
|
+
assertAcyclicGraph(graph, { sourceFile: meshJsonPath, stage, composition: "mesh" });
|
|
1284
|
+
return result;
|
|
1285
|
+
}
|
|
1286
|
+
function applyMeshLifecycleEdges(services, edges) {
|
|
1287
|
+
for (const edge of edges) {
|
|
1288
|
+
const consumer = services[edge.consumer];
|
|
1289
|
+
const old = consumer.depends_on && typeof consumer.depends_on === "object" && !Array.isArray(consumer.depends_on) ? consumer.depends_on : {};
|
|
1290
|
+
old[edge.provider] = { condition: "service_healthy" };
|
|
1291
|
+
consumer.depends_on = old;
|
|
700
1292
|
}
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
// src/core/mesh/v2/compileMeshTester.ts
|
|
1296
|
+
function refs(svc) {
|
|
1297
|
+
const out = [];
|
|
1298
|
+
const add = (v) => {
|
|
1299
|
+
if (typeof v === "string") out.push(v);
|
|
1300
|
+
};
|
|
1301
|
+
if (Array.isArray(svc.depends_on)) svc.depends_on.forEach(add);
|
|
1302
|
+
else if (svc.depends_on && typeof svc.depends_on === "object") Object.keys(svc.depends_on).forEach(add);
|
|
1303
|
+
if (Array.isArray(svc.links)) svc.links.forEach((v) => add(typeof v === "string" ? v.split(":")[0] : v));
|
|
1304
|
+
if (Array.isArray(svc.volumes_from)) svc.volumes_from.forEach((v) => add(typeof v === "string" ? v.split(":")[0] : v));
|
|
1305
|
+
if (typeof svc.network_mode === "string" && svc.network_mode.startsWith("service:")) out.push(svc.network_mode.slice(8));
|
|
1306
|
+
return out;
|
|
1307
|
+
}
|
|
1308
|
+
function referencedResources(svc, doc) {
|
|
1309
|
+
const sets = { volumes: /* @__PURE__ */ new Set(), networks: /* @__PURE__ */ new Set(), configs: /* @__PURE__ */ new Set(), secrets: /* @__PURE__ */ new Set() };
|
|
1310
|
+
for (const v of Array.isArray(svc.volumes) ? svc.volumes : []) {
|
|
1311
|
+
if (typeof v === "string") {
|
|
1312
|
+
const source = v.split(":")[0];
|
|
1313
|
+
if (doc.volumes?.[source]) sets.volumes.add(source);
|
|
1314
|
+
} else if (v && typeof v === "object" && v.type === "volume" && doc.volumes?.[v.source]) sets.volumes.add(v.source);
|
|
1315
|
+
}
|
|
1316
|
+
const nets = svc.networks;
|
|
1317
|
+
if (Array.isArray(nets)) nets.forEach((n) => {
|
|
1318
|
+
if (typeof n === "string" && doc.networks?.[n]) sets.networks.add(n);
|
|
1319
|
+
});
|
|
1320
|
+
else if (nets && typeof nets === "object") Object.keys(nets).forEach((n) => {
|
|
1321
|
+
if (doc.networks?.[n]) sets.networks.add(n);
|
|
1322
|
+
});
|
|
1323
|
+
for (const kind of ["configs", "secrets"]) {
|
|
1324
|
+
const v = svc[kind];
|
|
1325
|
+
if (Array.isArray(v)) for (const x of v) {
|
|
1326
|
+
const n = typeof x === "string" ? x : x?.source;
|
|
1327
|
+
if (typeof n === "string" && doc[kind]?.[n]) sets[kind].add(n);
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
return sets;
|
|
1331
|
+
}
|
|
1332
|
+
function compileMeshTester(meshDir, tester, endpointRegistry, effectiveTopLevelApps, stage, referenceContext) {
|
|
1333
|
+
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);
|
|
1334
|
+
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" });
|
|
1335
|
+
const included = /* @__PURE__ */ new Set(), visit = (name) => {
|
|
1336
|
+
if (included.has(name)) return;
|
|
1337
|
+
if (!raw.services[name]) throw new ConfigError({ sourceFile: file, configPath: `services.${name}`, stage, composition: "mesh", reason: "Tester service dependency does not exist" });
|
|
1338
|
+
included.add(name);
|
|
1339
|
+
for (const ref of refs(raw.services[name])) visit(ref);
|
|
1340
|
+
};
|
|
1341
|
+
visit(tester.service);
|
|
1342
|
+
for (const name of included) {
|
|
1343
|
+
const svc = raw.services[name];
|
|
1344
|
+
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" });
|
|
1345
|
+
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" });
|
|
1346
|
+
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" });
|
|
1347
|
+
}
|
|
1348
|
+
const res = { volumes: /* @__PURE__ */ new Set(), networks: /* @__PURE__ */ new Set(), configs: /* @__PURE__ */ new Set(), secrets: /* @__PURE__ */ new Set() };
|
|
1349
|
+
for (const name of included) {
|
|
1350
|
+
const own = referencedResources(raw.services[name], raw);
|
|
1351
|
+
for (const k of Object.keys(res)) for (const v of own[k]) res[k].add(v);
|
|
1352
|
+
}
|
|
1353
|
+
const selected = { services: Object.fromEntries([...included].map((k) => [k, raw.services[k]])) };
|
|
1354
|
+
for (const k of Object.keys(res)) if (res[k].size) selected[k] = Object.fromEntries([...res[k]].map((n) => [n, raw[k]?.[n]]));
|
|
1355
|
+
const ns = namespaceDependencyCompose({ namespacePrefix: "mesh-tester", document: selected });
|
|
1356
|
+
const runner = ns.serviceNameMap.get(tester.service);
|
|
1357
|
+
const runnerSvc = ns.document.services[runner];
|
|
1358
|
+
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" });
|
|
1359
|
+
runnerSvc.network_mode = "host";
|
|
1360
|
+
delete runnerSvc.networks;
|
|
1361
|
+
const meshCtx = referenceContext ?? { services: {}, bindings: /* @__PURE__ */ new Map(), endpoints: endpointRegistry, stage, meshJsonPath: meshPath };
|
|
1362
|
+
const env = tester.env ?? {};
|
|
1363
|
+
assertMeshTesterEnvPublic(env, "tester.env");
|
|
1364
|
+
runnerSvc.environment = { ...normalizeComposeEnvironment(runnerSvc.environment, "tester runner environment"), ...resolveMeshEnvMap(env, meshCtx, "tester.env") };
|
|
1365
|
+
const depends = runnerSvc.depends_on && typeof runnerSvc.depends_on === "object" && !Array.isArray(runnerSvc.depends_on) ? runnerSvc.depends_on : {};
|
|
1366
|
+
for (const app of effectiveTopLevelApps) depends[app] = { condition: "service_healthy" };
|
|
1367
|
+
runnerSvc.depends_on = depends;
|
|
1368
|
+
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 };
|
|
1369
|
+
}
|
|
1370
|
+
function assertUniqueHostPortMappings(yamlConfig) {
|
|
1371
|
+
const parsed = parse(yamlConfig);
|
|
1372
|
+
const owners = /* @__PURE__ */ new Map();
|
|
1373
|
+
for (const [serviceName, service] of Object.entries(parsed?.services ?? {})) {
|
|
1374
|
+
for (const port of service?.ports ?? []) {
|
|
1375
|
+
let hostPort = null;
|
|
1376
|
+
if (typeof port === "string") {
|
|
1377
|
+
const parts = port.split(":");
|
|
1378
|
+
if (parts.length === 2) hostPort = Number(parts[0]);
|
|
1379
|
+
if (parts.length === 3) hostPort = Number(parts[1]);
|
|
1380
|
+
} else if (port && typeof port === "object" && "published" in port) {
|
|
1381
|
+
hostPort = Number(port.published);
|
|
1382
|
+
}
|
|
1383
|
+
if (!hostPort || !Number.isInteger(hostPort)) continue;
|
|
1384
|
+
const existing = owners.get(hostPort);
|
|
1385
|
+
if (existing) {
|
|
1386
|
+
throw new ScriptError(
|
|
1387
|
+
`Port Collision Detected: Host port ${hostPort} is requested by both "${existing}" and "${serviceName}".`
|
|
1388
|
+
);
|
|
1389
|
+
}
|
|
1390
|
+
owners.set(hostPort, serviceName);
|
|
707
1391
|
}
|
|
708
|
-
} catch (err) {
|
|
709
|
-
throw new ScriptError(
|
|
710
|
-
`Invalid YAML syntax in tester docker compose (${composeRel}): ${errorMessage(err)}`
|
|
711
|
-
);
|
|
712
1392
|
}
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
// src/core/mesh/v2/compileMeshComposition.ts
|
|
1396
|
+
function mergeFragment(target, fragment, owner) {
|
|
1397
|
+
for (const key of ["services", "volumes", "networks", "configs", "secrets"]) {
|
|
1398
|
+
const incoming = fragment[key];
|
|
1399
|
+
if (!incoming) continue;
|
|
1400
|
+
const dest = target[key] ??= {};
|
|
1401
|
+
for (const [name, value] of Object.entries(incoming)) {
|
|
1402
|
+
if (name in dest) throw new ConfigError({ configPath: `${key}.${name}`, referencedObject: owner, reason: "Mesh composition name collision" });
|
|
1403
|
+
dest[name] = value;
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1407
|
+
function appendPort(service, target, published) {
|
|
1408
|
+
const ports = Array.isArray(service.ports) ? service.ports : [];
|
|
1409
|
+
ports.push({ target, published, host_ip: PUBLIC_HOST, protocol: "tcp" });
|
|
1410
|
+
service.ports = ports;
|
|
1411
|
+
}
|
|
1412
|
+
function ownerFor(pub, fragment) {
|
|
1413
|
+
return pub.target === "app" ? pub.ownerMeshService : fragment.endpoints.dependencies[pub.dependency]?.[pub.endpoint]?.networkHost ?? "";
|
|
1414
|
+
}
|
|
1415
|
+
function setEnv(service, env) {
|
|
1416
|
+
const current = service.environment && typeof service.environment === "object" && !Array.isArray(service.environment) ? service.environment : {};
|
|
1417
|
+
service.environment = { ...current, ...env };
|
|
1418
|
+
}
|
|
1419
|
+
function compileMeshComposition(stage, meshDir, options = {}) {
|
|
1420
|
+
const meshPath = path4.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);
|
|
1421
|
+
const rawName = raw.name ?? path4.basename(meshDir), projectName = deriveProjectName(rawName, stage, meshDir);
|
|
1422
|
+
const fragments = {};
|
|
1423
|
+
const compose = { name: projectName, services: {}, networks: { mesh: { driver: "bridge" } } };
|
|
1424
|
+
for (const [name, svc] of Object.entries(services).sort(([a], [b]) => a.localeCompare(b))) {
|
|
1425
|
+
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" });
|
|
1426
|
+
const suppress = new Set(Object.keys(svc.dependencyBindings));
|
|
1427
|
+
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 });
|
|
1428
|
+
fragments[name] = fragment;
|
|
1429
|
+
mergeFragment(compose, fragment.compose, name);
|
|
1430
|
+
const app = compose.services[name];
|
|
1431
|
+
const networks = { mesh: null };
|
|
1432
|
+
const localDeps = Object.keys(fragment.endpoints.dependencies).filter((dep) => !bindingMap.has(bindingKey(name, dep)) && Object.keys(fragment.effectiveBuild.dependencies[dep]?.endpoints ?? {}).length > 0);
|
|
1433
|
+
if (localDeps.length) {
|
|
1434
|
+
const privateName = `mesh--${name}`;
|
|
1435
|
+
networks[privateName] = null;
|
|
1436
|
+
compose.networks[privateName] = { driver: "bridge" };
|
|
1437
|
+
for (const dep of localDeps) {
|
|
1438
|
+
for (const ep of Object.values(fragment.endpoints.dependencies[dep] ?? {})) {
|
|
1439
|
+
const owner = ep.networkHost;
|
|
1440
|
+
const ownerService = compose.services[owner];
|
|
1441
|
+
if (ownerService) {
|
|
1442
|
+
const old = ownerService.networks && typeof ownerService.networks === "object" && !Array.isArray(ownerService.networks) ? ownerService.networks : {};
|
|
1443
|
+
old[privateName] = null;
|
|
1444
|
+
ownerService.networks = old;
|
|
1445
|
+
}
|
|
1446
|
+
}
|
|
1447
|
+
for (const generated of Object.keys(fragment.compose.services).filter((k) => k.startsWith(`svc--${name}--dep--${dep}--`))) {
|
|
1448
|
+
const ownerService = compose.services[generated];
|
|
1449
|
+
const old = ownerService.networks && typeof ownerService.networks === "object" && !Array.isArray(ownerService.networks) ? ownerService.networks : {};
|
|
1450
|
+
old[privateName] = null;
|
|
1451
|
+
ownerService.networks = old;
|
|
1452
|
+
}
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1455
|
+
app.networks = networks;
|
|
1456
|
+
}
|
|
1457
|
+
const publication = resolveMeshPublication(services, bindingMap, stage, meshPath), intents = [];
|
|
1458
|
+
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))) {
|
|
1459
|
+
const ep = services[name].effectiveBuild.app.endpoints[pub.endpoint];
|
|
1460
|
+
intents.push({ logicalPath: pub.logicalPath, requested: ep.publicPort });
|
|
1461
|
+
}
|
|
1462
|
+
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}`))) {
|
|
1463
|
+
const ep = services[name].effectiveBuild.dependencies[pub.dependency].endpoints[pub.endpoint];
|
|
1464
|
+
intents.push({ logicalPath: pub.logicalPath, requested: ep.publicPort });
|
|
1465
|
+
}
|
|
1466
|
+
const ports = allocateHostPorts(meshDir, stage, intents, Boolean(options.validationMode));
|
|
1467
|
+
const endpoints = { app: {}, dependencies: {} };
|
|
1468
|
+
for (const [name, svc] of Object.entries(services)) {
|
|
1469
|
+
endpoints.app[name] = {};
|
|
1470
|
+
for (const [epName, ep] of Object.entries(svc.effectiveBuild.app.endpoints)) {
|
|
1471
|
+
const host = name;
|
|
1472
|
+
const record = { logicalPath: `${name}.app.endpoints.${epName}`, networkHost: host, networkPort: ep.port, ...ep.scheme ? { scheme: ep.scheme } : {}, effectivelyPublished: false };
|
|
1473
|
+
endpoints.app[name][epName] = record;
|
|
1474
|
+
}
|
|
1475
|
+
endpoints.dependencies[name] = {};
|
|
1476
|
+
const fragment = fragments[name];
|
|
1477
|
+
for (const [depName, dep] of Object.entries(svc.effectiveBuild.dependencies)) {
|
|
1478
|
+
if (bindingMap.has(bindingKey(name, depName))) continue;
|
|
1479
|
+
endpoints.dependencies[name][depName] = {};
|
|
1480
|
+
for (const [epName, def] of Object.entries(dep.endpoints)) {
|
|
1481
|
+
const local = fragment.endpoints.dependencies[depName]?.[epName];
|
|
1482
|
+
if (!local) continue;
|
|
1483
|
+
endpoints.dependencies[name][depName][epName] = { ...local, logicalPath: `${name}.dependencies.${depName}.endpoints.${epName}`, effectivelyPublished: false };
|
|
1484
|
+
}
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
for (const pub of publication) {
|
|
1488
|
+
const ep = pub.target === "app" ? endpoints.app[pub.ownerMeshService]?.[pub.endpoint] : endpoints.dependencies[pub.ownerMeshService]?.[pub.dependency]?.[pub.endpoint];
|
|
1489
|
+
if (!ep) continue;
|
|
1490
|
+
ep.publicHost = PUBLIC_HOST;
|
|
1491
|
+
ep.publicPort = ports.get(pub.logicalPath);
|
|
1492
|
+
ep.effectivelyPublished = true;
|
|
1493
|
+
}
|
|
1494
|
+
for (const pub of publication) {
|
|
1495
|
+
const fragment = fragments[pub.ownerMeshService], endpoint = pub.target === "app" ? endpoints.app[pub.ownerMeshService][pub.endpoint] : endpoints.dependencies[pub.ownerMeshService][pub.dependency][pub.endpoint];
|
|
1496
|
+
const owner = ownerFor(pub, fragment);
|
|
1497
|
+
const service = compose.services[owner];
|
|
1498
|
+
if (service && endpoint) appendPort(service, endpoint.networkPort, endpoint.publicPort);
|
|
1499
|
+
}
|
|
1500
|
+
const refContext = { services, bindings: bindingMap, endpoints, stage, meshJsonPath: meshPath };
|
|
1501
|
+
for (const [name, fragment] of Object.entries(fragments)) {
|
|
1502
|
+
const app = compose.services[name];
|
|
1503
|
+
const buildEnv = resolveServiceBuildEnvThroughMesh(name, fragment.buildAppEnvironment ?? fragment.builderAppEnvironment ?? {}, refContext, `services.${name}.app.env`);
|
|
1504
|
+
const meshEnv = resolveMeshEnvMap(fragment.externalAppEnvironment ?? {}, refContext, `services.${name}.env`);
|
|
1505
|
+
setEnv(app, { ...buildEnv, ...meshEnv });
|
|
1506
|
+
for (const [depName, depEnv] of Object.entries(fragment.dependencyEnvironments ?? {})) {
|
|
1507
|
+
const logicalBinding = bindingMap.get(bindingKey(name, depName));
|
|
1508
|
+
if (logicalBinding) continue;
|
|
1509
|
+
const resolvedDep = resolveServiceBuildEnvThroughMesh(name, depEnv, refContext, `services.${name}.dependencies.${depName}.env`);
|
|
1510
|
+
const prefix = `svc--${name}--dep--${depName}--`;
|
|
1511
|
+
for (const [serviceName, service] of Object.entries(compose.services)) if (serviceName.startsWith(prefix)) setEnv(service, resolvedDep);
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
const edges = buildMeshLifecycleEdges(services, bindingMap, stage, meshPath);
|
|
1515
|
+
applyMeshLifecycleEdges(compose.services, edges);
|
|
1516
|
+
for (const [name, svc] of Object.entries(services)) for (const [sourceDep, dep] of Object.entries(svc.effectiveBuild.dependencies)) {
|
|
1517
|
+
if (bindingMap.has(bindingKey(name, sourceDep))) continue;
|
|
1518
|
+
for (const rawTarget of dep.dependsOn) {
|
|
1519
|
+
const targetKey = rawTarget.slice("dependencies.".length);
|
|
1520
|
+
const provider = bindingMap.get(bindingKey(name, targetKey));
|
|
1521
|
+
if (!provider) continue;
|
|
1522
|
+
const localEndpoints = endpoints.dependencies[name]?.[sourceDep] ?? {};
|
|
1523
|
+
for (const ep of Object.values(localEndpoints)) {
|
|
1524
|
+
const localOwner = ep.networkHost, localSvc = compose.services[localOwner];
|
|
1525
|
+
if (!localSvc) continue;
|
|
1526
|
+
const ds = localSvc.depends_on && typeof localSvc.depends_on === "object" && !Array.isArray(localSvc.depends_on) ? localSvc.depends_on : {};
|
|
1527
|
+
ds[provider] = { condition: "service_healthy" };
|
|
1528
|
+
localSvc.depends_on = ds;
|
|
1529
|
+
const net2 = localSvc.networks && typeof localSvc.networks === "object" && !Array.isArray(localSvc.networks) ? localSvc.networks : {};
|
|
1530
|
+
net2.mesh = null;
|
|
1531
|
+
localSvc.networks = net2;
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
const fullGraph = new Map(Object.keys(compose.services).map((name) => [name, /* @__PURE__ */ new Set()]));
|
|
1536
|
+
for (const [serviceName, service] of Object.entries(compose.services)) {
|
|
1537
|
+
const dependencies = service.depends_on;
|
|
1538
|
+
if (dependencies && typeof dependencies === "object" && !Array.isArray(dependencies)) for (const target of Object.keys(dependencies)) {
|
|
1539
|
+
if (fullGraph.has(target)) fullGraph.get(serviceName).add(target);
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
assertAcyclicGraph(fullGraph, { sourceFile: meshPath, stage, composition: "mesh" });
|
|
1543
|
+
let testerServiceName;
|
|
1544
|
+
if (stage === "e2e") {
|
|
1545
|
+
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? }" });
|
|
1546
|
+
const built = raw.tester ? compileMeshTester(meshDir, raw.tester, endpoints, Object.keys(services).sort(), "e2e", refContext) : void 0;
|
|
1547
|
+
if (built) {
|
|
1548
|
+
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 } : {} };
|
|
1549
|
+
mergeFragment(compose, fragment, "mesh tester");
|
|
1550
|
+
testerServiceName = built.runnerServiceName;
|
|
1551
|
+
}
|
|
719
1552
|
}
|
|
720
|
-
const
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
1553
|
+
const yaml = stringify(compose);
|
|
1554
|
+
assertUniqueHostPortMappings(yaml);
|
|
1555
|
+
return { compose, effectiveMesh: effective, loadedServices: services, endpoints, projectName, ...testerServiceName ? { testerServiceName } : {} };
|
|
1556
|
+
}
|
|
1557
|
+
|
|
1558
|
+
// src/core/mesh/checkers/checkMeshServices.ts
|
|
1559
|
+
function checkMeshServices(mesh, meshDir) {
|
|
1560
|
+
const root = resolveProjectDir(meshDir), meshPath = path4.join(root, "mesh.json");
|
|
1561
|
+
const checked = /* @__PURE__ */ new Set();
|
|
1562
|
+
for (const stage of ["dev", "prod", "test", "e2e"]) {
|
|
1563
|
+
const effective = resolveMeshStage(mesh, stage, meshPath);
|
|
1564
|
+
const services = loadEffectiveMeshServices(root, effective, stage);
|
|
1565
|
+
for (const [name, svc] of Object.entries(services)) {
|
|
1566
|
+
if (!checked.has(svc.absolutePath)) {
|
|
1567
|
+
console.log(pc22.cyan(`
|
|
1568
|
+
\u{1F50D} Checking mesh service ${name}...`));
|
|
1569
|
+
checkInfra(svc.absolutePath);
|
|
1570
|
+
checked.add(svc.absolutePath);
|
|
1571
|
+
}
|
|
1572
|
+
if (stage === "test") {
|
|
1573
|
+
const fragment = compileServiceComposition("test", svc.absolutePath, { validationMode: true, meshMode: true, deferReferenceResolution: true });
|
|
1574
|
+
const endpoints = { app: { [name]: fragment.endpoints.app }, dependencies: { [name]: fragment.endpoints.dependencies } };
|
|
1575
|
+
const ctx = { services: { [name]: svc }, bindings: /* @__PURE__ */ new Map(), endpoints, stage: "test", meshJsonPath: meshPath };
|
|
1576
|
+
for (const key of ["EXEC_MODE", "INFRA_MODE", ...Object.values(svc.effectiveBuild.app.endpoints).some((ep) => ep.primary) ? ["PORT"] : []]) {
|
|
1577
|
+
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" });
|
|
1578
|
+
}
|
|
1579
|
+
resolveServiceBuildEnvThroughMesh(name, fragment.builderAppEnvironment ?? {}, ctx, `services.${name}.app.env`);
|
|
1580
|
+
for (const [depName, depEnv] of Object.entries(fragment.dependencyEnvironments ?? {})) resolveServiceBuildEnvThroughMesh(name, depEnv, ctx, `services.${name}.dependencies.${depName}.env`);
|
|
1581
|
+
resolveMeshEnvMap(svc.meshEnv, ctx, `services.${name}.env`);
|
|
1582
|
+
}
|
|
731
1583
|
}
|
|
732
|
-
|
|
733
|
-
const dockerfilePolicyRel = testerConfig.policy?.dockerfile || "policy/dockerfile";
|
|
734
|
-
const dockerfilePolicyDir = path13.resolve(absTesterDir, dockerfilePolicyRel);
|
|
735
|
-
if (existsSync(dockerfilePolicyDir)) {
|
|
736
|
-
console.log(
|
|
737
|
-
pc22.cyan(
|
|
738
|
-
`
|
|
739
|
-
\u{1F50D} Validating Tester Dockerfile Contract (${dockerfilePolicyRel})...`
|
|
740
|
-
)
|
|
741
|
-
);
|
|
742
|
-
runStep(
|
|
743
|
-
"docker",
|
|
744
|
-
[
|
|
745
|
-
"run",
|
|
746
|
-
"--rm",
|
|
747
|
-
"--network",
|
|
748
|
-
"none",
|
|
749
|
-
"--mount",
|
|
750
|
-
`type=bind,src=${absTesterDir},dst=/project,readonly`,
|
|
751
|
-
"-w",
|
|
752
|
-
"/project",
|
|
753
|
-
CONFTEST_IMAGE,
|
|
754
|
-
"test",
|
|
755
|
-
dockerfileRel,
|
|
756
|
-
"-p",
|
|
757
|
-
`${dockerfilePolicyRel}/`
|
|
758
|
-
],
|
|
759
|
-
absTesterDir,
|
|
760
|
-
{ stepName: "E2E Tester Dockerfile Contract", targetFile: dockerfileRel }
|
|
761
|
-
);
|
|
1584
|
+
if (stage !== "test") compileMeshComposition(stage, root, { validationMode: true, allowMissingTester: true });
|
|
762
1585
|
}
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
);
|
|
770
|
-
runStep(
|
|
771
|
-
"docker",
|
|
772
|
-
[
|
|
773
|
-
"run",
|
|
774
|
-
"--rm",
|
|
775
|
-
"--network",
|
|
776
|
-
"none",
|
|
777
|
-
"--mount",
|
|
778
|
-
`type=bind,src=${absTesterDir},dst=/project,readonly`,
|
|
779
|
-
"-w",
|
|
780
|
-
"/project",
|
|
781
|
-
CONFTEST_IMAGE,
|
|
782
|
-
"test",
|
|
783
|
-
composeRel,
|
|
784
|
-
"-p",
|
|
785
|
-
`${composePolicyRel}/`,
|
|
786
|
-
"--all-namespaces"
|
|
787
|
-
],
|
|
788
|
-
absTesterDir,
|
|
789
|
-
{ stepName: "E2E Tester Compose Contract", targetFile: composeRel }
|
|
790
|
-
);
|
|
1586
|
+
}
|
|
1587
|
+
function checkMeshTester(mesh, meshDir, options = {}) {
|
|
1588
|
+
const root = resolveProjectDir(meshDir);
|
|
1589
|
+
if (!mesh.tester) {
|
|
1590
|
+
if (options.required) throw new ConfigError({ sourceFile: path4.join(root, "mesh.json"), configPath: "tester", stage: "e2e", composition: "mesh", reason: "Global mesh E2E requires root tester" });
|
|
1591
|
+
return;
|
|
791
1592
|
}
|
|
792
|
-
|
|
793
|
-
|
|
1593
|
+
const file = resolveInsideProject(root, mesh.tester.compose, { sourceFile: path4.join(root, "mesh.json"), configPath: "tester.compose", stage: "e2e" });
|
|
1594
|
+
loadComposeDocument(file, { sourceFile: path4.join(root, "mesh.json"), configPath: "tester.compose", stage: "e2e", composition: "mesh" });
|
|
1595
|
+
compileMeshComposition("e2e", root, { validationMode: true });
|
|
794
1596
|
}
|
|
795
1597
|
|
|
796
1598
|
// src/core/mesh/checkers/checkMesh.ts
|
|
@@ -801,7 +1603,7 @@ function checkMesh(meshDir = process.cwd(), options = {}) {
|
|
|
801
1603
|
checkMeshTester(mesh, absMeshDir, { required: Boolean(options.requireTester) });
|
|
802
1604
|
console.log(
|
|
803
1605
|
pc22.bold(
|
|
804
|
-
pc22.green("\n\u{1F389} All mesh infrastructure, services, and contract checks passed!\n")
|
|
1606
|
+
pc22.green("\n\u{1F389} All V2 mesh infrastructure, services, and contract checks passed!\n")
|
|
805
1607
|
)
|
|
806
1608
|
);
|
|
807
1609
|
}
|
|
@@ -840,1036 +1642,74 @@ Examples:
|
|
|
840
1642
|
}
|
|
841
1643
|
});
|
|
842
1644
|
};
|
|
843
|
-
function
|
|
844
|
-
const
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
let hostPort = null;
|
|
849
|
-
if (typeof port === "string") {
|
|
850
|
-
const parts = port.split(":");
|
|
851
|
-
if (parts.length === 2) hostPort = Number(parts[0]);
|
|
852
|
-
if (parts.length === 3) hostPort = Number(parts[1]);
|
|
853
|
-
} else if (port && typeof port === "object" && "published" in port) {
|
|
854
|
-
hostPort = Number(port.published);
|
|
855
|
-
}
|
|
856
|
-
if (!hostPort || !Number.isInteger(hostPort)) continue;
|
|
857
|
-
const existing = owners.get(hostPort);
|
|
858
|
-
if (existing) {
|
|
859
|
-
throw new ScriptError(
|
|
860
|
-
`Port Collision Detected: Host port ${hostPort} is requested by both "${existing}" and "${serviceName}".`
|
|
861
|
-
);
|
|
862
|
-
}
|
|
863
|
-
owners.set(hostPort, serviceName);
|
|
864
|
-
}
|
|
865
|
-
}
|
|
866
|
-
}
|
|
867
|
-
|
|
868
|
-
// src/utils/dependencyPorts.ts
|
|
869
|
-
var EXPLICIT_PORT_MAPPING = /^([1-9]\d{0,4}):([1-9]\d{0,4})$/;
|
|
870
|
-
function assertValidPort(port, label) {
|
|
871
|
-
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
872
|
-
throw new ScriptError(`${label} must be between 1 and 65535.`);
|
|
873
|
-
}
|
|
874
|
-
}
|
|
875
|
-
function parseExplicitPortMapping(value, context = "Dependency port") {
|
|
876
|
-
const match = EXPLICIT_PORT_MAPPING.exec(value.trim());
|
|
877
|
-
if (!match) {
|
|
878
|
-
throw new ScriptError(`${context} "${value}" must use "HOST_PORT:CONTAINER_PORT".`);
|
|
879
|
-
}
|
|
880
|
-
const hostPort = Number(match[1]);
|
|
881
|
-
const containerPort = Number(match[2]);
|
|
882
|
-
assertValidPort(hostPort, `${context} host port`);
|
|
883
|
-
assertValidPort(containerPort, `${context} container port`);
|
|
884
|
-
return { raw: `${hostPort}:${containerPort}`, hostPort, containerPort };
|
|
885
|
-
}
|
|
886
|
-
function normalizePrimaryDependencyPort(value, context = "Dependency port") {
|
|
887
|
-
if (typeof value === "number") {
|
|
888
|
-
assertValidPort(value, `${context} host port`);
|
|
889
|
-
return { raw: `${value}:3000`, hostPort: value, containerPort: 3e3 };
|
|
890
|
-
}
|
|
891
|
-
const trimmed = value.trim();
|
|
892
|
-
if (/^[1-9]\d{0,4}$/.test(trimmed)) {
|
|
893
|
-
const hostPort = Number(trimmed);
|
|
894
|
-
assertValidPort(hostPort, `${context} host port`);
|
|
895
|
-
return { raw: `${hostPort}:3000`, hostPort, containerPort: 3e3 };
|
|
896
|
-
}
|
|
897
|
-
return parseExplicitPortMapping(trimmed, context);
|
|
898
|
-
}
|
|
899
|
-
function getDependencyPortMappings(dependency, context = "Dependency") {
|
|
900
|
-
const mappings = [];
|
|
901
|
-
if (dependency.port !== void 0) {
|
|
902
|
-
mappings.push(normalizePrimaryDependencyPort(dependency.port, `${context} primary port`));
|
|
1645
|
+
function compileMeshEnvironment(stage, rawMeshDir = process.cwd(), options = {}) {
|
|
1646
|
+
const meshDir = resolveProjectDir(rawMeshDir), compiled = compileMeshComposition(stage, meshDir), yaml = stringify(compiled.compose);
|
|
1647
|
+
if (options.validateWithDocker !== false) {
|
|
1648
|
+
const result = spawnSync("docker", ["compose", "--project-directory", meshDir, "-f", "-", "config", "--quiet"], { cwd: meshDir, encoding: "utf-8", input: yaml });
|
|
1649
|
+
if (result.error || result.status !== 0) throw new ScriptError(`Generated mesh Compose configuration is invalid: ${result.error?.message ?? result.stderr ?? result.stdout}`, { cause: result.error });
|
|
903
1650
|
}
|
|
904
|
-
|
|
905
|
-
mappings.push(parseExplicitPortMapping(value, `${context} auxiliary port`));
|
|
906
|
-
}
|
|
907
|
-
return [...new Map(mappings.map((mapping) => [mapping.raw, mapping])).values()];
|
|
1651
|
+
return { yaml, ...compiled.testerServiceName ? { testerServiceName: compiled.testerServiceName } : {} };
|
|
908
1652
|
}
|
|
909
|
-
var
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
var
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
var buildDependencySchema = z.object({
|
|
917
|
-
path: z.string({ required_error: 'Dependency "path" is required' }).describe("Relative path to mock Docker Compose file"),
|
|
918
|
-
service: z.string().optional().describe("Target service name in the mock compose file"),
|
|
919
|
-
port: z.union([z.number(), z.string()]).optional().describe("Host port to map to this dependency locally"),
|
|
920
|
-
ports: z.array(auxiliaryPortMappingSchema).optional().describe("Additional explicit HOST_PORT:CONTAINER_PORT mappings for local dependency tooling")
|
|
921
|
-
}).strict().describe("Service dependency specification");
|
|
922
|
-
var buildOverrideSchema = z.object({
|
|
923
|
-
path: z.string({ required_error: 'Override "path" is required' }).describe("Relative path to the environment stage override file")
|
|
924
|
-
}).strict().describe("Environment override specification");
|
|
925
|
-
var buildTesterSchema = z.object({
|
|
926
|
-
envOverrides: z.record(z.string(), z.string()).optional().describe(
|
|
927
|
-
"Environment variable overrides for the individual E2E tester with URL templating"
|
|
928
|
-
)
|
|
929
|
-
}).strict().describe("E2E tester configuration");
|
|
930
|
-
var buildJsonSchema = z.object({
|
|
931
|
-
$schema: z.string().optional().describe("JSON Schema URL or relative path"),
|
|
932
|
-
name: z.string().optional().describe("Service project name"),
|
|
933
|
-
dockerfile: z.string().optional().describe("Relative path to the Dockerfile (defaults to 'Dockerfile')"),
|
|
934
|
-
port: z.union([z.number(), z.string()]).optional().describe(
|
|
935
|
-
"Host port exposed by this service when listening publicly"
|
|
936
|
-
),
|
|
937
|
-
policy: buildPolicyConfigSchema.optional(),
|
|
938
|
-
policies: buildPolicyConfigSchema.optional(),
|
|
939
|
-
composeFiles: z.array(z.string()).optional().describe("Additional compose files to merge"),
|
|
940
|
-
dependencies: z.record(z.string(), buildDependencySchema).optional().describe("Service dependencies and mocks"),
|
|
941
|
-
envOverrides: z.record(z.string(), z.string()).optional().describe("Environment variable overrides for the app service with URL templating"),
|
|
942
|
-
overrides: z.record(
|
|
943
|
-
z.enum(["dev", "prod", "test", "e2e"]),
|
|
944
|
-
buildOverrideSchema
|
|
945
|
-
).optional().describe("Stage overrides (dev, prod, test, e2e)"),
|
|
946
|
-
services: z.record(z.string(), z.any()).optional().describe("Additional Docker Compose service overrides"),
|
|
947
|
-
tester: buildTesterSchema.optional()
|
|
948
|
-
}).strict().describe("Solid Stack service build and deployment configuration");
|
|
949
|
-
|
|
950
|
-
// src/utils/extractBuildDeps.ts
|
|
951
|
-
var extractBuildDeps = (buildJson, projectDir = process.cwd()) => {
|
|
952
|
-
if (!buildJson || typeof buildJson !== "object") {
|
|
953
|
-
return [];
|
|
954
|
-
}
|
|
955
|
-
if (!("dependencies" in buildJson) || !buildJson.dependencies) {
|
|
956
|
-
return [];
|
|
957
|
-
}
|
|
958
|
-
const schema = z.object({
|
|
959
|
-
dependencies: z.record(z.string(), buildDependencySchema)
|
|
960
|
-
});
|
|
961
|
-
const result = schema.safeParse(buildJson);
|
|
962
|
-
if (!result.success) {
|
|
963
|
-
const errorDetails = result.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ");
|
|
964
|
-
throw new ScriptError(
|
|
965
|
-
`Invalid build.json structure for dependencies: ${errorDetails}`
|
|
966
|
-
);
|
|
967
|
-
}
|
|
968
|
-
const dependenciesData = result.data.dependencies;
|
|
969
|
-
const dependencies = Object.entries(dependenciesData || {}).map(
|
|
970
|
-
([name, service]) => {
|
|
971
|
-
return {
|
|
972
|
-
path: path13.resolve(projectDir, service.path),
|
|
973
|
-
name,
|
|
974
|
-
serviceName: service.service,
|
|
975
|
-
port: service.port,
|
|
976
|
-
ports: service.ports
|
|
977
|
-
};
|
|
978
|
-
}
|
|
979
|
-
);
|
|
980
|
-
return dependencies;
|
|
981
|
-
};
|
|
982
|
-
var VALID_STAGES = ["dev", "prod", "test", "e2e"];
|
|
983
|
-
var extractOverrides = (buildJson, projectDir = process.cwd()) => {
|
|
984
|
-
if (!buildJson || typeof buildJson !== "object") {
|
|
985
|
-
return {};
|
|
986
|
-
}
|
|
987
|
-
if (!("overrides" in buildJson) || !buildJson.overrides) {
|
|
988
|
-
return {};
|
|
989
|
-
}
|
|
990
|
-
const schema = z.object({
|
|
991
|
-
overrides: z.record(
|
|
992
|
-
z.enum(VALID_STAGES, {
|
|
993
|
-
errorMap: () => ({
|
|
994
|
-
message: `Unknown stage override. Supported stages are: ${VALID_STAGES.join(", ")}`
|
|
995
|
-
})
|
|
996
|
-
}),
|
|
997
|
-
z.object({
|
|
998
|
-
path: z.string({ required_error: "Override 'path' is required" })
|
|
999
|
-
})
|
|
1000
|
-
)
|
|
1001
|
-
});
|
|
1002
|
-
const result = schema.safeParse(buildJson);
|
|
1003
|
-
if (!result.success) {
|
|
1004
|
-
const errorDetails = result.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ");
|
|
1005
|
-
throw new ScriptError(
|
|
1006
|
-
`Invalid build.json structure for overrides: ${errorDetails}`
|
|
1007
|
-
);
|
|
1008
|
-
}
|
|
1009
|
-
const resolvedOverrides = {};
|
|
1010
|
-
for (const [key, value] of Object.entries(result.data.overrides)) {
|
|
1011
|
-
resolvedOverrides[key] = {
|
|
1012
|
-
path: path13.resolve(projectDir, value.path)
|
|
1013
|
-
};
|
|
1014
|
-
}
|
|
1015
|
-
return resolvedOverrides;
|
|
1653
|
+
var activeComposeSet = /* @__PURE__ */ new Set();
|
|
1654
|
+
var signalHandlersRegistered = false;
|
|
1655
|
+
var activeChildProcess = null;
|
|
1656
|
+
var isTearingDown = false;
|
|
1657
|
+
var isShuttingDown = false;
|
|
1658
|
+
var isProcessAlive = (c) => {
|
|
1659
|
+
return Boolean(c && c.exitCode === null && c.signalCode === null);
|
|
1016
1660
|
};
|
|
1017
|
-
function
|
|
1018
|
-
|
|
1019
|
-
if (!
|
|
1020
|
-
|
|
1661
|
+
function setActiveChild(child) {
|
|
1662
|
+
activeChildProcess = child;
|
|
1663
|
+
if (!child) {
|
|
1664
|
+
isShuttingDown = false;
|
|
1021
1665
|
}
|
|
1022
|
-
return normalized;
|
|
1023
1666
|
}
|
|
1024
|
-
function
|
|
1025
|
-
|
|
1026
|
-
if (options.hash && projectDir) ;
|
|
1027
|
-
if (!stage) {
|
|
1028
|
-
return base;
|
|
1029
|
-
}
|
|
1030
|
-
const s = stage.toLowerCase();
|
|
1031
|
-
if (s === "dev") {
|
|
1032
|
-
return base;
|
|
1033
|
-
}
|
|
1034
|
-
if (s === "prod") {
|
|
1035
|
-
return `${base}-prod`;
|
|
1036
|
-
}
|
|
1037
|
-
if (s === "test" || s === "test-unit") {
|
|
1038
|
-
return `${base}-test`;
|
|
1039
|
-
}
|
|
1040
|
-
if (s === "e2e" || s === "test-e2e") {
|
|
1041
|
-
return `${base}-e2e`;
|
|
1042
|
-
}
|
|
1043
|
-
return `${base}-${s}`;
|
|
1667
|
+
function setTearingDown(tearingDown) {
|
|
1668
|
+
isTearingDown = tearingDown;
|
|
1044
1669
|
}
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
const rawProjectName = mesh.name || path13.basename(meshDir);
|
|
1051
|
-
const projectName = deriveProjectName(
|
|
1052
|
-
rawProjectName,
|
|
1053
|
-
options.includeTester ? "e2e" : mode
|
|
1054
|
-
);
|
|
1055
|
-
const composeConfig = {
|
|
1056
|
-
name: projectName,
|
|
1057
|
-
networks: {
|
|
1058
|
-
mesh: {}
|
|
1059
|
-
},
|
|
1060
|
-
services: {}
|
|
1670
|
+
function registerActiveCompose(yamlConfig, projectDir, options = {}) {
|
|
1671
|
+
const entry = {
|
|
1672
|
+
yamlConfig,
|
|
1673
|
+
projectDir,
|
|
1674
|
+
removeVolumes: options.removeVolumes
|
|
1061
1675
|
};
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1676
|
+
activeComposeSet.add(entry);
|
|
1677
|
+
ensureSignalHandlers();
|
|
1678
|
+
return () => {
|
|
1679
|
+
activeComposeSet.delete(entry);
|
|
1680
|
+
};
|
|
1681
|
+
}
|
|
1682
|
+
function ensureSignalHandlers() {
|
|
1683
|
+
if (signalHandlersRegistered) return;
|
|
1684
|
+
signalHandlersRegistered = true;
|
|
1685
|
+
const handleSignal = (signal) => {
|
|
1686
|
+
if (isTearingDown) {
|
|
1687
|
+
return;
|
|
1071
1688
|
}
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1689
|
+
if (activeChildProcess && isProcessAlive(activeChildProcess)) {
|
|
1690
|
+
const child = activeChildProcess;
|
|
1691
|
+
if (signal === "SIGINT") {
|
|
1692
|
+
if (!isShuttingDown) {
|
|
1693
|
+
isShuttingDown = true;
|
|
1694
|
+
setTimeout(() => {
|
|
1695
|
+
if (isProcessAlive(child)) {
|
|
1696
|
+
try {
|
|
1697
|
+
child.kill("SIGKILL");
|
|
1698
|
+
} catch {
|
|
1699
|
+
}
|
|
1700
|
+
}
|
|
1701
|
+
}, 1e4).unref();
|
|
1702
|
+
return;
|
|
1703
|
+
}
|
|
1704
|
+
try {
|
|
1705
|
+
child.kill("SIGINT");
|
|
1706
|
+
} catch {
|
|
1080
1707
|
}
|
|
1081
|
-
return
|
|
1708
|
+
return;
|
|
1082
1709
|
}
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
}
|
|
1086
|
-
return vol;
|
|
1087
|
-
});
|
|
1088
|
-
}
|
|
1089
|
-
function rewriteServiceSecret(svc, oldKey, newKey) {
|
|
1090
|
-
if (!svc || !svc.secrets) return;
|
|
1091
|
-
if (Array.isArray(svc.secrets)) {
|
|
1092
|
-
svc.secrets = svc.secrets.map((sec) => {
|
|
1093
|
-
if (sec === oldKey) return newKey;
|
|
1094
|
-
if (typeof sec === "object" && sec.source === oldKey) {
|
|
1095
|
-
return { ...sec, source: newKey };
|
|
1096
|
-
}
|
|
1097
|
-
return sec;
|
|
1098
|
-
});
|
|
1099
|
-
}
|
|
1100
|
-
}
|
|
1101
|
-
function rewriteServiceConfig(svc, oldKey, newKey) {
|
|
1102
|
-
if (!svc || !svc.configs) return;
|
|
1103
|
-
if (Array.isArray(svc.configs)) {
|
|
1104
|
-
svc.configs = svc.configs.map((cfg) => {
|
|
1105
|
-
if (cfg === oldKey) return newKey;
|
|
1106
|
-
if (typeof cfg === "object" && cfg.source === oldKey) {
|
|
1107
|
-
return { ...cfg, source: newKey };
|
|
1108
|
-
}
|
|
1109
|
-
return cfg;
|
|
1110
|
-
});
|
|
1111
|
-
}
|
|
1112
|
-
}
|
|
1113
|
-
function mergeAndNamespaceMockResources(parsed, namespacePrefix, baseDir, targetMeshDir) {
|
|
1114
|
-
if (!parsed || typeof parsed !== "object") return;
|
|
1115
|
-
if (parsed.volumes && typeof parsed.volumes === "object") {
|
|
1116
|
-
composeConfig.volumes = composeConfig.volumes || {};
|
|
1117
|
-
for (const [volKey, volDef] of Object.entries(parsed.volumes)) {
|
|
1118
|
-
const namespacedVolKey = `${namespacePrefix}_${volKey}`;
|
|
1119
|
-
composeConfig.volumes[namespacedVolKey] = volDef ?? {};
|
|
1120
|
-
if (parsed.services && typeof parsed.services === "object") {
|
|
1121
|
-
for (const svc of Object.values(parsed.services)) {
|
|
1122
|
-
rewriteServiceVolume(svc, volKey, namespacedVolKey);
|
|
1123
|
-
}
|
|
1124
|
-
}
|
|
1125
|
-
}
|
|
1126
|
-
}
|
|
1127
|
-
if (parsed.secrets && typeof parsed.secrets === "object") {
|
|
1128
|
-
composeConfig.secrets = composeConfig.secrets || {};
|
|
1129
|
-
for (const [secKey, secDef] of Object.entries(parsed.secrets)) {
|
|
1130
|
-
const namespacedSecKey = `${namespacePrefix}_${secKey}`;
|
|
1131
|
-
const clonedDef = { ...secDef };
|
|
1132
|
-
if (clonedDef.file) {
|
|
1133
|
-
clonedDef.file = toComposePath(targetMeshDir, path13.resolve(baseDir, clonedDef.file));
|
|
1134
|
-
}
|
|
1135
|
-
composeConfig.secrets[namespacedSecKey] = clonedDef;
|
|
1136
|
-
if (parsed.services && typeof parsed.services === "object") {
|
|
1137
|
-
for (const svc of Object.values(parsed.services)) {
|
|
1138
|
-
rewriteServiceSecret(svc, secKey, namespacedSecKey);
|
|
1139
|
-
}
|
|
1140
|
-
}
|
|
1141
|
-
}
|
|
1142
|
-
}
|
|
1143
|
-
if (parsed.configs && typeof parsed.configs === "object") {
|
|
1144
|
-
composeConfig.configs = composeConfig.configs || {};
|
|
1145
|
-
for (const [cfgKey, cfgDef] of Object.entries(parsed.configs)) {
|
|
1146
|
-
const namespacedCfgKey = `${namespacePrefix}_${cfgKey}`;
|
|
1147
|
-
const clonedDef = { ...cfgDef };
|
|
1148
|
-
if (clonedDef.file) {
|
|
1149
|
-
clonedDef.file = toComposePath(targetMeshDir, path13.resolve(baseDir, clonedDef.file));
|
|
1150
|
-
}
|
|
1151
|
-
composeConfig.configs[namespacedCfgKey] = clonedDef;
|
|
1152
|
-
if (parsed.services && typeof parsed.services === "object") {
|
|
1153
|
-
for (const svc of Object.values(parsed.services)) {
|
|
1154
|
-
rewriteServiceConfig(svc, cfgKey, namespacedCfgKey);
|
|
1155
|
-
}
|
|
1156
|
-
}
|
|
1157
|
-
}
|
|
1158
|
-
}
|
|
1159
|
-
}
|
|
1160
|
-
function applyInternalMockDependsOnMapping(svc, mapping) {
|
|
1161
|
-
if (!svc.depends_on) return;
|
|
1162
|
-
if (Array.isArray(svc.depends_on)) {
|
|
1163
|
-
svc.depends_on = svc.depends_on.map((d) => mapping.get(d) || d);
|
|
1164
|
-
} else if (typeof svc.depends_on === "object") {
|
|
1165
|
-
const newDepends = {};
|
|
1166
|
-
for (const [k, v] of Object.entries(svc.depends_on)) {
|
|
1167
|
-
newDepends[mapping.get(k) || k] = v;
|
|
1168
|
-
}
|
|
1169
|
-
svc.depends_on = newDepends;
|
|
1170
|
-
}
|
|
1171
|
-
}
|
|
1172
|
-
function registerService(key, serviceDef, origin) {
|
|
1173
|
-
if (composeConfig.services[key]) {
|
|
1174
|
-
throw new ScriptError(
|
|
1175
|
-
`Service name collision in mesh compose configuration: Service "${key}" from ${origin} conflicts with an existing service definition.`
|
|
1176
|
-
);
|
|
1177
|
-
}
|
|
1178
|
-
composeConfig.services[key] = serviceDef;
|
|
1179
|
-
}
|
|
1180
|
-
for (const serviceName of Object.keys(mesh.services)) {
|
|
1181
|
-
composeConfig.networks[`${serviceName}_net`] = {};
|
|
1182
|
-
}
|
|
1183
|
-
if (mesh.dependencies && typeof mesh.dependencies === "object") {
|
|
1184
|
-
for (const [depKey, depDef] of Object.entries(mesh.dependencies)) {
|
|
1185
|
-
const depComposePath = path13.resolve(meshDir, depDef.path);
|
|
1186
|
-
if (!existsSync(depComposePath)) {
|
|
1187
|
-
throw new ScriptError(
|
|
1188
|
-
`Root dependency compose file not found: ${depComposePath}`
|
|
1189
|
-
);
|
|
1190
|
-
}
|
|
1191
|
-
const raw = readFileSync(depComposePath, "utf-8");
|
|
1192
|
-
const parsed = parse(raw);
|
|
1193
|
-
if (!parsed?.services || typeof parsed.services !== "object") {
|
|
1194
|
-
throw new ScriptError(
|
|
1195
|
-
`Root dependency compose file "${depDef.path}" does not define any services.`
|
|
1196
|
-
);
|
|
1197
|
-
}
|
|
1198
|
-
mergeAndNamespaceMockResources(parsed, `mesh_${depKey}`, meshDir, meshDir);
|
|
1199
|
-
const targetServiceName = depDef.service || Object.keys(parsed.services)[0];
|
|
1200
|
-
const serviceEntry = targetServiceName ? parsed.services[targetServiceName] : void 0;
|
|
1201
|
-
if (!serviceEntry) {
|
|
1202
|
-
throw new ScriptError(
|
|
1203
|
-
`Service "${targetServiceName}" not found in root dependency compose file: ${depComposePath}`
|
|
1204
|
-
);
|
|
1205
|
-
}
|
|
1206
|
-
const sidecarMapping = /* @__PURE__ */ new Map();
|
|
1207
|
-
for (const sName of Object.keys(parsed.services)) {
|
|
1208
|
-
if (sName === targetServiceName) {
|
|
1209
|
-
sidecarMapping.set(sName, depKey);
|
|
1210
|
-
} else {
|
|
1211
|
-
const companionKey = `${depKey}-${sName}`;
|
|
1212
|
-
sidecarMapping.set(sName, composeConfig.services[sName] ? companionKey : sName);
|
|
1213
|
-
}
|
|
1214
|
-
}
|
|
1215
|
-
const resolvedService = resolveServicePaths(serviceEntry, meshDir, meshDir);
|
|
1216
|
-
delete resolvedService.container_name;
|
|
1217
|
-
normalizeDependsOn(resolvedService);
|
|
1218
|
-
applyInternalMockDependsOnMapping(resolvedService, sidecarMapping);
|
|
1219
|
-
resolvedService.networks = {
|
|
1220
|
-
mesh: {
|
|
1221
|
-
aliases: [depKey, targetServiceName].filter(Boolean)
|
|
1222
|
-
}
|
|
1223
|
-
};
|
|
1224
|
-
registerService(depKey, resolvedService, `root dependency "${depKey}"`);
|
|
1225
|
-
for (const [sName, sDef] of Object.entries(parsed.services)) {
|
|
1226
|
-
if (sName !== targetServiceName) {
|
|
1227
|
-
const finalKey = sidecarMapping.get(sName);
|
|
1228
|
-
const companion = resolveServicePaths(sDef, meshDir, meshDir);
|
|
1229
|
-
delete companion.container_name;
|
|
1230
|
-
normalizeDependsOn(companion);
|
|
1231
|
-
applyInternalMockDependsOnMapping(companion, sidecarMapping);
|
|
1232
|
-
companion.networks = {
|
|
1233
|
-
mesh: {
|
|
1234
|
-
aliases: [sName, finalKey]
|
|
1235
|
-
}
|
|
1236
|
-
};
|
|
1237
|
-
registerService(finalKey, companion, `companion of root dependency "${depKey}"`);
|
|
1238
|
-
}
|
|
1239
|
-
}
|
|
1240
|
-
}
|
|
1241
|
-
}
|
|
1242
|
-
const providerAliases = /* @__PURE__ */ new Map();
|
|
1243
|
-
for (const sName of Object.keys(mesh.services)) {
|
|
1244
|
-
providerAliases.set(sName, /* @__PURE__ */ new Set());
|
|
1245
|
-
}
|
|
1246
|
-
const globalDepAliasToProvider = /* @__PURE__ */ new Map();
|
|
1247
|
-
const INTERNAL_PORT = 3e3;
|
|
1248
|
-
const serviceUrls = /* @__PURE__ */ new Map();
|
|
1249
|
-
const allocatedPorts = /* @__PURE__ */ new Map();
|
|
1250
|
-
function claimPort(portVal, ownerDesc) {
|
|
1251
|
-
if (!portVal) return;
|
|
1252
|
-
const portStr = String(portVal);
|
|
1253
|
-
const hostPort = portStr.includes(":") ? portStr.split(":")[0] : portStr;
|
|
1254
|
-
if (!hostPort) return;
|
|
1255
|
-
if (allocatedPorts.has(hostPort)) {
|
|
1256
|
-
throw new ScriptError(
|
|
1257
|
-
`\u274C Port Collision Detected: Host port ${hostPort} is requested by both [${allocatedPorts.get(hostPort)}] and [${ownerDesc}].`
|
|
1258
|
-
);
|
|
1259
|
-
}
|
|
1260
|
-
allocatedPorts.set(hostPort, ownerDesc);
|
|
1261
|
-
}
|
|
1262
|
-
for (const [serviceName, serviceConfig] of Object.entries(mesh.services)) {
|
|
1263
|
-
const serviceDir = path13.resolve(meshDir, serviceConfig.path);
|
|
1264
|
-
const serviceBuildJson = getBuildJson(serviceDir);
|
|
1265
|
-
const serviceDeps = extractBuildDeps(serviceBuildJson, serviceDir);
|
|
1266
|
-
let publicPort = null;
|
|
1267
|
-
if (serviceConfig.port !== void 0 && serviceConfig.port !== null && serviceConfig.port !== "") {
|
|
1268
|
-
publicPort = serviceConfig.port;
|
|
1269
|
-
claimPort(publicPort, `mesh service "${serviceName}"`);
|
|
1270
|
-
} else if (serviceConfig.preservePort && serviceBuildJson.port) {
|
|
1271
|
-
publicPort = serviceBuildJson.port;
|
|
1272
|
-
claimPort(publicPort, `mesh service "${serviceName}" (via preservePort)`);
|
|
1273
|
-
}
|
|
1274
|
-
const provideMap = {
|
|
1275
|
-
...serviceConfig.replaceMocks || {},
|
|
1276
|
-
...serviceConfig.provideDependency || {}
|
|
1277
|
-
};
|
|
1278
|
-
for (const dep of serviceDeps) {
|
|
1279
|
-
if (provideMap[dep.name] || mesh.dependencies?.[dep.name]) continue;
|
|
1280
|
-
for (const mapping of getDependencyPortMappings(dep, `Local dependency "${dep.name}" of service "${serviceName}"`)) {
|
|
1281
|
-
claimPort(mapping.raw, `local dependency "${dep.name}" of service "${serviceName}"`);
|
|
1282
|
-
}
|
|
1283
|
-
}
|
|
1284
|
-
const hostPort = publicPort ? String(publicPort).includes(":") ? String(publicPort).split(":")[0] : String(publicPort) : null;
|
|
1285
|
-
serviceUrls.set(serviceName, {
|
|
1286
|
-
networkUrl: `http://${serviceName}:${INTERNAL_PORT}`,
|
|
1287
|
-
publicUrl: hostPort ? `http://localhost:${hostPort}` : null
|
|
1288
|
-
});
|
|
1289
|
-
}
|
|
1290
|
-
function escapeRegExp(string) {
|
|
1291
|
-
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1292
|
-
}
|
|
1293
|
-
function interpolateEnvTemplates(value, context) {
|
|
1294
|
-
if (typeof value !== "string") {
|
|
1295
|
-
return value;
|
|
1296
|
-
}
|
|
1297
|
-
if (!options.silenceWarnings && context.includes("Tester") && value.includes(".network_url")) {
|
|
1298
|
-
console.warn(
|
|
1299
|
-
pc22.yellow(`
|
|
1300
|
-
\u26A0\uFE0F WARNING: You are passing a '.network_url' template to the E2E tester ("${value}"). Since the tester runs in 'network_mode: host', it cannot resolve internal Docker DNS. Use '.public_url' instead. (Mute with --silence-warnings)
|
|
1301
|
-
`)
|
|
1302
|
-
);
|
|
1303
|
-
}
|
|
1304
|
-
let interpolated = value;
|
|
1305
|
-
for (const [sName, urls] of serviceUrls.entries()) {
|
|
1306
|
-
interpolated = interpolated.replace(
|
|
1307
|
-
new RegExp(`\\$\\{${escapeRegExp(sName)}\\.network_url\\}`, "g"),
|
|
1308
|
-
urls.networkUrl
|
|
1309
|
-
);
|
|
1310
|
-
if (urls.publicUrl) {
|
|
1311
|
-
interpolated = interpolated.replace(
|
|
1312
|
-
new RegExp(`\\$\\{${escapeRegExp(sName)}\\.public_url\\}`, "g"),
|
|
1313
|
-
urls.publicUrl
|
|
1314
|
-
);
|
|
1315
|
-
}
|
|
1316
|
-
}
|
|
1317
|
-
const unresolvedMatch = interpolated.match(/\$\{([^}]+?)\.(network_url|public_url)\}/);
|
|
1318
|
-
if (unresolvedMatch) {
|
|
1319
|
-
const variable = unresolvedMatch[0];
|
|
1320
|
-
const targetService = unresolvedMatch[1];
|
|
1321
|
-
const type = unresolvedMatch[2];
|
|
1322
|
-
if (!serviceUrls.has(targetService)) {
|
|
1323
|
-
throw new ScriptError(
|
|
1324
|
-
`[${context}] Unresolved template variable: ${variable}. Service "${targetService}" is not defined in mesh.json.`
|
|
1325
|
-
);
|
|
1326
|
-
} else if (type === "public_url") {
|
|
1327
|
-
throw new ScriptError(
|
|
1328
|
-
`[${context}] Unresolved template variable: ${variable}. Service "${targetService}" does not expose a public port (missing 'port' or 'preservePort' in mesh.json).`
|
|
1329
|
-
);
|
|
1330
|
-
} else {
|
|
1331
|
-
throw new ScriptError(`[${context}] Unresolved template variable: ${variable}.`);
|
|
1332
|
-
}
|
|
1333
|
-
}
|
|
1334
|
-
return interpolated;
|
|
1335
|
-
}
|
|
1336
|
-
for (const [serviceName, serviceConfig] of Object.entries(mesh.services)) {
|
|
1337
|
-
const serviceDir = path13.resolve(meshDir, serviceConfig.path);
|
|
1338
|
-
const serviceBuildJson = getBuildJson(serviceDir);
|
|
1339
|
-
const serviceOverrides = extractOverrides(serviceBuildJson, serviceDir);
|
|
1340
|
-
const serviceDeps = extractBuildDeps(serviceBuildJson, serviceDir);
|
|
1341
|
-
const relServiceDir = toComposePath(meshDir, serviceDir);
|
|
1342
|
-
const dockerfile = serviceBuildJson.dockerfile || "Dockerfile";
|
|
1343
|
-
const environment = {
|
|
1344
|
-
INFRA_MODE: "integrated",
|
|
1345
|
-
EXEC_MODE: mode
|
|
1346
|
-
};
|
|
1347
|
-
let overrideVolumes = [];
|
|
1348
|
-
let overrideHealthcheck = void 0;
|
|
1349
|
-
let overrideCommand = void 0;
|
|
1350
|
-
let overrideApp = void 0;
|
|
1351
|
-
const stageOverride = serviceOverrides[mode];
|
|
1352
|
-
if (stageOverride && existsSync(stageOverride.path)) {
|
|
1353
|
-
try {
|
|
1354
|
-
const overrideYaml = parse(readFileSync(stageOverride.path, "utf-8"));
|
|
1355
|
-
mergeTopLevelResources(overrideYaml);
|
|
1356
|
-
overrideApp = overrideYaml?.services?.app || overrideYaml?.services?.[serviceName];
|
|
1357
|
-
if (!overrideApp && overrideYaml?.services && Object.keys(overrideYaml.services).length > 0) {
|
|
1358
|
-
throw new ScriptError(
|
|
1359
|
-
`Override file "${stageOverride.path}" must define service "app" or "${serviceName}".`
|
|
1360
|
-
);
|
|
1361
|
-
}
|
|
1362
|
-
if (overrideApp) {
|
|
1363
|
-
if (Array.isArray(overrideApp.environment)) {
|
|
1364
|
-
for (const item of overrideApp.environment) {
|
|
1365
|
-
const eqIdx = item.indexOf("=");
|
|
1366
|
-
if (eqIdx !== -1) {
|
|
1367
|
-
environment[item.slice(0, eqIdx)] = item.slice(eqIdx + 1);
|
|
1368
|
-
} else {
|
|
1369
|
-
environment[item] = process.env[item] ?? null;
|
|
1370
|
-
}
|
|
1371
|
-
}
|
|
1372
|
-
} else if (overrideApp.environment && typeof overrideApp.environment === "object") {
|
|
1373
|
-
Object.assign(environment, overrideApp.environment);
|
|
1374
|
-
}
|
|
1375
|
-
if (overrideApp.command) {
|
|
1376
|
-
overrideCommand = overrideApp.command;
|
|
1377
|
-
}
|
|
1378
|
-
if (Array.isArray(overrideApp.volumes)) {
|
|
1379
|
-
overrideVolumes = overrideApp.volumes.map(
|
|
1380
|
-
(vol) => resolveVolumeEntry(vol, serviceDir, meshDir)
|
|
1381
|
-
);
|
|
1382
|
-
}
|
|
1383
|
-
if (overrideApp.healthcheck) {
|
|
1384
|
-
overrideHealthcheck = overrideApp.healthcheck;
|
|
1385
|
-
}
|
|
1386
|
-
}
|
|
1387
|
-
} catch (err) {
|
|
1388
|
-
if (err instanceof ScriptError) throw err;
|
|
1389
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
1390
|
-
throw new ScriptError(
|
|
1391
|
-
`Failed to parse override file ${stageOverride.path}: ${msg}`
|
|
1392
|
-
);
|
|
1393
|
-
}
|
|
1394
|
-
}
|
|
1395
|
-
environment.PORT = String(INTERNAL_PORT);
|
|
1396
|
-
const buildArgs = {};
|
|
1397
|
-
if (overrideApp?.build?.args) {
|
|
1398
|
-
if (Array.isArray(overrideApp.build.args)) {
|
|
1399
|
-
for (const item of overrideApp.build.args) {
|
|
1400
|
-
if (typeof item === "string") {
|
|
1401
|
-
const eqIdx = item.indexOf("=");
|
|
1402
|
-
if (eqIdx !== -1) {
|
|
1403
|
-
buildArgs[item.slice(0, eqIdx)] = item.slice(eqIdx + 1);
|
|
1404
|
-
} else {
|
|
1405
|
-
buildArgs[item] = process.env[item] ?? null;
|
|
1406
|
-
}
|
|
1407
|
-
}
|
|
1408
|
-
}
|
|
1409
|
-
} else if (typeof overrideApp.build.args === "object") {
|
|
1410
|
-
Object.assign(buildArgs, overrideApp.build.args);
|
|
1411
|
-
}
|
|
1412
|
-
}
|
|
1413
|
-
if (serviceBuildJson.envOverrides) {
|
|
1414
|
-
for (const [k, v] of Object.entries(serviceBuildJson.envOverrides)) {
|
|
1415
|
-
const interpolated = interpolateEnvTemplates(v, `Service build.json: ${serviceName}`);
|
|
1416
|
-
environment[k] = interpolated;
|
|
1417
|
-
buildArgs[k] = interpolated;
|
|
1418
|
-
}
|
|
1419
|
-
}
|
|
1420
|
-
if (serviceConfig.envOverrides) {
|
|
1421
|
-
for (const [k, v] of Object.entries(serviceConfig.envOverrides)) {
|
|
1422
|
-
const interpolated = interpolateEnvTemplates(v, `Service: ${serviceName}`);
|
|
1423
|
-
environment[k] = interpolated;
|
|
1424
|
-
buildArgs[k] = interpolated;
|
|
1425
|
-
}
|
|
1426
|
-
}
|
|
1427
|
-
const serviceDef = {
|
|
1428
|
-
build: {
|
|
1429
|
-
context: relServiceDir,
|
|
1430
|
-
dockerfile,
|
|
1431
|
-
target: mode,
|
|
1432
|
-
...Object.keys(buildArgs).length > 0 ? { args: buildArgs } : {}
|
|
1433
|
-
},
|
|
1434
|
-
init: true,
|
|
1435
|
-
logging: {
|
|
1436
|
-
driver: "json-file",
|
|
1437
|
-
options: {
|
|
1438
|
-
"max-size": "10m",
|
|
1439
|
-
"max-file": "3"
|
|
1440
|
-
}
|
|
1441
|
-
},
|
|
1442
|
-
environment,
|
|
1443
|
-
depends_on: {}
|
|
1444
|
-
};
|
|
1445
|
-
const envFilePath = path13.resolve(serviceDir, `.env.${mode}`);
|
|
1446
|
-
if (existsSync(envFilePath)) {
|
|
1447
|
-
serviceDef.env_file = [toComposePath(meshDir, envFilePath)];
|
|
1448
|
-
}
|
|
1449
|
-
if (mode === "dev") {
|
|
1450
|
-
const volSet = /* @__PURE__ */ new Set();
|
|
1451
|
-
volSet.add(`${relServiceDir}:/app`);
|
|
1452
|
-
volSet.add("/app/node_modules");
|
|
1453
|
-
for (const v of overrideVolumes) {
|
|
1454
|
-
if (typeof v === "string") {
|
|
1455
|
-
volSet.add(v);
|
|
1456
|
-
}
|
|
1457
|
-
}
|
|
1458
|
-
serviceDef.volumes = Array.from(volSet);
|
|
1459
|
-
}
|
|
1460
|
-
const urls = serviceUrls.get(serviceName);
|
|
1461
|
-
if (urls.publicUrl) {
|
|
1462
|
-
const pubPort = urls.publicUrl.split(":").pop();
|
|
1463
|
-
serviceDef.ports = [`${pubPort}:${INTERNAL_PORT}`];
|
|
1464
|
-
} else {
|
|
1465
|
-
delete serviceDef.ports;
|
|
1466
|
-
}
|
|
1467
|
-
if (overrideCommand) {
|
|
1468
|
-
serviceDef.command = overrideCommand;
|
|
1469
|
-
}
|
|
1470
|
-
if (serviceConfig.healthcheck) {
|
|
1471
|
-
if (serviceConfig.healthcheck.type === "tcp") {
|
|
1472
|
-
const hcPort = serviceConfig.healthcheck.port || INTERNAL_PORT;
|
|
1473
|
-
serviceDef.healthcheck = {
|
|
1474
|
-
test: [
|
|
1475
|
-
"CMD-SHELL",
|
|
1476
|
-
`nc -z 127.0.0.1 ${hcPort} || node -e "require('net').connect(${hcPort},'127.0.0.1').on('connect',()=>process.exit(0)).on('error',()=>process.exit(1))" || exit 1`
|
|
1477
|
-
],
|
|
1478
|
-
interval: "2s",
|
|
1479
|
-
timeout: "2s",
|
|
1480
|
-
start_period: "3s",
|
|
1481
|
-
retries: 10
|
|
1482
|
-
};
|
|
1483
|
-
} else {
|
|
1484
|
-
serviceDef.healthcheck = serviceConfig.healthcheck;
|
|
1485
|
-
}
|
|
1486
|
-
} else if (overrideHealthcheck) {
|
|
1487
|
-
serviceDef.healthcheck = overrideHealthcheck;
|
|
1488
|
-
} else {
|
|
1489
|
-
serviceDef.healthcheck = {
|
|
1490
|
-
test: [
|
|
1491
|
-
"CMD-SHELL",
|
|
1492
|
-
`nc -z 127.0.0.1 ${INTERNAL_PORT} || node -e "require('net').connect(${INTERNAL_PORT},'127.0.0.1').on('connect',()=>process.exit(0)).on('error',()=>process.exit(1))" || exit 1`
|
|
1493
|
-
],
|
|
1494
|
-
interval: "2s",
|
|
1495
|
-
timeout: "2s",
|
|
1496
|
-
start_period: "3s",
|
|
1497
|
-
retries: 10
|
|
1498
|
-
};
|
|
1499
|
-
}
|
|
1500
|
-
const namespacedAppKey = `${serviceName}-app`;
|
|
1501
|
-
serviceDef.networks = {
|
|
1502
|
-
mesh: {
|
|
1503
|
-
aliases: [serviceName, namespacedAppKey]
|
|
1504
|
-
},
|
|
1505
|
-
[`${serviceName}_net`]: {
|
|
1506
|
-
aliases: ["app", serviceName, namespacedAppKey]
|
|
1507
|
-
}
|
|
1508
|
-
};
|
|
1509
|
-
const provideMap = {
|
|
1510
|
-
...serviceConfig.replaceMocks || {},
|
|
1511
|
-
...serviceConfig.provideDependency || {}
|
|
1512
|
-
};
|
|
1513
|
-
const declaredDepNames = new Set(serviceDeps.map((d) => d.name));
|
|
1514
|
-
for (const [depKey, targetProvider] of Object.entries(provideMap)) {
|
|
1515
|
-
if (!declaredDepNames.has(depKey)) {
|
|
1516
|
-
throw new ScriptError(
|
|
1517
|
-
`Service "${serviceName}" declares provideDependency/replaceMocks for "${depKey}", but "${depKey}" is not declared in its build.json dependencies.`
|
|
1518
|
-
);
|
|
1519
|
-
}
|
|
1520
|
-
if (!mesh.services[targetProvider]) {
|
|
1521
|
-
throw new ScriptError(
|
|
1522
|
-
`Service "${serviceName}" maps dependency "${depKey}" to nonexistent service "${targetProvider}".`
|
|
1523
|
-
);
|
|
1524
|
-
}
|
|
1525
|
-
if (globalDepAliasToProvider.has(depKey) && globalDepAliasToProvider.get(depKey) !== targetProvider) {
|
|
1526
|
-
throw new ScriptError(
|
|
1527
|
-
`Dependency alias collision: Dependency key "${depKey}" is mapped to multiple different provider services ("${globalDepAliasToProvider.get(
|
|
1528
|
-
depKey
|
|
1529
|
-
)}" and "${targetProvider}").`
|
|
1530
|
-
);
|
|
1531
|
-
}
|
|
1532
|
-
if (mesh.services[depKey] && depKey !== targetProvider) {
|
|
1533
|
-
throw new ScriptError(
|
|
1534
|
-
`Dependency alias conflict: Dependency key "${depKey}" collides with declared mesh service "${depKey}".`
|
|
1535
|
-
);
|
|
1536
|
-
}
|
|
1537
|
-
globalDepAliasToProvider.set(depKey, targetProvider);
|
|
1538
|
-
}
|
|
1539
|
-
for (const dep of serviceDeps) {
|
|
1540
|
-
const depKey = dep.name;
|
|
1541
|
-
if (provideMap[depKey]) {
|
|
1542
|
-
const fellowService = provideMap[depKey];
|
|
1543
|
-
const fellowAppKey = `${fellowService}-app`;
|
|
1544
|
-
serviceDef.depends_on[fellowAppKey] = {
|
|
1545
|
-
condition: "service_healthy"
|
|
1546
|
-
};
|
|
1547
|
-
providerAliases.get(fellowService)?.add(depKey);
|
|
1548
|
-
} else if (mesh.dependencies && mesh.dependencies[depKey]) {
|
|
1549
|
-
serviceDef.depends_on[depKey] = {
|
|
1550
|
-
condition: "service_healthy"
|
|
1551
|
-
};
|
|
1552
|
-
} else {
|
|
1553
|
-
const namespacedDepKey = `${serviceName}-${depKey}`;
|
|
1554
|
-
serviceDef.depends_on[namespacedDepKey] = {
|
|
1555
|
-
condition: "service_healthy"
|
|
1556
|
-
};
|
|
1557
|
-
const depComposePath = dep.path;
|
|
1558
|
-
if (!existsSync(depComposePath)) {
|
|
1559
|
-
throw new ScriptError(
|
|
1560
|
-
`Mock compose file for dependency "${depKey}" not found: ${depComposePath}`
|
|
1561
|
-
);
|
|
1562
|
-
}
|
|
1563
|
-
const raw = readFileSync(depComposePath, "utf-8");
|
|
1564
|
-
const parsed = parse(raw);
|
|
1565
|
-
if (!parsed?.services || typeof parsed.services !== "object") {
|
|
1566
|
-
throw new ScriptError(
|
|
1567
|
-
`Invalid compose file for dependency "${depKey}": missing "services"`
|
|
1568
|
-
);
|
|
1569
|
-
}
|
|
1570
|
-
mergeAndNamespaceMockResources(parsed, `${serviceName}_${depKey}`, serviceDir, meshDir);
|
|
1571
|
-
if (dep.serviceName && !parsed.services[dep.serviceName]) {
|
|
1572
|
-
throw new ScriptError(
|
|
1573
|
-
`Service "${dep.serviceName}" declared in build.json not found in mock compose ${depComposePath}`
|
|
1574
|
-
);
|
|
1575
|
-
}
|
|
1576
|
-
const targetMockService = dep.serviceName ? parsed.services[dep.serviceName] : Object.values(parsed.services)[0];
|
|
1577
|
-
if (!targetMockService) {
|
|
1578
|
-
throw new ScriptError(
|
|
1579
|
-
`No services found in mock compose ${depComposePath}`
|
|
1580
|
-
);
|
|
1581
|
-
}
|
|
1582
|
-
const sidecarMapping = /* @__PURE__ */ new Map();
|
|
1583
|
-
for (const mName of Object.keys(parsed.services)) {
|
|
1584
|
-
if (parsed.services[mName] === targetMockService) {
|
|
1585
|
-
sidecarMapping.set(mName, namespacedDepKey);
|
|
1586
|
-
} else {
|
|
1587
|
-
sidecarMapping.set(mName, `${serviceName}-${mName}`);
|
|
1588
|
-
}
|
|
1589
|
-
}
|
|
1590
|
-
const resolvedMock = resolveServicePaths(
|
|
1591
|
-
targetMockService,
|
|
1592
|
-
serviceDir,
|
|
1593
|
-
meshDir
|
|
1594
|
-
);
|
|
1595
|
-
delete resolvedMock.ports;
|
|
1596
|
-
delete resolvedMock.container_name;
|
|
1597
|
-
normalizeDependsOn(resolvedMock);
|
|
1598
|
-
applyInternalMockDependsOnMapping(resolvedMock, sidecarMapping);
|
|
1599
|
-
const portMappings = getDependencyPortMappings(dep, `Local dependency "${depKey}" of service "${serviceName}"`);
|
|
1600
|
-
if (portMappings.length > 0) {
|
|
1601
|
-
resolvedMock.ports = portMappings.map((mapping) => mapping.raw);
|
|
1602
|
-
}
|
|
1603
|
-
resolvedMock.networks = {
|
|
1604
|
-
[`${serviceName}_net`]: {
|
|
1605
|
-
aliases: [depKey, namespacedDepKey]
|
|
1606
|
-
}
|
|
1607
|
-
};
|
|
1608
|
-
registerService(namespacedDepKey, resolvedMock, `mock dependency for "${serviceName}"`);
|
|
1609
|
-
for (const [mName, mDef] of Object.entries(parsed.services)) {
|
|
1610
|
-
if (mDef !== targetMockService) {
|
|
1611
|
-
const sidecarKey = sidecarMapping.get(mName);
|
|
1612
|
-
if (!composeConfig.services[sidecarKey]) {
|
|
1613
|
-
const resolvedSidecar = resolveServicePaths(mDef, serviceDir, meshDir);
|
|
1614
|
-
delete resolvedSidecar.ports;
|
|
1615
|
-
delete resolvedSidecar.container_name;
|
|
1616
|
-
normalizeDependsOn(resolvedSidecar);
|
|
1617
|
-
applyInternalMockDependsOnMapping(resolvedSidecar, sidecarMapping);
|
|
1618
|
-
resolvedSidecar.networks = {
|
|
1619
|
-
[`${serviceName}_net`]: {
|
|
1620
|
-
aliases: [mName, sidecarKey]
|
|
1621
|
-
}
|
|
1622
|
-
};
|
|
1623
|
-
registerService(sidecarKey, resolvedSidecar, `sidecar of mock "${depKey}"`);
|
|
1624
|
-
}
|
|
1625
|
-
}
|
|
1626
|
-
}
|
|
1627
|
-
}
|
|
1628
|
-
}
|
|
1629
|
-
if (Object.keys(serviceDef.depends_on).length === 0) {
|
|
1630
|
-
delete serviceDef.depends_on;
|
|
1631
|
-
}
|
|
1632
|
-
registerService(namespacedAppKey, serviceDef, `mesh service "${serviceName}"`);
|
|
1633
|
-
}
|
|
1634
|
-
for (const [providerName, aliases] of providerAliases.entries()) {
|
|
1635
|
-
const appKey = `${providerName}-app`;
|
|
1636
|
-
const serviceDef = composeConfig.services[appKey];
|
|
1637
|
-
if (serviceDef && serviceDef.networks?.mesh) {
|
|
1638
|
-
const existingAliases = new Set(serviceDef.networks.mesh.aliases || []);
|
|
1639
|
-
for (const alias of aliases) {
|
|
1640
|
-
existingAliases.add(alias);
|
|
1641
|
-
}
|
|
1642
|
-
serviceDef.networks.mesh.aliases = Array.from(existingAliases);
|
|
1643
|
-
}
|
|
1644
|
-
}
|
|
1645
|
-
let testerServiceName;
|
|
1646
|
-
if (options.includeTester && mesh.tester) {
|
|
1647
|
-
const testerDir = path13.resolve(meshDir, mesh.tester.path);
|
|
1648
|
-
const composeRel = mesh.tester.compose || "docker-compose.yml";
|
|
1649
|
-
const testerComposePath = path13.resolve(testerDir, composeRel);
|
|
1650
|
-
if (existsSync(testerComposePath)) {
|
|
1651
|
-
const raw = readFileSync(testerComposePath, "utf-8");
|
|
1652
|
-
const parsed = parse(raw);
|
|
1653
|
-
mergeTopLevelResources(parsed);
|
|
1654
|
-
if (parsed?.services && typeof parsed.services === "object") {
|
|
1655
|
-
const firstKey = Object.keys(parsed.services)[0];
|
|
1656
|
-
if (firstKey && parsed.services[firstKey]) {
|
|
1657
|
-
testerServiceName = firstKey;
|
|
1658
|
-
for (const [tKey, tDef] of Object.entries(parsed.services)) {
|
|
1659
|
-
const resolvedTester = resolveServicePaths(
|
|
1660
|
-
tDef,
|
|
1661
|
-
testerDir,
|
|
1662
|
-
meshDir
|
|
1663
|
-
);
|
|
1664
|
-
delete resolvedTester.container_name;
|
|
1665
|
-
normalizeDependsOn(resolvedTester);
|
|
1666
|
-
resolvedTester.network_mode = "host";
|
|
1667
|
-
delete resolvedTester.networks;
|
|
1668
|
-
if (tKey === firstKey) {
|
|
1669
|
-
resolvedTester.depends_on = resolvedTester.depends_on || {};
|
|
1670
|
-
for (const sName of Object.keys(mesh.services)) {
|
|
1671
|
-
resolvedTester.depends_on[`${sName}-app`] = {
|
|
1672
|
-
condition: "service_healthy"
|
|
1673
|
-
};
|
|
1674
|
-
}
|
|
1675
|
-
if (mesh.tester.envOverrides) {
|
|
1676
|
-
if (Array.isArray(resolvedTester.environment)) {
|
|
1677
|
-
const envObj = {};
|
|
1678
|
-
for (const item of resolvedTester.environment) {
|
|
1679
|
-
if (typeof item === "string") {
|
|
1680
|
-
const eqIdx = item.indexOf("=");
|
|
1681
|
-
if (eqIdx !== -1) {
|
|
1682
|
-
envObj[item.slice(0, eqIdx)] = item.slice(eqIdx + 1);
|
|
1683
|
-
} else {
|
|
1684
|
-
envObj[item] = process.env[item] ?? null;
|
|
1685
|
-
}
|
|
1686
|
-
}
|
|
1687
|
-
}
|
|
1688
|
-
resolvedTester.environment = envObj;
|
|
1689
|
-
} else if (!resolvedTester.environment || typeof resolvedTester.environment !== "object") {
|
|
1690
|
-
resolvedTester.environment = {};
|
|
1691
|
-
}
|
|
1692
|
-
for (const [k, v] of Object.entries(mesh.tester.envOverrides)) {
|
|
1693
|
-
resolvedTester.environment[k] = interpolateEnvTemplates(v, `Tester: ${tKey}`);
|
|
1694
|
-
}
|
|
1695
|
-
}
|
|
1696
|
-
}
|
|
1697
|
-
registerService(tKey, resolvedTester, `tester service "${tKey}"`);
|
|
1698
|
-
}
|
|
1699
|
-
}
|
|
1700
|
-
}
|
|
1701
|
-
}
|
|
1702
|
-
}
|
|
1703
|
-
for (const svc of Object.values(composeConfig.services)) {
|
|
1704
|
-
if (svc.depends_on && typeof svc.depends_on === "object") {
|
|
1705
|
-
for (const [depTarget, depOpts] of Object.entries(svc.depends_on)) {
|
|
1706
|
-
const targetSvc = composeConfig.services[depTarget];
|
|
1707
|
-
if (targetSvc && (!targetSvc.healthcheck || targetSvc.healthcheck.disable) && depOpts && depOpts.condition === "service_healthy") {
|
|
1708
|
-
depOpts.condition = "service_started";
|
|
1709
|
-
}
|
|
1710
|
-
}
|
|
1711
|
-
}
|
|
1712
|
-
}
|
|
1713
|
-
const generatedYaml = stringify(composeConfig);
|
|
1714
|
-
assertUniqueHostPortMappings(generatedYaml);
|
|
1715
|
-
if (options.validateWithDocker === false) {
|
|
1716
|
-
return { yaml: generatedYaml, testerServiceName };
|
|
1717
|
-
}
|
|
1718
|
-
const result = spawnSync(
|
|
1719
|
-
"docker",
|
|
1720
|
-
[
|
|
1721
|
-
"compose",
|
|
1722
|
-
"-p",
|
|
1723
|
-
projectName,
|
|
1724
|
-
"--project-directory",
|
|
1725
|
-
meshDir,
|
|
1726
|
-
"-f",
|
|
1727
|
-
"-",
|
|
1728
|
-
"config"
|
|
1729
|
-
],
|
|
1730
|
-
{
|
|
1731
|
-
cwd: meshDir,
|
|
1732
|
-
input: generatedYaml,
|
|
1733
|
-
encoding: "utf-8"
|
|
1734
|
-
}
|
|
1735
|
-
);
|
|
1736
|
-
if (result.error) {
|
|
1737
|
-
throw new ScriptError(
|
|
1738
|
-
`Failed to run docker compose config: ${result.error.message}`,
|
|
1739
|
-
{ cause: result.error }
|
|
1740
|
-
);
|
|
1741
|
-
}
|
|
1742
|
-
if (result.status !== 0) {
|
|
1743
|
-
throw new ScriptError(
|
|
1744
|
-
`\u274C Failed to validate mesh compose configuration:
|
|
1745
|
-
${result.stderr || result.stdout}`
|
|
1746
|
-
);
|
|
1747
|
-
}
|
|
1748
|
-
return {
|
|
1749
|
-
yaml: result.stdout || generatedYaml,
|
|
1750
|
-
testerServiceName
|
|
1751
|
-
};
|
|
1752
|
-
}
|
|
1753
|
-
function resolveVolumeEntry(vol, baseDir, meshDir) {
|
|
1754
|
-
if (typeof vol === "string") {
|
|
1755
|
-
if (!vol.includes(":")) {
|
|
1756
|
-
return vol;
|
|
1757
|
-
}
|
|
1758
|
-
const parts = vol.split(":");
|
|
1759
|
-
const host = parts[0];
|
|
1760
|
-
if (isBindMount(host)) {
|
|
1761
|
-
const absHost = path13.resolve(baseDir, host);
|
|
1762
|
-
const formattedRel = toComposePath(meshDir, absHost);
|
|
1763
|
-
return `${formattedRel}:${parts.slice(1).join(":")}`;
|
|
1764
|
-
}
|
|
1765
|
-
return vol;
|
|
1766
|
-
}
|
|
1767
|
-
if (vol && typeof vol === "object") {
|
|
1768
|
-
const cloned = { ...vol };
|
|
1769
|
-
if (cloned.type === "bind" && cloned.source && typeof cloned.source === "string") {
|
|
1770
|
-
const absSource = path13.resolve(baseDir, cloned.source);
|
|
1771
|
-
cloned.source = toComposePath(meshDir, absSource);
|
|
1772
|
-
}
|
|
1773
|
-
return cloned;
|
|
1774
|
-
}
|
|
1775
|
-
return vol;
|
|
1776
|
-
}
|
|
1777
|
-
function resolveServicePaths(service, baseDir, meshDir) {
|
|
1778
|
-
const cloned = JSON.parse(JSON.stringify(service));
|
|
1779
|
-
if (cloned.build) {
|
|
1780
|
-
if (typeof cloned.build === "string") {
|
|
1781
|
-
cloned.build = toComposePath(meshDir, path13.resolve(baseDir, cloned.build));
|
|
1782
|
-
} else if (cloned.build.context) {
|
|
1783
|
-
cloned.build.context = toComposePath(
|
|
1784
|
-
meshDir,
|
|
1785
|
-
path13.resolve(baseDir, cloned.build.context)
|
|
1786
|
-
);
|
|
1787
|
-
}
|
|
1788
|
-
}
|
|
1789
|
-
if (Array.isArray(cloned.volumes)) {
|
|
1790
|
-
cloned.volumes = cloned.volumes.map(
|
|
1791
|
-
(vol) => resolveVolumeEntry(vol, baseDir, meshDir)
|
|
1792
|
-
);
|
|
1793
|
-
}
|
|
1794
|
-
if (Array.isArray(cloned.env_file)) {
|
|
1795
|
-
cloned.env_file = cloned.env_file.map((ef) => {
|
|
1796
|
-
if (typeof ef === "string") {
|
|
1797
|
-
return toComposePath(meshDir, path13.resolve(baseDir, ef));
|
|
1798
|
-
}
|
|
1799
|
-
if (ef && typeof ef === "object" && ef.path) {
|
|
1800
|
-
return {
|
|
1801
|
-
...ef,
|
|
1802
|
-
path: toComposePath(meshDir, path13.resolve(baseDir, ef.path))
|
|
1803
|
-
};
|
|
1804
|
-
}
|
|
1805
|
-
return ef;
|
|
1806
|
-
});
|
|
1807
|
-
} else if (typeof cloned.env_file === "string") {
|
|
1808
|
-
cloned.env_file = toComposePath(meshDir, path13.resolve(baseDir, cloned.env_file));
|
|
1809
|
-
}
|
|
1810
|
-
normalizeDependsOn(cloned);
|
|
1811
|
-
return cloned;
|
|
1812
|
-
}
|
|
1813
|
-
var activeComposeSet = /* @__PURE__ */ new Set();
|
|
1814
|
-
var signalHandlersRegistered = false;
|
|
1815
|
-
var activeChildProcess = null;
|
|
1816
|
-
var isTearingDown = false;
|
|
1817
|
-
var isShuttingDown = false;
|
|
1818
|
-
var isProcessAlive = (c) => {
|
|
1819
|
-
return Boolean(c && c.exitCode === null && c.signalCode === null);
|
|
1820
|
-
};
|
|
1821
|
-
function setActiveChild(child) {
|
|
1822
|
-
activeChildProcess = child;
|
|
1823
|
-
if (!child) {
|
|
1824
|
-
isShuttingDown = false;
|
|
1825
|
-
}
|
|
1826
|
-
}
|
|
1827
|
-
function setTearingDown(tearingDown) {
|
|
1828
|
-
isTearingDown = tearingDown;
|
|
1829
|
-
}
|
|
1830
|
-
function registerActiveCompose(yamlConfig, projectDir, options = {}) {
|
|
1831
|
-
const entry = {
|
|
1832
|
-
yamlConfig,
|
|
1833
|
-
projectDir,
|
|
1834
|
-
removeVolumes: options.removeVolumes
|
|
1835
|
-
};
|
|
1836
|
-
activeComposeSet.add(entry);
|
|
1837
|
-
ensureSignalHandlers();
|
|
1838
|
-
return () => {
|
|
1839
|
-
activeComposeSet.delete(entry);
|
|
1840
|
-
};
|
|
1841
|
-
}
|
|
1842
|
-
function ensureSignalHandlers() {
|
|
1843
|
-
if (signalHandlersRegistered) return;
|
|
1844
|
-
signalHandlersRegistered = true;
|
|
1845
|
-
const handleSignal = (signal) => {
|
|
1846
|
-
if (isTearingDown) {
|
|
1847
|
-
return;
|
|
1848
|
-
}
|
|
1849
|
-
if (activeChildProcess && isProcessAlive(activeChildProcess)) {
|
|
1850
|
-
const child = activeChildProcess;
|
|
1851
|
-
if (signal === "SIGINT") {
|
|
1852
|
-
if (!isShuttingDown) {
|
|
1853
|
-
isShuttingDown = true;
|
|
1854
|
-
setTimeout(() => {
|
|
1855
|
-
if (isProcessAlive(child)) {
|
|
1856
|
-
try {
|
|
1857
|
-
child.kill("SIGKILL");
|
|
1858
|
-
} catch {
|
|
1859
|
-
}
|
|
1860
|
-
}
|
|
1861
|
-
}, 1e4).unref();
|
|
1862
|
-
return;
|
|
1863
|
-
}
|
|
1864
|
-
try {
|
|
1865
|
-
child.kill("SIGINT");
|
|
1866
|
-
} catch {
|
|
1867
|
-
}
|
|
1868
|
-
return;
|
|
1869
|
-
}
|
|
1870
|
-
try {
|
|
1871
|
-
child.kill(signal);
|
|
1872
|
-
} catch {
|
|
1710
|
+
try {
|
|
1711
|
+
child.kill(signal);
|
|
1712
|
+
} catch {
|
|
1873
1713
|
}
|
|
1874
1714
|
setTimeout(() => {
|
|
1875
1715
|
if (isProcessAlive(child)) {
|
|
@@ -2021,12 +1861,12 @@ function redactYamlSecrets(yamlContent) {
|
|
|
2021
1861
|
return redacted;
|
|
2022
1862
|
}
|
|
2023
1863
|
function getRunStatePath(projectDir) {
|
|
2024
|
-
return
|
|
1864
|
+
return path4.resolve(resolveProjectDir(projectDir), ".builder", "run.state");
|
|
2025
1865
|
}
|
|
2026
1866
|
function writeRunState(projectDir, state) {
|
|
2027
1867
|
try {
|
|
2028
1868
|
const absDir = resolveProjectDir(projectDir);
|
|
2029
|
-
const builderDir =
|
|
1869
|
+
const builderDir = path4.resolve(absDir, ".builder");
|
|
2030
1870
|
if (!existsSync(builderDir)) {
|
|
2031
1871
|
mkdirSync(builderDir, { recursive: true });
|
|
2032
1872
|
}
|
|
@@ -2035,7 +1875,7 @@ function writeRunState(projectDir, state) {
|
|
|
2035
1875
|
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
2036
1876
|
};
|
|
2037
1877
|
writeFileSync(
|
|
2038
|
-
|
|
1878
|
+
path4.resolve(builderDir, "run.state"),
|
|
2039
1879
|
JSON.stringify(fullState, null, 2),
|
|
2040
1880
|
"utf-8"
|
|
2041
1881
|
);
|
|
@@ -2066,9 +1906,9 @@ function projectNamesForServiceStage(projectDir, stage) {
|
|
|
2066
1906
|
let rawName;
|
|
2067
1907
|
try {
|
|
2068
1908
|
const buildJson = getBuildJson(absDir);
|
|
2069
|
-
rawName = buildJson.name ||
|
|
1909
|
+
rawName = buildJson.name || path4.basename(absDir);
|
|
2070
1910
|
} catch {
|
|
2071
|
-
rawName =
|
|
1911
|
+
rawName = path4.basename(absDir);
|
|
2072
1912
|
}
|
|
2073
1913
|
const s = stage.toLowerCase();
|
|
2074
1914
|
if (s === "dev") {
|
|
@@ -2094,13 +1934,13 @@ function projectNamesForServiceStage(projectDir, stage) {
|
|
|
2094
1934
|
function projectNamesForMeshStage(meshDir, stage) {
|
|
2095
1935
|
const absDir = resolveProjectDir(meshDir);
|
|
2096
1936
|
let rawMeshName;
|
|
2097
|
-
let
|
|
1937
|
+
let serviceNames = [];
|
|
2098
1938
|
try {
|
|
2099
1939
|
const mesh = getMeshJson(absDir);
|
|
2100
|
-
rawMeshName = mesh.name ||
|
|
2101
|
-
|
|
1940
|
+
rawMeshName = mesh.name || path4.basename(absDir);
|
|
1941
|
+
serviceNames = Object.keys(resolveMeshStage(mesh, "test", path4.join(absDir, "mesh.json")).services);
|
|
2102
1942
|
} catch {
|
|
2103
|
-
rawMeshName =
|
|
1943
|
+
rawMeshName = path4.basename(absDir);
|
|
2104
1944
|
}
|
|
2105
1945
|
const s = stage.toLowerCase();
|
|
2106
1946
|
if (s === "dev") {
|
|
@@ -2113,19 +1953,10 @@ function projectNamesForMeshStage(meshDir, stage) {
|
|
|
2113
1953
|
return [deriveProjectName(rawMeshName, "e2e")];
|
|
2114
1954
|
}
|
|
2115
1955
|
if (s === "test-unit") {
|
|
2116
|
-
return
|
|
2117
|
-
const svcDir = path13.resolve(absDir, svc.path);
|
|
2118
|
-
return projectNamesForServiceStage(svcDir, "test-unit")[0];
|
|
2119
|
-
});
|
|
1956
|
+
return serviceNames.map((name) => `${deriveProjectName(rawMeshName, "dev")}-${name}-test`);
|
|
2120
1957
|
}
|
|
2121
1958
|
if (s === "test") {
|
|
2122
|
-
|
|
2123
|
-
for (const svc of Object.values(services)) {
|
|
2124
|
-
const svcDir = path13.resolve(absDir, svc.path);
|
|
2125
|
-
list.push(...projectNamesForServiceStage(svcDir, "test"));
|
|
2126
|
-
}
|
|
2127
|
-
list.push(deriveProjectName(rawMeshName, "e2e"));
|
|
2128
|
-
return Array.from(new Set(list));
|
|
1959
|
+
return [...serviceNames.map((name) => `${deriveProjectName(rawMeshName, "dev")}-${name}-test`), deriveProjectName(rawMeshName, "e2e")];
|
|
2129
1960
|
}
|
|
2130
1961
|
return [deriveProjectName(rawMeshName, s)];
|
|
2131
1962
|
}
|
|
@@ -2146,9 +1977,8 @@ async function handleMeshDown(rawStage = "dev", options = {}) {
|
|
|
2146
1977
|
);
|
|
2147
1978
|
if (options.debug) {
|
|
2148
1979
|
try {
|
|
2149
|
-
const mode = stage === "dev" ? "dev" : "prod";
|
|
2150
|
-
const
|
|
2151
|
-
const { yaml } = compileMeshEnvironment(mode, meshDir, { includeTester });
|
|
1980
|
+
const mode = stage === "dev" ? "dev" : stage === "test-e2e" ? "e2e" : "prod";
|
|
1981
|
+
const { yaml } = compileMeshEnvironment(mode, meshDir, { validateWithDocker: false });
|
|
2152
1982
|
console.log(
|
|
2153
1983
|
pc22.yellow("\nFinal merged Mesh YAML configuration:\n"),
|
|
2154
1984
|
redactYamlSecrets(yaml)
|
|
@@ -2252,13 +2082,7 @@ async function checkHostPortCollisions(ports) {
|
|
|
2252
2082
|
if (port > 0 && port < 65536) {
|
|
2253
2083
|
const inUse = await isPortInUse(port);
|
|
2254
2084
|
if (inUse) {
|
|
2255
|
-
|
|
2256
|
-
pc22.yellow(
|
|
2257
|
-
`
|
|
2258
|
-
\u26A0\uFE0F Host Port Conflict Warning: Port ${port} is already in use on the host (e.g. by another running stage or process). Docker Compose may fail to bind to this port.
|
|
2259
|
-
`
|
|
2260
|
-
)
|
|
2261
|
-
);
|
|
2085
|
+
throw new ScriptError(`Host port ${port} is already in use. Builder does not remap fixed public ports.`);
|
|
2262
2086
|
}
|
|
2263
2087
|
}
|
|
2264
2088
|
}
|
|
@@ -2321,12 +2145,7 @@ async function runMeshDev(options = {}) {
|
|
|
2321
2145
|
const meshDir = resolveProjectDir(options.projectDir);
|
|
2322
2146
|
console.log(pc22.cyan(`
|
|
2323
2147
|
\u{1F680} Starting Global DEV Mesh Environment...`));
|
|
2324
|
-
|
|
2325
|
-
checkMesh(meshDir, { requireTester: false });
|
|
2326
|
-
}
|
|
2327
|
-
const { yaml } = compileMeshEnvironment("dev", meshDir, {
|
|
2328
|
-
silenceWarnings: options.silenceWarnings
|
|
2329
|
-
});
|
|
2148
|
+
const { yaml } = compileMeshEnvironment("dev", meshDir);
|
|
2330
2149
|
const parsed = parse(yaml);
|
|
2331
2150
|
const projectName = parsed?.name || "mesh-dev";
|
|
2332
2151
|
if (options.debug) {
|
|
@@ -2364,1008 +2183,116 @@ async function runMeshDev(options = {}) {
|
|
|
2364
2183
|
return status;
|
|
2365
2184
|
}
|
|
2366
2185
|
async function runMeshProd(options = {}) {
|
|
2367
|
-
const meshDir = resolveProjectDir(options.projectDir);
|
|
2368
|
-
console.log(pc22.cyan(`
|
|
2369
|
-
\u{1F3ED} Starting Global PROD Mesh Environment...`));
|
|
2370
|
-
|
|
2371
|
-
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
silenceWarnings: options.silenceWarnings
|
|
2375
|
-
});
|
|
2376
|
-
const parsed = parse(yaml);
|
|
2377
|
-
const projectName = parsed?.name || "mesh-prod";
|
|
2378
|
-
if (options.debug) {
|
|
2379
|
-
console.log(
|
|
2380
|
-
pc22.yellow("\nFinal merged Mesh Prod YAML configuration:\n"),
|
|
2381
|
-
redactYamlSecrets(yaml)
|
|
2382
|
-
);
|
|
2383
|
-
}
|
|
2384
|
-
if (options.dryRun) {
|
|
2385
|
-
console.log(pc22.green("Dry run complete. Compose was not started."));
|
|
2386
|
-
return 0;
|
|
2387
|
-
}
|
|
2388
|
-
const hostPorts = extractHostPorts(yaml);
|
|
2389
|
-
await checkHostPortCollisions(hostPorts);
|
|
2390
|
-
writeRunState(meshDir, {
|
|
2391
|
-
projectName,
|
|
2392
|
-
stage: "prod",
|
|
2393
|
-
projectDir: meshDir
|
|
2394
|
-
});
|
|
2395
|
-
const upArgs = ["up", "--build"];
|
|
2396
|
-
if (options.detach) {
|
|
2397
|
-
upArgs.push("-d");
|
|
2398
|
-
}
|
|
2399
|
-
let status = 0;
|
|
2400
|
-
try {
|
|
2401
|
-
status = await runCompose(upArgs, yaml, meshDir, {
|
|
2402
|
-
removeVolumes: false
|
|
2403
|
-
});
|
|
2404
|
-
} finally {
|
|
2405
|
-
if (!options.detach) {
|
|
2406
|
-
await teardownCompose(yaml, meshDir, { removeVolumes: false });
|
|
2407
|
-
clearRunState(meshDir);
|
|
2408
|
-
}
|
|
2409
|
-
}
|
|
2410
|
-
return status;
|
|
2411
|
-
}
|
|
2412
|
-
|
|
2413
|
-
// src/utils/ymlMods/addDependenciesToAppService.ts
|
|
2414
|
-
var addDependenciesToAppService = (yml, dependencies) => {
|
|
2415
|
-
if (!yml || !yml.services || !yml.services.app) {
|
|
2416
|
-
throw new ScriptError("Invalid YAML structure. Missing 'services.app' field.");
|
|
2417
|
-
}
|
|
2418
|
-
if (!dependencies || dependencies.length === 0) {
|
|
2419
|
-
return;
|
|
2420
|
-
}
|
|
2421
|
-
normalizeDependsOn(yml.services.app);
|
|
2422
|
-
yml.services.app.depends_on = yml.services.app.depends_on || {};
|
|
2423
|
-
dependencies.forEach((dep) => {
|
|
2424
|
-
const targetSvc = yml.services[dep.name];
|
|
2425
|
-
const hasHealthcheck = Boolean(targetSvc?.healthcheck);
|
|
2426
|
-
yml.services.app.depends_on[dep.name] = {
|
|
2427
|
-
condition: hasHealthcheck ? "service_healthy" : "service_started"
|
|
2428
|
-
};
|
|
2429
|
-
});
|
|
2430
|
-
};
|
|
2431
|
-
|
|
2432
|
-
// src/utils/ymlMods/attachName.ts
|
|
2433
|
-
var attachName = (yml, nameOrBuildJson) => {
|
|
2434
|
-
if (!yml) {
|
|
2435
|
-
throw new ScriptError("Invalid YAML structure. Missing 'yml' field.");
|
|
2436
|
-
}
|
|
2437
|
-
const name = typeof nameOrBuildJson === "string" ? nameOrBuildJson : nameOrBuildJson?.name;
|
|
2438
|
-
if (name) {
|
|
2439
|
-
yml.name = name;
|
|
2440
|
-
}
|
|
2441
|
-
};
|
|
2442
|
-
|
|
2443
|
-
// src/utils/ymlMods/makeE2eDependOnApp.ts
|
|
2444
|
-
var makeE2eDependOnApp = (yml) => {
|
|
2445
|
-
if (!yml || !yml.services) {
|
|
2446
|
-
throw new ScriptError("Invalid YAML structure. Missing 'services' field.");
|
|
2447
|
-
}
|
|
2448
|
-
if (!yml.services.tester) {
|
|
2449
|
-
throw new ScriptError("Tester service not found");
|
|
2450
|
-
}
|
|
2451
|
-
if (!yml.services.app) {
|
|
2452
|
-
throw new ScriptError("App service not found");
|
|
2453
|
-
}
|
|
2454
|
-
normalizeDependsOn(yml.services.tester);
|
|
2455
|
-
const appHasHealthcheck = Boolean(yml.services.app?.healthcheck);
|
|
2456
|
-
yml.services.tester.depends_on = {
|
|
2457
|
-
...yml.services.tester.depends_on || {},
|
|
2458
|
-
app: {
|
|
2459
|
-
condition: appHasHealthcheck ? "service_healthy" : "service_started"
|
|
2460
|
-
}
|
|
2461
|
-
};
|
|
2462
|
-
};
|
|
2463
|
-
|
|
2464
|
-
// src/utils/ymlMods/renameServicesWithDependencies.ts
|
|
2465
|
-
var renameServicesWithDependencies = (yml, dependencies) => {
|
|
2466
|
-
if (!yml || !yml.services || typeof yml.services !== "object") {
|
|
2467
|
-
throw new ScriptError("Invalid YAML structure. Missing 'services' field.");
|
|
2468
|
-
}
|
|
2469
|
-
if (!dependencies || dependencies.length === 0) {
|
|
2470
|
-
return;
|
|
2471
|
-
}
|
|
2472
|
-
const renameMap = /* @__PURE__ */ new Map();
|
|
2473
|
-
for (const dep of dependencies) {
|
|
2474
|
-
if (dep.serviceName && dep.name && dep.serviceName !== dep.name) {
|
|
2475
|
-
renameMap.set(dep.serviceName, dep.name);
|
|
2476
|
-
}
|
|
2477
|
-
}
|
|
2478
|
-
if (renameMap.size === 0) {
|
|
2479
|
-
return;
|
|
2480
|
-
}
|
|
2481
|
-
const currentKeys = new Set(Object.keys(yml.services));
|
|
2482
|
-
for (const [oldName, newName] of renameMap.entries()) {
|
|
2483
|
-
if (currentKeys.has(newName) && !renameMap.has(newName)) {
|
|
2484
|
-
throw new ScriptError(
|
|
2485
|
-
`Service collision: cannot rename "${oldName}" to "${newName}" because a service named "${newName}" already exists in the stack.`
|
|
2486
|
-
);
|
|
2487
|
-
}
|
|
2488
|
-
}
|
|
2489
|
-
const newServices = {};
|
|
2490
|
-
for (const [name, service] of Object.entries(yml.services)) {
|
|
2491
|
-
const targetName = renameMap.get(name) || name;
|
|
2492
|
-
newServices[targetName] = service;
|
|
2493
|
-
}
|
|
2494
|
-
yml.services = newServices;
|
|
2495
|
-
for (const service of Object.values(yml.services)) {
|
|
2496
|
-
if (!service || typeof service !== "object") continue;
|
|
2497
|
-
if (service.depends_on) {
|
|
2498
|
-
if (Array.isArray(service.depends_on)) {
|
|
2499
|
-
service.depends_on = service.depends_on.map(
|
|
2500
|
-
(dep) => renameMap.get(dep) || dep
|
|
2501
|
-
);
|
|
2502
|
-
} else if (typeof service.depends_on === "object") {
|
|
2503
|
-
const updatedDependsOn = {};
|
|
2504
|
-
for (const [depName, depConfig] of Object.entries(service.depends_on)) {
|
|
2505
|
-
const targetDepName = renameMap.get(depName) || depName;
|
|
2506
|
-
updatedDependsOn[targetDepName] = depConfig;
|
|
2507
|
-
}
|
|
2508
|
-
service.depends_on = updatedDependsOn;
|
|
2509
|
-
}
|
|
2510
|
-
}
|
|
2511
|
-
if (Array.isArray(service.links)) {
|
|
2512
|
-
service.links = service.links.map((link) => {
|
|
2513
|
-
const [targetSvc, alias] = link.split(":");
|
|
2514
|
-
if (targetSvc && renameMap.has(targetSvc)) {
|
|
2515
|
-
const newTarget = renameMap.get(targetSvc);
|
|
2516
|
-
return alias ? `${newTarget}:${alias}` : newTarget;
|
|
2517
|
-
}
|
|
2518
|
-
return link;
|
|
2519
|
-
});
|
|
2520
|
-
}
|
|
2521
|
-
if (typeof service.network_mode === "string" && service.network_mode.startsWith("service:")) {
|
|
2522
|
-
const targetSvc = service.network_mode.slice("service:".length);
|
|
2523
|
-
if (renameMap.has(targetSvc)) {
|
|
2524
|
-
service.network_mode = `service:${renameMap.get(targetSvc)}`;
|
|
2525
|
-
}
|
|
2526
|
-
}
|
|
2527
|
-
if (Array.isArray(service.volumes_from)) {
|
|
2528
|
-
service.volumes_from = service.volumes_from.map((vf) => {
|
|
2529
|
-
const [vfSvc, mode] = vf.split(":");
|
|
2530
|
-
if (vfSvc && renameMap.has(vfSvc)) {
|
|
2531
|
-
const newTarget = renameMap.get(vfSvc);
|
|
2532
|
-
return mode ? `${newTarget}:${mode}` : newTarget;
|
|
2533
|
-
}
|
|
2534
|
-
return vf;
|
|
2535
|
-
});
|
|
2536
|
-
}
|
|
2537
|
-
if (service.extends && typeof service.extends === "object") {
|
|
2538
|
-
if (service.extends.service && renameMap.has(service.extends.service)) {
|
|
2539
|
-
service.extends.service = renameMap.get(service.extends.service);
|
|
2540
|
-
}
|
|
2541
|
-
}
|
|
2542
|
-
}
|
|
2543
|
-
};
|
|
2544
|
-
function findServiceDefinersInDeclaredFiles(buildJson, projectDir, serviceName) {
|
|
2545
|
-
const declaredFiles = getDeclaredYamlFiles(buildJson, projectDir);
|
|
2546
|
-
const hits = [];
|
|
2547
|
-
for (const file of declaredFiles) {
|
|
2548
|
-
if (!existsSync(file.absolutePath)) continue;
|
|
2549
|
-
try {
|
|
2550
|
-
const content = readFileSync(file.absolutePath, "utf-8");
|
|
2551
|
-
const parsed = parse(content);
|
|
2552
|
-
if (parsed && typeof parsed === "object" && parsed.services && typeof parsed.services === "object") {
|
|
2553
|
-
const svc = parsed.services[serviceName];
|
|
2554
|
-
if (svc) {
|
|
2555
|
-
const hasImageOrBuild = Boolean(svc.image || svc.build);
|
|
2556
|
-
hits.push(
|
|
2557
|
-
` - ${file.relativePath} (${file.source})${hasImageOrBuild ? " [defines image/build]" : " [no image/build]"}`
|
|
2558
|
-
);
|
|
2559
|
-
}
|
|
2560
|
-
}
|
|
2561
|
-
} catch {
|
|
2562
|
-
}
|
|
2563
|
-
}
|
|
2564
|
-
return hits;
|
|
2565
|
-
}
|
|
2566
|
-
function explainComposeMergeFailure(buildJson, projectDir, envName, filesUsed, rawOutput) {
|
|
2567
|
-
const lines = [];
|
|
2568
|
-
const serviceMatch = rawOutput.match(
|
|
2569
|
-
/service "([^"]+)" has neither an image nor a build context specified/
|
|
2570
|
-
);
|
|
2571
|
-
const envMissingMatch = /env file .* not found|no such file or directory.*\.env/i.test(rawOutput);
|
|
2572
|
-
const actualComposeFiles = filesUsed.filter(
|
|
2573
|
-
(f) => !f.startsWith("-") && (f.endsWith(".yml") || f.endsWith(".yaml"))
|
|
2574
|
-
);
|
|
2575
|
-
lines.push(`Environment : ${envName}`);
|
|
2576
|
-
lines.push(`Compose files merged :`);
|
|
2577
|
-
if (actualComposeFiles.length > 0) {
|
|
2578
|
-
actualComposeFiles.forEach((f) => lines.push(` - ${f}`));
|
|
2579
|
-
} else {
|
|
2580
|
-
filesUsed.filter((f) => f !== "-f").forEach((f) => lines.push(` - ${f}`));
|
|
2581
|
-
}
|
|
2582
|
-
lines.push("");
|
|
2583
|
-
if (serviceMatch && serviceMatch[1]) {
|
|
2584
|
-
const serviceName = serviceMatch[1];
|
|
2585
|
-
lines.push(
|
|
2586
|
-
`ROOT CAUSE: Service "${serviceName}" is referenced in the merged stack, but none of the files provide an "image:" or "build:".`
|
|
2587
|
-
);
|
|
2588
|
-
lines.push("");
|
|
2589
|
-
lines.push(
|
|
2590
|
-
`Files declared in build.json that define a "${serviceName}:" service block:`
|
|
2591
|
-
);
|
|
2592
|
-
const definers = findServiceDefinersInDeclaredFiles(
|
|
2593
|
-
buildJson,
|
|
2594
|
-
projectDir,
|
|
2595
|
-
serviceName
|
|
2596
|
-
);
|
|
2597
|
-
if (definers.length > 0) {
|
|
2598
|
-
definers.forEach((d) => lines.push(d));
|
|
2599
|
-
} else {
|
|
2600
|
-
lines.push(
|
|
2601
|
-
` (none found \u2014 check spelling/indentation of "${serviceName}:" in files declared in build.json)`
|
|
2602
|
-
);
|
|
2603
|
-
}
|
|
2604
|
-
lines.push("");
|
|
2605
|
-
lines.push("HOW TO FIX:");
|
|
2606
|
-
lines.push(
|
|
2607
|
-
` - Ensure the file declaring service "${serviceName}" with an "image:" or "build:" is referenced in build.json under dependencies or overrides.`
|
|
2608
|
-
);
|
|
2609
|
-
} else if (/env_file.*must be a string/i.test(rawOutput)) {
|
|
2610
|
-
lines.push(
|
|
2611
|
-
`ROOT CAUSE: Docker Compose schema error for env_file. Your Docker Compose version is likely older than 2.24.0, which does not support the object syntax { path, required: false }.`
|
|
2612
|
-
);
|
|
2613
|
-
lines.push("");
|
|
2614
|
-
lines.push("HOW TO FIX:");
|
|
2615
|
-
lines.push(
|
|
2616
|
-
` - Upgrade Docker Compose to version 2.24.0 or newer to support modern compose templates.`
|
|
2617
|
-
);
|
|
2618
|
-
} else if (/required variable "?([^"\s]+)"? is missing a value/i.test(rawOutput)) {
|
|
2619
|
-
const varMatch = rawOutput.match(/required variable "?([^"\s]+)"? is missing a value/i);
|
|
2620
|
-
const varName = varMatch ? varMatch[1] : "VARIABLE";
|
|
2621
|
-
lines.push(
|
|
2622
|
-
`ROOT CAUSE: Required environment variable "${varName}" is missing a value.`
|
|
2623
|
-
);
|
|
2624
|
-
lines.push("");
|
|
2625
|
-
lines.push("HOW TO FIX:");
|
|
2626
|
-
lines.push(
|
|
2627
|
-
` - Define "${varName}" in your shell environment or inside your .env file.`
|
|
2628
|
-
);
|
|
2629
|
-
} else if (/port is already allocated|address already in use/i.test(rawOutput)) {
|
|
2630
|
-
lines.push(
|
|
2631
|
-
`ROOT CAUSE: Host port collision. A requested host port is already allocated or in use by another running process or container.`
|
|
2632
|
-
);
|
|
2633
|
-
lines.push("");
|
|
2634
|
-
lines.push("HOW TO FIX:");
|
|
2635
|
-
lines.push(
|
|
2636
|
-
` - Stop the conflicting process or container, or change the exposed host port in build.json / compose overrides.`
|
|
2637
|
-
);
|
|
2638
|
-
} else if (envMissingMatch) {
|
|
2639
|
-
lines.push(`ROOT CAUSE: A referenced .env file could not be found.`);
|
|
2640
|
-
lines.push("");
|
|
2641
|
-
lines.push("HOW TO FIX:");
|
|
2642
|
-
lines.push(
|
|
2643
|
-
` - Create the missing env file at the project root (e.g. .env.dev, .env.prod, .env.test)`
|
|
2644
|
-
);
|
|
2645
|
-
} else {
|
|
2646
|
-
lines.push(
|
|
2647
|
-
"Docker Compose failed to resolve this merged stack. Common causes:"
|
|
2648
|
-
);
|
|
2649
|
-
lines.push(
|
|
2650
|
-
` - A "\${VAR}" substitution with no default and no value set in the shell or an env_file.`
|
|
2651
|
-
);
|
|
2652
|
-
lines.push(` - A YAML syntax error in one of the files listed in build.json.`);
|
|
2653
|
-
lines.push(` - A duplicate or conflicting key across merged compose files.`);
|
|
2654
|
-
}
|
|
2655
|
-
lines.push("");
|
|
2656
|
-
lines.push("Raw Docker Compose output:");
|
|
2657
|
-
lines.push("-".repeat(60));
|
|
2658
|
-
lines.push(rawOutput.trim());
|
|
2659
|
-
lines.push("-".repeat(60));
|
|
2660
|
-
return lines.join("\n");
|
|
2661
|
-
}
|
|
2662
|
-
var cachedTemplatesDir = null;
|
|
2663
|
-
var lastEnvTemplatesDir = void 0;
|
|
2664
|
-
function getTemplatesDir() {
|
|
2665
|
-
const envVal = process.env.BUILDER_TEMPLATES_DIR;
|
|
2666
|
-
if (envVal !== lastEnvTemplatesDir) {
|
|
2667
|
-
cachedTemplatesDir = null;
|
|
2668
|
-
lastEnvTemplatesDir = envVal;
|
|
2669
|
-
}
|
|
2670
|
-
if (envVal) {
|
|
2671
|
-
const envDir = path13.resolve(envVal);
|
|
2672
|
-
if (!fs.existsSync(envDir) || !fs.existsSync(path13.join(envDir, "docker"))) {
|
|
2673
|
-
throw new ScriptError(
|
|
2674
|
-
`BUILDER_TEMPLATES_DIR is set to "${envVal}" but directory does not exist or lacks a "docker/" subdirectory (resolved: "${envDir}").`
|
|
2675
|
-
);
|
|
2676
|
-
}
|
|
2677
|
-
return envDir;
|
|
2678
|
-
}
|
|
2679
|
-
if (cachedTemplatesDir && fs.existsSync(cachedTemplatesDir)) {
|
|
2680
|
-
return cachedTemplatesDir;
|
|
2681
|
-
}
|
|
2682
|
-
const currentDir = typeof __dirname !== "undefined" ? __dirname : path13.dirname(fileURLToPath(import.meta.url));
|
|
2683
|
-
const candidates = [
|
|
2684
|
-
// When executing compiled output in dist/ (e.g. dist/templates)
|
|
2685
|
-
path13.resolve(currentDir, "templates"),
|
|
2686
|
-
path13.resolve(currentDir, "../templates"),
|
|
2687
|
-
// When executing from src/ (e.g. src/core/templates.ts -> ../../templates)
|
|
2688
|
-
path13.resolve(currentDir, "../../templates"),
|
|
2689
|
-
// Fallback relative to cwd
|
|
2690
|
-
path13.resolve(process.cwd(), "templates")
|
|
2691
|
-
];
|
|
2692
|
-
for (const cand of candidates) {
|
|
2693
|
-
if (fs.existsSync(cand) && fs.existsSync(path13.join(cand, "docker"))) {
|
|
2694
|
-
cachedTemplatesDir = cand;
|
|
2695
|
-
return cand;
|
|
2696
|
-
}
|
|
2697
|
-
}
|
|
2698
|
-
throw new ScriptError(
|
|
2699
|
-
`Templates directory not found. Searched candidates:
|
|
2700
|
-
${candidates.join("\n")}`
|
|
2701
|
-
);
|
|
2702
|
-
}
|
|
2703
|
-
function getDockerComposeTemplate(filename) {
|
|
2704
|
-
const templatesDir = getTemplatesDir();
|
|
2705
|
-
const filePath = path13.join(templatesDir, "docker", filename);
|
|
2706
|
-
if (!fs.existsSync(filePath)) {
|
|
2707
|
-
throw new ScriptError(`Docker compose template not found: ${filePath}`);
|
|
2708
|
-
}
|
|
2709
|
-
return filePath;
|
|
2710
|
-
}
|
|
2711
|
-
|
|
2712
|
-
// src/core/compileEnvironment.ts
|
|
2713
|
-
var compileEnvironment = (environment, projectDir = process.cwd(), options = {}) => {
|
|
2714
|
-
const absProjectDir = resolveProjectDir(projectDir);
|
|
2715
|
-
const buildJson = getBuildJson(absProjectDir);
|
|
2716
|
-
const overrides = extractOverrides(buildJson, absProjectDir);
|
|
2717
|
-
const dependencies = extractBuildDeps(buildJson, absProjectDir);
|
|
2718
|
-
const rawProjectName = buildJson.name || path13.basename(absProjectDir);
|
|
2719
|
-
const projectName = deriveProjectName(rawProjectName, environment);
|
|
2720
|
-
const baseComposePath = getDockerComposeTemplate("docker-compose.base.yml");
|
|
2721
|
-
const composeFlags = [
|
|
2722
|
-
"compose",
|
|
2723
|
-
"-p",
|
|
2724
|
-
projectName,
|
|
2725
|
-
"--project-directory",
|
|
2726
|
-
absProjectDir,
|
|
2727
|
-
"-f",
|
|
2728
|
-
baseComposePath
|
|
2729
|
-
];
|
|
2730
|
-
const filesUsed = [baseComposePath];
|
|
2731
|
-
const defaultEnv = path13.resolve(absProjectDir, ".env");
|
|
2732
|
-
if (existsSync(defaultEnv)) {
|
|
2733
|
-
composeFlags.push("--env-file", defaultEnv);
|
|
2734
|
-
}
|
|
2735
|
-
if (environment === "e2e") {
|
|
2736
|
-
const prodEnv = path13.resolve(absProjectDir, ".env.prod");
|
|
2737
|
-
if (existsSync(prodEnv)) {
|
|
2738
|
-
composeFlags.push("--env-file", prodEnv);
|
|
2739
|
-
}
|
|
2740
|
-
const e2eEnv = path13.resolve(absProjectDir, ".env.e2e");
|
|
2741
|
-
if (existsSync(e2eEnv)) {
|
|
2742
|
-
composeFlags.push("--env-file", e2eEnv);
|
|
2743
|
-
}
|
|
2744
|
-
} else {
|
|
2745
|
-
const stageEnv = path13.resolve(absProjectDir, `.env.${environment}`);
|
|
2746
|
-
if (existsSync(stageEnv)) {
|
|
2747
|
-
composeFlags.push("--env-file", stageEnv);
|
|
2748
|
-
}
|
|
2749
|
-
}
|
|
2750
|
-
switch (environment) {
|
|
2751
|
-
case "dev": {
|
|
2752
|
-
const devPath = getDockerComposeTemplate("docker-compose.dev.yml");
|
|
2753
|
-
const standalonePath = getDockerComposeTemplate("docker-compose.standalone.yml");
|
|
2754
|
-
composeFlags.push("-f", devPath);
|
|
2755
|
-
filesUsed.push(devPath);
|
|
2756
|
-
if (overrides.dev) {
|
|
2757
|
-
composeFlags.push("-f", overrides.dev.path);
|
|
2758
|
-
filesUsed.push(overrides.dev.path);
|
|
2759
|
-
}
|
|
2760
|
-
if (options.full && dependencies.length > 0) {
|
|
2761
|
-
for (const dep of dependencies) {
|
|
2762
|
-
composeFlags.push("-f", dep.path);
|
|
2763
|
-
filesUsed.push(dep.path);
|
|
2764
|
-
}
|
|
2765
|
-
}
|
|
2766
|
-
composeFlags.push("-f", standalonePath);
|
|
2767
|
-
filesUsed.push(standalonePath);
|
|
2768
|
-
break;
|
|
2769
|
-
}
|
|
2770
|
-
case "test": {
|
|
2771
|
-
const testPath = getDockerComposeTemplate("docker-compose.test.yml");
|
|
2772
|
-
composeFlags.push("-f", testPath);
|
|
2773
|
-
filesUsed.push(testPath);
|
|
2774
|
-
if (overrides.test) {
|
|
2775
|
-
composeFlags.push("-f", overrides.test.path);
|
|
2776
|
-
filesUsed.push(overrides.test.path);
|
|
2777
|
-
}
|
|
2778
|
-
break;
|
|
2779
|
-
}
|
|
2780
|
-
case "prod": {
|
|
2781
|
-
const prodPath = getDockerComposeTemplate("docker-compose.prod.yml");
|
|
2782
|
-
const standalonePath = getDockerComposeTemplate("docker-compose.standalone.yml");
|
|
2783
|
-
composeFlags.push("-f", prodPath);
|
|
2784
|
-
filesUsed.push(prodPath);
|
|
2785
|
-
if (overrides.prod) {
|
|
2786
|
-
composeFlags.push("-f", overrides.prod.path);
|
|
2787
|
-
filesUsed.push(overrides.prod.path);
|
|
2788
|
-
}
|
|
2789
|
-
if (dependencies.length > 0) {
|
|
2790
|
-
for (const dep of dependencies) {
|
|
2791
|
-
composeFlags.push("-f", dep.path);
|
|
2792
|
-
filesUsed.push(dep.path);
|
|
2793
|
-
}
|
|
2794
|
-
}
|
|
2795
|
-
composeFlags.push("-f", standalonePath);
|
|
2796
|
-
filesUsed.push(standalonePath);
|
|
2797
|
-
break;
|
|
2798
|
-
}
|
|
2799
|
-
case "e2e": {
|
|
2800
|
-
const prodPath = getDockerComposeTemplate("docker-compose.prod.yml");
|
|
2801
|
-
const e2ePath = getDockerComposeTemplate("docker-compose.e2e.yml");
|
|
2802
|
-
const standalonePath = getDockerComposeTemplate("docker-compose.standalone.yml");
|
|
2803
|
-
composeFlags.push("-f", prodPath);
|
|
2804
|
-
filesUsed.push(prodPath);
|
|
2805
|
-
if (overrides.prod) {
|
|
2806
|
-
composeFlags.push("-f", overrides.prod.path);
|
|
2807
|
-
filesUsed.push(overrides.prod.path);
|
|
2808
|
-
}
|
|
2809
|
-
if (dependencies.length > 0) {
|
|
2810
|
-
for (const dep of dependencies) {
|
|
2811
|
-
composeFlags.push("-f", dep.path);
|
|
2812
|
-
filesUsed.push(dep.path);
|
|
2813
|
-
}
|
|
2814
|
-
}
|
|
2815
|
-
composeFlags.push("-f", standalonePath);
|
|
2816
|
-
filesUsed.push(standalonePath);
|
|
2817
|
-
composeFlags.push("-f", e2ePath);
|
|
2818
|
-
filesUsed.push(e2ePath);
|
|
2819
|
-
if (overrides.e2e) {
|
|
2820
|
-
composeFlags.push("-f", overrides.e2e.path);
|
|
2821
|
-
filesUsed.push(overrides.e2e.path);
|
|
2822
|
-
}
|
|
2823
|
-
break;
|
|
2824
|
-
}
|
|
2825
|
-
}
|
|
2826
|
-
composeFlags.push("config");
|
|
2827
|
-
const envVars = { ...process.env };
|
|
2828
|
-
if (buildJson.port) {
|
|
2829
|
-
envVars.PUBLIC_PORT = String(buildJson.port);
|
|
2830
|
-
}
|
|
2831
|
-
envVars.PORT = "3000";
|
|
2832
|
-
const result = spawnSync("docker", composeFlags, {
|
|
2833
|
-
cwd: absProjectDir,
|
|
2834
|
-
encoding: "utf-8",
|
|
2835
|
-
env: envVars
|
|
2836
|
-
});
|
|
2837
|
-
if (result.error) {
|
|
2838
|
-
throw new ScriptError(
|
|
2839
|
-
`Failed to run docker compose: ${result.error.message}`,
|
|
2840
|
-
{ cause: result.error }
|
|
2841
|
-
);
|
|
2842
|
-
}
|
|
2843
|
-
if (result.status !== 0) {
|
|
2844
|
-
const rawOutput = result.stderr || result.stdout;
|
|
2845
|
-
const explanation = explainComposeMergeFailure(
|
|
2846
|
-
buildJson,
|
|
2847
|
-
absProjectDir,
|
|
2848
|
-
environment,
|
|
2849
|
-
filesUsed,
|
|
2850
|
-
rawOutput
|
|
2851
|
-
);
|
|
2852
|
-
throw new ScriptError(`\u274C Failed to merge compose files:
|
|
2853
|
-
${explanation}`);
|
|
2854
|
-
}
|
|
2855
|
-
const mergedYamlConfig = result.stdout;
|
|
2856
|
-
const yml = parse(mergedYamlConfig);
|
|
2857
|
-
if (environment === "prod" || environment === "e2e" || environment === "dev" && options.full) {
|
|
2858
|
-
renameServicesWithDependencies(yml, dependencies);
|
|
2859
|
-
addDependenciesToAppService(yml, dependencies);
|
|
2860
|
-
}
|
|
2861
|
-
if (environment === "e2e") {
|
|
2862
|
-
makeE2eDependOnApp(yml);
|
|
2863
|
-
}
|
|
2864
|
-
const INTERNAL_PORT = 3e3;
|
|
2865
|
-
const urlRegistry = /* @__PURE__ */ new Map();
|
|
2866
|
-
const appPublicPort = buildJson.port ? Number(buildJson.port) : null;
|
|
2867
|
-
urlRegistry.set("app", {
|
|
2868
|
-
networkUrl: `http://app:${INTERNAL_PORT}`,
|
|
2869
|
-
publicUrl: appPublicPort ? `http://localhost:${appPublicPort}` : null
|
|
2870
|
-
});
|
|
2871
|
-
if (buildJson.name && buildJson.name !== "app") {
|
|
2872
|
-
urlRegistry.set(buildJson.name, urlRegistry.get("app"));
|
|
2873
|
-
}
|
|
2874
|
-
for (const dep of dependencies) {
|
|
2875
|
-
const depPortStr = dep.port ? String(dep.port) : null;
|
|
2876
|
-
const depHostPort = depPortStr ? depPortStr.includes(":") ? depPortStr.split(":")[0] : depPortStr : null;
|
|
2877
|
-
urlRegistry.set(dep.name, {
|
|
2878
|
-
networkUrl: `http://${dep.name}:${INTERNAL_PORT}`,
|
|
2879
|
-
publicUrl: depHostPort ? `http://localhost:${depHostPort}` : null
|
|
2880
|
-
});
|
|
2881
|
-
}
|
|
2882
|
-
const interpolateEnv = (val, context) => {
|
|
2883
|
-
if (!options.silenceWarnings && context.includes("Tester") && val.includes(".network_url")) {
|
|
2884
|
-
console.warn(
|
|
2885
|
-
pc22.yellow(`
|
|
2886
|
-
\u26A0\uFE0F WARNING: You are passing a '.network_url' template to the E2E tester ("${val}"). Since the tester runs in 'network_mode: host', it cannot resolve internal Docker DNS. Use '.public_url' instead. (Mute with --silence-warnings)
|
|
2887
|
-
`)
|
|
2888
|
-
);
|
|
2889
|
-
}
|
|
2890
|
-
let output = val;
|
|
2891
|
-
for (const [sName, urls] of urlRegistry.entries()) {
|
|
2892
|
-
const escaped = sName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
2893
|
-
output = output.replace(
|
|
2894
|
-
new RegExp(`\\$\\{${escaped}\\.network_url\\}`, "g"),
|
|
2895
|
-
urls.networkUrl
|
|
2896
|
-
);
|
|
2897
|
-
if (urls.publicUrl) {
|
|
2898
|
-
output = output.replace(
|
|
2899
|
-
new RegExp(`\\$\\{${escaped}\\.public_url\\}`, "g"),
|
|
2900
|
-
urls.publicUrl
|
|
2901
|
-
);
|
|
2902
|
-
}
|
|
2903
|
-
}
|
|
2904
|
-
const unresolvedMatch = output.match(/\$\{([^}]+?)\.(network_url|public_url)\}/);
|
|
2905
|
-
if (unresolvedMatch) {
|
|
2906
|
-
const variable = unresolvedMatch[0];
|
|
2907
|
-
const targetService = unresolvedMatch[1];
|
|
2908
|
-
const type = unresolvedMatch[2];
|
|
2909
|
-
if (!urlRegistry.has(targetService)) {
|
|
2910
|
-
throw new ScriptError(
|
|
2911
|
-
`[${context}] Unresolved template variable: ${variable}. Check build.json dependencies.`
|
|
2912
|
-
);
|
|
2913
|
-
} else if (type === "public_url") {
|
|
2914
|
-
throw new ScriptError(
|
|
2915
|
-
`[${context}] Unresolved template variable: ${variable}. Service "${targetService}" does not expose a public port (missing 'port' explicitly defined in build.json).`
|
|
2916
|
-
);
|
|
2917
|
-
} else {
|
|
2918
|
-
throw new ScriptError(`[${context}] Unresolved template variable: ${variable}.`);
|
|
2919
|
-
}
|
|
2920
|
-
}
|
|
2921
|
-
return output;
|
|
2922
|
-
};
|
|
2923
|
-
const normalizeEnvironment = (serviceConfig) => {
|
|
2924
|
-
if (Array.isArray(serviceConfig.environment)) {
|
|
2925
|
-
const envObj = {};
|
|
2926
|
-
for (const item of serviceConfig.environment) {
|
|
2927
|
-
if (typeof item === "string") {
|
|
2928
|
-
const eqIdx = item.indexOf("=");
|
|
2929
|
-
if (eqIdx !== -1) {
|
|
2930
|
-
envObj[item.slice(0, eqIdx)] = item.slice(eqIdx + 1);
|
|
2931
|
-
} else {
|
|
2932
|
-
envObj[item] = process.env[item] ?? null;
|
|
2933
|
-
}
|
|
2934
|
-
}
|
|
2935
|
-
}
|
|
2936
|
-
serviceConfig.environment = envObj;
|
|
2937
|
-
} else if (!serviceConfig.environment || typeof serviceConfig.environment !== "object") {
|
|
2938
|
-
serviceConfig.environment = {};
|
|
2939
|
-
}
|
|
2940
|
-
};
|
|
2941
|
-
const normalizeBuildArgs = (serviceConfig) => {
|
|
2942
|
-
if (typeof serviceConfig.build === "string") {
|
|
2943
|
-
serviceConfig.build = {
|
|
2944
|
-
context: serviceConfig.build
|
|
2945
|
-
};
|
|
2946
|
-
}
|
|
2947
|
-
if (serviceConfig.build && typeof serviceConfig.build === "object") {
|
|
2948
|
-
if (Array.isArray(serviceConfig.build.args)) {
|
|
2949
|
-
const argsObj = {};
|
|
2950
|
-
for (const item of serviceConfig.build.args) {
|
|
2951
|
-
if (typeof item === "string") {
|
|
2952
|
-
const eqIdx = item.indexOf("=");
|
|
2953
|
-
if (eqIdx !== -1) {
|
|
2954
|
-
argsObj[item.slice(0, eqIdx)] = item.slice(eqIdx + 1);
|
|
2955
|
-
} else {
|
|
2956
|
-
argsObj[item] = process.env[item] ?? null;
|
|
2957
|
-
}
|
|
2958
|
-
}
|
|
2959
|
-
}
|
|
2960
|
-
serviceConfig.build.args = argsObj;
|
|
2961
|
-
} else if (!serviceConfig.build.args || typeof serviceConfig.build.args !== "object") {
|
|
2962
|
-
serviceConfig.build.args = {};
|
|
2963
|
-
}
|
|
2964
|
-
}
|
|
2965
|
-
};
|
|
2966
|
-
if (buildJson.envOverrides && yml.services && yml.services.app) {
|
|
2967
|
-
normalizeEnvironment(yml.services.app);
|
|
2968
|
-
normalizeBuildArgs(yml.services.app);
|
|
2969
|
-
for (const [k, v] of Object.entries(buildJson.envOverrides)) {
|
|
2970
|
-
const val = interpolateEnv(v, "App EnvOverrides");
|
|
2971
|
-
yml.services.app.environment[k] = val;
|
|
2972
|
-
if (yml.services.app.build?.args) {
|
|
2973
|
-
yml.services.app.build.args[k] = val;
|
|
2974
|
-
}
|
|
2975
|
-
}
|
|
2976
|
-
}
|
|
2977
|
-
if (buildJson.tester?.envOverrides && yml.services && yml.services.tester) {
|
|
2978
|
-
normalizeEnvironment(yml.services.tester);
|
|
2979
|
-
normalizeBuildArgs(yml.services.tester);
|
|
2980
|
-
for (const [k, v] of Object.entries(buildJson.tester.envOverrides)) {
|
|
2981
|
-
const val = interpolateEnv(v, "Tester EnvOverrides");
|
|
2982
|
-
yml.services.tester.environment[k] = val;
|
|
2983
|
-
if (yml.services.tester.build?.args) {
|
|
2984
|
-
yml.services.tester.build.args[k] = val;
|
|
2985
|
-
}
|
|
2986
|
-
}
|
|
2987
|
-
}
|
|
2988
|
-
if (yml.services && (environment === "prod" || environment === "e2e" || environment === "dev" && options.full)) {
|
|
2989
|
-
for (const dep of dependencies) {
|
|
2990
|
-
const mappings = getDependencyPortMappings(dep, `Dependency "${dep.name}"`);
|
|
2991
|
-
let targetSvc = dep.serviceName && yml.services[dep.serviceName] ? dep.serviceName : dep.name;
|
|
2992
|
-
if (!yml.services[targetSvc]) {
|
|
2993
|
-
targetSvc = Object.keys(yml.services).find((key) => key !== "app" && key !== "tester") ?? targetSvc;
|
|
2994
|
-
}
|
|
2995
|
-
const service = yml.services[targetSvc];
|
|
2996
|
-
if (!service) {
|
|
2997
|
-
throw new ScriptError(`Dependency "${dep.name}" target service could not be resolved for port injection.`);
|
|
2998
|
-
}
|
|
2999
|
-
delete service.ports;
|
|
3000
|
-
if (mappings.length > 0) service.ports = mappings.map((mapping) => mapping.raw);
|
|
3001
|
-
}
|
|
3002
|
-
}
|
|
3003
|
-
if (environment === "dev" && options.full && yml.services?.app) {
|
|
3004
|
-
normalizeEnvironment(yml.services.app);
|
|
3005
|
-
yml.services.app.environment.INFRA_MODE = "integrated";
|
|
3006
|
-
}
|
|
3007
|
-
attachName(yml, projectName);
|
|
3008
|
-
const finalYamlConfig = stringify(yml);
|
|
3009
|
-
assertUniqueHostPortMappings(finalYamlConfig);
|
|
3010
|
-
return finalYamlConfig;
|
|
3011
|
-
};
|
|
3012
|
-
|
|
3013
|
-
// src/core/runners/runTestUnit.ts
|
|
3014
|
-
var runTestUnit = async (options) => {
|
|
3015
|
-
if (!options.skipBanner) {
|
|
3016
|
-
console.log(pc22.bold(pc22.blue(`
|
|
3017
|
-
========================================`)));
|
|
3018
|
-
console.log(pc22.bold(pc22.blue(`\u{1F9EA} STAGE: UNIT & ISOLATED TESTS`)));
|
|
3019
|
-
console.log(pc22.bold(pc22.blue(`========================================
|
|
3020
|
-
`)));
|
|
3021
|
-
}
|
|
3022
|
-
const finalYamlConfig = compileEnvironment("test", options.projectDir, {
|
|
3023
|
-
silenceWarnings: options.silenceWarnings
|
|
3024
|
-
});
|
|
3025
|
-
const parsed = parse(finalYamlConfig);
|
|
3026
|
-
const projectName = parsed?.name || "test";
|
|
3027
|
-
if (options.debug) {
|
|
3028
|
-
console.log(
|
|
3029
|
-
pc22.yellow("Final merged YAML configuration:\n"),
|
|
3030
|
-
redactYamlSecrets(finalYamlConfig)
|
|
3031
|
-
);
|
|
3032
|
-
}
|
|
3033
|
-
if (options.dryRun) {
|
|
3034
|
-
console.log(pc22.green("[DRY-RUN] Unit tests simulated. Compose was not started."));
|
|
3035
|
-
return 0;
|
|
3036
|
-
}
|
|
3037
|
-
await teardownCompose(finalYamlConfig, options.projectDir, {
|
|
3038
|
-
removeVolumes: true,
|
|
3039
|
-
silent: true
|
|
3040
|
-
});
|
|
3041
|
-
writeRunState(options.projectDir, {
|
|
3042
|
-
projectName,
|
|
3043
|
-
stage: "test-unit",
|
|
3044
|
-
projectDir: options.projectDir
|
|
3045
|
-
});
|
|
3046
|
-
let status = 0;
|
|
3047
|
-
try {
|
|
3048
|
-
status = await runCompose(
|
|
3049
|
-
["up", "--build", "--abort-on-container-exit", "--exit-code-from", "app"],
|
|
3050
|
-
finalYamlConfig,
|
|
3051
|
-
options.projectDir,
|
|
3052
|
-
{ removeVolumes: true }
|
|
3053
|
-
);
|
|
3054
|
-
} finally {
|
|
3055
|
-
await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
|
|
3056
|
-
clearRunState(options.projectDir);
|
|
3057
|
-
}
|
|
3058
|
-
if (status === 0) {
|
|
3059
|
-
console.log(pc22.bold(pc22.green(`
|
|
3060
|
-
\u2705 Unit tests passed successfully.
|
|
3061
|
-
`)));
|
|
3062
|
-
} else {
|
|
3063
|
-
console.error(pc22.red(`
|
|
3064
|
-
\u274C Unit tests failed with exit code ${status}.
|
|
3065
|
-
`));
|
|
3066
|
-
}
|
|
3067
|
-
return status;
|
|
3068
|
-
};
|
|
3069
|
-
var runTestE2e = async (options) => {
|
|
3070
|
-
if (!options.skipBanner) {
|
|
3071
|
-
console.log(pc22.bold(pc22.blue(`
|
|
3072
|
-
========================================`)));
|
|
3073
|
-
console.log(pc22.bold(pc22.blue(`\u{1F6A6} STAGE: INTEGRATED E2E TESTS`)));
|
|
3074
|
-
console.log(pc22.bold(pc22.blue(`========================================
|
|
3075
|
-
`)));
|
|
3076
|
-
}
|
|
3077
|
-
const finalYamlConfig = compileEnvironment("e2e", options.projectDir, {
|
|
3078
|
-
silenceWarnings: options.silenceWarnings
|
|
3079
|
-
});
|
|
3080
|
-
const parsed = parse(finalYamlConfig);
|
|
3081
|
-
const projectName = parsed?.name || "e2e";
|
|
3082
|
-
if (options.debug) {
|
|
3083
|
-
console.log(
|
|
3084
|
-
pc22.yellow("Final merged YAML configuration:\n"),
|
|
3085
|
-
redactYamlSecrets(finalYamlConfig)
|
|
3086
|
-
);
|
|
3087
|
-
}
|
|
3088
|
-
if (options.dryRun) {
|
|
3089
|
-
console.log(pc22.green("[DRY-RUN] E2E tests simulated. Compose was not started."));
|
|
3090
|
-
return 0;
|
|
3091
|
-
}
|
|
3092
|
-
await teardownCompose(finalYamlConfig, options.projectDir, {
|
|
3093
|
-
removeVolumes: true,
|
|
3094
|
-
silent: true
|
|
3095
|
-
});
|
|
3096
|
-
writeRunState(options.projectDir, {
|
|
3097
|
-
projectName,
|
|
3098
|
-
stage: "test-e2e",
|
|
3099
|
-
projectDir: options.projectDir
|
|
3100
|
-
});
|
|
3101
|
-
let status = 0;
|
|
3102
|
-
try {
|
|
3103
|
-
status = await runCompose(
|
|
3104
|
-
[
|
|
3105
|
-
"up",
|
|
3106
|
-
"--build",
|
|
3107
|
-
"--abort-on-container-exit",
|
|
3108
|
-
"--exit-code-from",
|
|
3109
|
-
"tester"
|
|
3110
|
-
],
|
|
3111
|
-
finalYamlConfig,
|
|
3112
|
-
options.projectDir,
|
|
3113
|
-
{ removeVolumes: true }
|
|
3114
|
-
);
|
|
3115
|
-
} finally {
|
|
3116
|
-
await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
|
|
3117
|
-
clearRunState(options.projectDir);
|
|
3118
|
-
}
|
|
3119
|
-
if (status === 0) {
|
|
3120
|
-
console.log(pc22.bold(pc22.green(`
|
|
3121
|
-
\u2705 E2E tests passed successfully.
|
|
3122
|
-
`)));
|
|
3123
|
-
} else {
|
|
3124
|
-
console.error(pc22.red(`
|
|
3125
|
-
\u274C E2E tests failed with exit code ${status}.
|
|
3126
|
-
`));
|
|
3127
|
-
}
|
|
3128
|
-
return status;
|
|
3129
|
-
};
|
|
3130
|
-
|
|
3131
|
-
// src/core/runners/runTest.ts
|
|
3132
|
-
var runTest = async (options) => {
|
|
3133
|
-
console.log(pc22.bold(pc22.blue(`
|
|
3134
|
-
========================================`)));
|
|
3135
|
-
console.log(pc22.bold(pc22.blue(`\u{1F9EA} [1/2] STAGE: UNIT & ISOLATED TESTS`)));
|
|
3136
|
-
console.log(pc22.bold(pc22.blue(`========================================
|
|
3137
|
-
`)));
|
|
3138
|
-
const unitStatus = await runTestUnit({ ...options, skipBanner: true });
|
|
3139
|
-
if (unitStatus !== 0) {
|
|
3140
|
-
console.error(
|
|
3141
|
-
pc22.red(
|
|
3142
|
-
`
|
|
3143
|
-
\u274C [1/2] Unit tests failed with exit code ${unitStatus}. Aborting E2E tests.
|
|
3144
|
-
`
|
|
3145
|
-
)
|
|
3146
|
-
);
|
|
3147
|
-
return unitStatus;
|
|
3148
|
-
}
|
|
3149
|
-
console.log(
|
|
3150
|
-
pc22.bold(pc22.green(`
|
|
3151
|
-
\u2705 [1/2] Unit tests passed successfully.
|
|
3152
|
-
`))
|
|
3153
|
-
);
|
|
3154
|
-
console.log(pc22.bold(pc22.blue(`========================================`)));
|
|
3155
|
-
console.log(pc22.bold(pc22.blue(`\u{1F6A6} [2/2] STAGE: INTEGRATED E2E TESTS`)));
|
|
3156
|
-
console.log(pc22.bold(pc22.blue(`========================================
|
|
3157
|
-
`)));
|
|
3158
|
-
const e2eStatus = await runTestE2e({ ...options, skipBanner: true });
|
|
3159
|
-
if (e2eStatus !== 0) {
|
|
3160
|
-
console.error(
|
|
3161
|
-
pc22.red(`
|
|
3162
|
-
\u274C [2/2] E2E tests failed with exit code ${e2eStatus}.
|
|
3163
|
-
`)
|
|
3164
|
-
);
|
|
3165
|
-
return e2eStatus;
|
|
3166
|
-
}
|
|
3167
|
-
console.log(pc22.bold(pc22.green(`
|
|
3168
|
-
\u2705 [2/2] E2E tests passed successfully.
|
|
3169
|
-
`)));
|
|
3170
|
-
console.log(
|
|
3171
|
-
pc22.bold(
|
|
3172
|
-
pc22.green(`\u{1F389} All test stages (unit + e2e) completed successfully!
|
|
3173
|
-
`)
|
|
3174
|
-
)
|
|
3175
|
-
);
|
|
3176
|
-
return 0;
|
|
3177
|
-
};
|
|
3178
|
-
async function runMeshTestE2e(options = {}) {
|
|
3179
|
-
const meshDir = resolveProjectDir(options.projectDir);
|
|
3180
|
-
console.log(pc22.bold(pc22.blue(`
|
|
3181
|
-
========================================`)));
|
|
3182
|
-
console.log(pc22.bold(pc22.blue(`\u{1F6A6} [MESH] STAGE: GLOBAL INTEGRATED E2E TESTS`)));
|
|
3183
|
-
console.log(pc22.bold(pc22.blue(`========================================
|
|
3184
|
-
`)));
|
|
3185
|
-
if (!options.skipChecks) {
|
|
3186
|
-
checkMesh(meshDir, { requireTester: true });
|
|
3187
|
-
}
|
|
3188
|
-
const { yaml, testerServiceName } = compileMeshEnvironment("prod", meshDir, {
|
|
3189
|
-
includeTester: true,
|
|
3190
|
-
silenceWarnings: options.silenceWarnings
|
|
3191
|
-
});
|
|
3192
|
-
if (!testerServiceName) {
|
|
3193
|
-
throw new ScriptError(
|
|
3194
|
-
"No tester service could be identified in the tester docker compose configuration."
|
|
3195
|
-
);
|
|
3196
|
-
}
|
|
3197
|
-
if (options.debug) {
|
|
3198
|
-
console.log(
|
|
3199
|
-
pc22.yellow("\nFinal merged Mesh E2E YAML configuration:\n"),
|
|
3200
|
-
redactYamlSecrets(yaml)
|
|
3201
|
-
);
|
|
3202
|
-
}
|
|
3203
|
-
if (options.dryRun) {
|
|
3204
|
-
console.log(pc22.green("[DRY-RUN] Global E2E test simulated. Compose was not started."));
|
|
3205
|
-
return 0;
|
|
3206
|
-
}
|
|
3207
|
-
const parsed = parse(yaml);
|
|
3208
|
-
const projectName = parsed?.name || "mesh-e2e";
|
|
3209
|
-
await teardownCompose(yaml, meshDir, { removeVolumes: true, silent: true });
|
|
3210
|
-
writeRunState(meshDir, {
|
|
3211
|
-
projectName,
|
|
3212
|
-
stage: "test-e2e",
|
|
3213
|
-
projectDir: meshDir
|
|
3214
|
-
});
|
|
3215
|
-
let status = 0;
|
|
3216
|
-
try {
|
|
3217
|
-
status = await runCompose(
|
|
3218
|
-
[
|
|
3219
|
-
"up",
|
|
3220
|
-
"--build",
|
|
3221
|
-
"--abort-on-container-exit",
|
|
3222
|
-
"--exit-code-from",
|
|
3223
|
-
testerServiceName
|
|
3224
|
-
],
|
|
3225
|
-
yaml,
|
|
3226
|
-
meshDir,
|
|
3227
|
-
{ removeVolumes: true }
|
|
3228
|
-
);
|
|
3229
|
-
} finally {
|
|
3230
|
-
console.log(pc22.cyan("\n\u{1F9F9} Cleaning up global mesh containers and volumes..."));
|
|
3231
|
-
await teardownCompose(yaml, meshDir, { removeVolumes: true });
|
|
3232
|
-
clearRunState(meshDir);
|
|
3233
|
-
}
|
|
3234
|
-
if (status === 0) {
|
|
3235
|
-
console.log(pc22.bold(pc22.green(`
|
|
3236
|
-
\u2705 Global E2E tests passed successfully.
|
|
3237
|
-
`)));
|
|
3238
|
-
} else {
|
|
3239
|
-
console.error(pc22.red(`
|
|
3240
|
-
\u274C Global E2E tests failed with exit code ${status}.
|
|
3241
|
-
`));
|
|
3242
|
-
}
|
|
3243
|
-
return status;
|
|
3244
|
-
}
|
|
3245
|
-
|
|
3246
|
-
// src/core/mesh/runners/runMeshTest.ts
|
|
3247
|
-
async function runMeshTest(options = {}) {
|
|
3248
|
-
const meshDir = resolveProjectDir(options.projectDir);
|
|
3249
|
-
console.log(pc22.bold(pc22.blue(`
|
|
3250
|
-
========================================`)));
|
|
3251
|
-
console.log(pc22.bold(pc22.blue(`\u{1F9EA} GLOBAL MESH TEST PIPELINE`)));
|
|
3252
|
-
console.log(pc22.bold(pc22.blue(`========================================
|
|
3253
|
-
`)));
|
|
3254
|
-
if (!options.skipChecks) {
|
|
3255
|
-
checkMesh(meshDir, { requireTester: true });
|
|
3256
|
-
}
|
|
3257
|
-
const mesh = getMeshJson(meshDir);
|
|
3258
|
-
console.log(pc22.bold(pc22.blue(`
|
|
3259
|
-
========================================`)));
|
|
3260
|
-
console.log(
|
|
3261
|
-
pc22.bold(
|
|
3262
|
-
pc22.blue(`\u{1F9EA} [1/2] STAGE: LOCAL SUBMODULE TEST SUITES (Unit & Isolated E2E)`)
|
|
3263
|
-
)
|
|
3264
|
-
);
|
|
3265
|
-
console.log(pc22.bold(pc22.blue(`========================================
|
|
3266
|
-
`)));
|
|
3267
|
-
for (const [serviceName, serviceConfig] of Object.entries(mesh.services)) {
|
|
3268
|
-
const serviceDir = path13.resolve(meshDir, serviceConfig.path);
|
|
3269
|
-
console.log(
|
|
3270
|
-
pc22.bold(pc22.cyan(`
|
|
3271
|
-
-> Running full test suite for [${serviceName}] in isolation...`))
|
|
3272
|
-
);
|
|
3273
|
-
if (options.dryRun) {
|
|
3274
|
-
console.log(
|
|
3275
|
-
pc22.green(`[DRY-RUN] Full isolated tests for ${serviceName} simulated.`)
|
|
3276
|
-
);
|
|
3277
|
-
continue;
|
|
3278
|
-
}
|
|
3279
|
-
const serviceStatus = await runTest({
|
|
3280
|
-
projectDir: serviceDir,
|
|
3281
|
-
debug: Boolean(options.debug),
|
|
3282
|
-
detach: Boolean(options.detach),
|
|
3283
|
-
silenceWarnings: options.silenceWarnings
|
|
3284
|
-
});
|
|
3285
|
-
if (serviceStatus !== 0) {
|
|
3286
|
-
console.error(
|
|
3287
|
-
pc22.red(
|
|
3288
|
-
`
|
|
3289
|
-
\u274C Isolated tests failed for service [${serviceName}] with exit code ${serviceStatus}. Aborting global E2E tests.
|
|
3290
|
-
`
|
|
3291
|
-
)
|
|
3292
|
-
);
|
|
3293
|
-
return serviceStatus;
|
|
3294
|
-
}
|
|
2186
|
+
const meshDir = resolveProjectDir(options.projectDir);
|
|
2187
|
+
console.log(pc22.cyan(`
|
|
2188
|
+
\u{1F3ED} Starting Global PROD Mesh Environment...`));
|
|
2189
|
+
const { yaml } = compileMeshEnvironment("prod", meshDir);
|
|
2190
|
+
const parsed = parse(yaml);
|
|
2191
|
+
const projectName = parsed?.name || "mesh-prod";
|
|
2192
|
+
if (options.debug) {
|
|
3295
2193
|
console.log(
|
|
3296
|
-
pc22.
|
|
3297
|
-
|
|
3298
|
-
`))
|
|
2194
|
+
pc22.yellow("\nFinal merged Mesh Prod YAML configuration:\n"),
|
|
2195
|
+
redactYamlSecrets(yaml)
|
|
3299
2196
|
);
|
|
3300
2197
|
}
|
|
3301
|
-
|
|
3302
|
-
|
|
3303
|
-
|
|
3304
|
-
pc22.bold(
|
|
3305
|
-
pc22.blue(`\u{1F6A6} [2/2] STAGE: INTEGRATED PRODUCTION MESH & GLOBAL E2E ASSERTIONS`)
|
|
3306
|
-
)
|
|
3307
|
-
);
|
|
3308
|
-
console.log(pc22.bold(pc22.blue(`========================================
|
|
3309
|
-
`)));
|
|
3310
|
-
const e2eStatus = await runMeshTestE2e({ ...options, skipChecks: true });
|
|
3311
|
-
if (e2eStatus !== 0) {
|
|
3312
|
-
return e2eStatus;
|
|
2198
|
+
if (options.dryRun) {
|
|
2199
|
+
console.log(pc22.green("Dry run complete. Compose was not started."));
|
|
2200
|
+
return 0;
|
|
3313
2201
|
}
|
|
3314
|
-
|
|
3315
|
-
|
|
3316
|
-
|
|
3317
|
-
|
|
3318
|
-
|
|
3319
|
-
|
|
3320
|
-
|
|
2202
|
+
const hostPorts = extractHostPorts(yaml);
|
|
2203
|
+
await checkHostPortCollisions(hostPorts);
|
|
2204
|
+
writeRunState(meshDir, {
|
|
2205
|
+
projectName,
|
|
2206
|
+
stage: "prod",
|
|
2207
|
+
projectDir: meshDir
|
|
2208
|
+
});
|
|
2209
|
+
const upArgs = ["up", "--build"];
|
|
2210
|
+
if (options.detach) {
|
|
2211
|
+
upArgs.push("-d");
|
|
2212
|
+
}
|
|
2213
|
+
let status = 0;
|
|
2214
|
+
try {
|
|
2215
|
+
status = await runCompose(upArgs, yaml, meshDir, {
|
|
2216
|
+
removeVolumes: false
|
|
2217
|
+
});
|
|
2218
|
+
} finally {
|
|
2219
|
+
if (!options.detach) {
|
|
2220
|
+
await teardownCompose(yaml, meshDir, { removeVolumes: false });
|
|
2221
|
+
clearRunState(meshDir);
|
|
2222
|
+
}
|
|
2223
|
+
}
|
|
2224
|
+
return status;
|
|
3321
2225
|
}
|
|
3322
2226
|
async function runMeshTestUnit(options = {}) {
|
|
3323
|
-
const meshDir = resolveProjectDir(options.projectDir);
|
|
3324
|
-
console.log(pc22.bold(pc22.blue(
|
|
3325
|
-
|
|
3326
|
-
|
|
3327
|
-
|
|
3328
|
-
|
|
3329
|
-
|
|
3330
|
-
|
|
3331
|
-
|
|
3332
|
-
|
|
3333
|
-
|
|
3334
|
-
const
|
|
3335
|
-
|
|
3336
|
-
|
|
3337
|
-
|
|
3338
|
-
|
|
2227
|
+
const meshDir = resolveProjectDir(options.projectDir), meshPath = path4.join(meshDir, "mesh.json"), raw = getMeshJson(meshDir), effective = resolveMeshStage(raw, "test", meshPath), services = loadEffectiveMeshServices(meshDir, effective, "test");
|
|
2228
|
+
console.log(pc22.bold(pc22.blue("\n[1/2] MESH SERVICE UNIT/ISOLATED TESTS\n")));
|
|
2229
|
+
for (const [name, svc] of Object.entries(services).sort(([a], [b]) => a.localeCompare(b))) {
|
|
2230
|
+
console.log(pc22.cyan(`-> Running isolated unit tests for [${name}]`));
|
|
2231
|
+
const compiled = compileServiceComposition("test", svc.absolutePath, { meshMode: true, full: false, externalAppEnv: {}, deferReferenceResolution: true, appServiceName: "app" });
|
|
2232
|
+
const endpoints = { app: { [name]: compiled.endpoints.app }, dependencies: { [name]: compiled.endpoints.dependencies } };
|
|
2233
|
+
const refCtx = { services: { [name]: svc }, bindings: /* @__PURE__ */ new Map(), endpoints, stage: "test", meshJsonPath: meshPath };
|
|
2234
|
+
const env = svc.meshEnv;
|
|
2235
|
+
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" });
|
|
2236
|
+
const resolvedBuild = resolveServiceBuildEnvThroughMesh(name, compiled.builderAppEnvironment ?? {}, refCtx, `services.${name}.app.env`);
|
|
2237
|
+
for (const [depName, depEnv] of Object.entries(compiled.dependencyEnvironments ?? {})) resolveServiceBuildEnvThroughMesh(name, depEnv, refCtx, `services.${name}.dependencies.${depName}.env`);
|
|
2238
|
+
const resolved = resolveMeshEnvMap(env, refCtx, `services.${name}.env`);
|
|
2239
|
+
const app = compiled.compose.services.app;
|
|
2240
|
+
app.environment = { ...app.environment, ...resolvedBuild, ...resolved };
|
|
2241
|
+
const projectName = `${deriveProjectName(raw.name ?? path4.basename(meshDir), "dev")}-${name}-test`;
|
|
2242
|
+
compiled.compose.name = projectName;
|
|
2243
|
+
const yaml = stringify(compiled.compose);
|
|
2244
|
+
if (options.debug) console.log(yaml);
|
|
3339
2245
|
if (options.dryRun) {
|
|
3340
|
-
console.log(pc22.green(`[DRY-RUN] Unit tests for ${
|
|
2246
|
+
console.log(pc22.green(`[DRY-RUN] Unit tests for ${name} compiled.`));
|
|
3341
2247
|
continue;
|
|
3342
2248
|
}
|
|
3343
|
-
|
|
3344
|
-
|
|
3345
|
-
|
|
3346
|
-
|
|
3347
|
-
|
|
3348
|
-
}
|
|
3349
|
-
|
|
3350
|
-
|
|
3351
|
-
pc22.red(`
|
|
3352
|
-
\u274C Unit tests failed for service [${serviceName}] with exit code ${unitStatus}.
|
|
3353
|
-
`)
|
|
3354
|
-
);
|
|
3355
|
-
return unitStatus;
|
|
2249
|
+
await teardownCompose(yaml, svc.absolutePath, { removeVolumes: true, silent: true });
|
|
2250
|
+
writeRunState(svc.absolutePath, { projectName, stage: "test-unit", projectDir: svc.absolutePath });
|
|
2251
|
+
let status;
|
|
2252
|
+
try {
|
|
2253
|
+
status = await runCompose(["up", "--build", "--abort-on-container-exit", "--exit-code-from", "app"], yaml, svc.absolutePath, { removeVolumes: true });
|
|
2254
|
+
} finally {
|
|
2255
|
+
await teardownCompose(yaml, svc.absolutePath, { removeVolumes: true });
|
|
2256
|
+
clearRunState(svc.absolutePath);
|
|
3356
2257
|
}
|
|
3357
|
-
|
|
3358
|
-
pc22.bold(pc22.green(`
|
|
3359
|
-
\u2705 Isolated unit tests passed for service: [${serviceName}]
|
|
3360
|
-
`))
|
|
3361
|
-
);
|
|
2258
|
+
if (status !== 0) return status;
|
|
3362
2259
|
}
|
|
3363
|
-
console.log(
|
|
3364
|
-
pc22.bold(pc22.green(`\u{1F389} All mesh service unit tests completed successfully!
|
|
3365
|
-
`))
|
|
3366
|
-
);
|
|
3367
2260
|
return 0;
|
|
3368
2261
|
}
|
|
2262
|
+
async function runMeshTestE2e(options = {}) {
|
|
2263
|
+
const meshDir = resolveProjectDir(options.projectDir), mesh = getMeshJson(meshDir);
|
|
2264
|
+
if (!options.skipChecks) checkMesh(meshDir, { requireTester: true });
|
|
2265
|
+
if (!mesh.tester) throw new ScriptError("Global mesh E2E requires root mesh.json.tester { compose, service, env? }");
|
|
2266
|
+
const { yaml, testerServiceName } = compileMeshEnvironment("e2e", meshDir);
|
|
2267
|
+
if (!testerServiceName) throw new ScriptError("Global mesh E2E tester runner could not be compiled.");
|
|
2268
|
+
if (options.debug) console.log(pc22.yellow("\nFinal global mesh E2E YAML configuration:\n"), redactYamlSecrets(yaml));
|
|
2269
|
+
if (options.dryRun) {
|
|
2270
|
+
console.log(pc22.green("[DRY-RUN] Global mesh E2E compiled; Compose was not started."));
|
|
2271
|
+
return 0;
|
|
2272
|
+
}
|
|
2273
|
+
await checkHostPortCollisions(extractHostPorts(yaml));
|
|
2274
|
+
const projectName = parse(yaml)?.name || "mesh-e2e";
|
|
2275
|
+
await teardownCompose(yaml, meshDir, { removeVolumes: true, silent: true });
|
|
2276
|
+
writeRunState(meshDir, { projectName, stage: "test-e2e", projectDir: meshDir });
|
|
2277
|
+
let status = 0;
|
|
2278
|
+
try {
|
|
2279
|
+
status = await runCompose(["up", "--build", "--abort-on-container-exit", "--exit-code-from", testerServiceName], yaml, meshDir, { removeVolumes: true });
|
|
2280
|
+
} finally {
|
|
2281
|
+
await teardownCompose(yaml, meshDir, { removeVolumes: true });
|
|
2282
|
+
clearRunState(meshDir);
|
|
2283
|
+
}
|
|
2284
|
+
return status;
|
|
2285
|
+
}
|
|
2286
|
+
|
|
2287
|
+
// src/core/mesh/runners/runMeshTest.ts
|
|
2288
|
+
async function runMeshTest(options = {}) {
|
|
2289
|
+
console.log(pc22.bold(pc22.blue("\n========================================\nMESH TEST PIPELINE\n========================================\n")));
|
|
2290
|
+
console.log(pc22.bold(pc22.blue("[1/2] MESH SERVICE UNIT/ISOLATED TESTS")));
|
|
2291
|
+
const unitStatus = await runMeshTestUnit(options);
|
|
2292
|
+
if (unitStatus !== 0) return unitStatus;
|
|
2293
|
+
console.log(pc22.bold(pc22.blue("[2/2] GLOBAL MESH E2E")));
|
|
2294
|
+
return runMeshTestE2e(options);
|
|
2295
|
+
}
|
|
3369
2296
|
|
|
3370
2297
|
// src/commands/mesh/commands/up/handler.ts
|
|
3371
2298
|
async function handleMeshUp(rawStage = "dev", options = {}) {
|
|
@@ -3417,7 +2344,10 @@ Examples:
|
|
|
3417
2344
|
$ builder mesh up prod
|
|
3418
2345
|
$ builder mesh up test
|
|
3419
2346
|
$ builder mesh up test-unit
|
|
3420
|
-
$ builder mesh up test-e2e
|
|
2347
|
+
$ builder mesh up test-e2e
|
|
2348
|
+
|
|
2349
|
+
JSON overlays: test-unit uses mesh/build test; test-e2e uses mesh/build e2e.
|
|
2350
|
+
The test command runs per-service unit tests before global E2E.`
|
|
3421
2351
|
).action(
|
|
3422
2352
|
async (stage = "dev", options = {}) => {
|
|
3423
2353
|
const exitCode = await handleMeshUp(stage, {
|
|
@@ -3425,8 +2355,7 @@ Examples:
|
|
|
3425
2355
|
debug: options.debug,
|
|
3426
2356
|
detach: options.detach,
|
|
3427
2357
|
dryRun: options.dryRun,
|
|
3428
|
-
skipChecks: options.skipChecks
|
|
3429
|
-
silenceWarnings: options.silenceWarnings
|
|
2358
|
+
skipChecks: options.skipChecks
|
|
3430
2359
|
});
|
|
3431
2360
|
if (exitCode !== 0) {
|
|
3432
2361
|
process.exit(exitCode);
|
|
@@ -3487,6 +2416,9 @@ var registerPruneCommand = (cmd) => {
|
|
|
3487
2416
|
}
|
|
3488
2417
|
});
|
|
3489
2418
|
};
|
|
2419
|
+
var compileEnvironment = (stage, projectDir = process.cwd(), options = {}) => stringify(compileServiceComposition(stage, projectDir, { full: Boolean(options.full), silenceWarnings: options.silenceWarnings }).compose);
|
|
2420
|
+
|
|
2421
|
+
// src/commands/service/commands/down/handler.ts
|
|
3490
2422
|
async function handleServiceDown(rawStage = "dev", options = {}) {
|
|
3491
2423
|
const projectDir = resolveProjectDir(options.projectDir);
|
|
3492
2424
|
const stage = (rawStage || "dev").toLowerCase();
|
|
@@ -3656,12 +2588,178 @@ var runProd = async (options) => {
|
|
|
3656
2588
|
}
|
|
3657
2589
|
return status;
|
|
3658
2590
|
};
|
|
2591
|
+
var runTestUnit = async (options) => {
|
|
2592
|
+
if (!options.skipBanner) {
|
|
2593
|
+
console.log(pc22.bold(pc22.blue(`
|
|
2594
|
+
========================================`)));
|
|
2595
|
+
console.log(pc22.bold(pc22.blue(`\u{1F9EA} STAGE: UNIT & ISOLATED TESTS`)));
|
|
2596
|
+
console.log(pc22.bold(pc22.blue(`========================================
|
|
2597
|
+
`)));
|
|
2598
|
+
}
|
|
2599
|
+
const finalYamlConfig = compileEnvironment("test", options.projectDir, {
|
|
2600
|
+
silenceWarnings: options.silenceWarnings
|
|
2601
|
+
});
|
|
2602
|
+
const parsed = parse(finalYamlConfig);
|
|
2603
|
+
const projectName = parsed?.name || "test";
|
|
2604
|
+
if (options.debug) {
|
|
2605
|
+
console.log(
|
|
2606
|
+
pc22.yellow("Final merged YAML configuration:\n"),
|
|
2607
|
+
redactYamlSecrets(finalYamlConfig)
|
|
2608
|
+
);
|
|
2609
|
+
}
|
|
2610
|
+
if (options.dryRun) {
|
|
2611
|
+
console.log(pc22.green("[DRY-RUN] Unit tests simulated. Compose was not started."));
|
|
2612
|
+
return 0;
|
|
2613
|
+
}
|
|
2614
|
+
await checkHostPortCollisions(extractHostPorts(finalYamlConfig));
|
|
2615
|
+
await teardownCompose(finalYamlConfig, options.projectDir, {
|
|
2616
|
+
removeVolumes: true,
|
|
2617
|
+
silent: true
|
|
2618
|
+
});
|
|
2619
|
+
writeRunState(options.projectDir, {
|
|
2620
|
+
projectName,
|
|
2621
|
+
stage: "test-unit",
|
|
2622
|
+
projectDir: options.projectDir
|
|
2623
|
+
});
|
|
2624
|
+
let status = 0;
|
|
2625
|
+
try {
|
|
2626
|
+
status = await runCompose(
|
|
2627
|
+
["up", "--build", "--abort-on-container-exit", "--exit-code-from", "app"],
|
|
2628
|
+
finalYamlConfig,
|
|
2629
|
+
options.projectDir,
|
|
2630
|
+
{ removeVolumes: true }
|
|
2631
|
+
);
|
|
2632
|
+
} finally {
|
|
2633
|
+
await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
|
|
2634
|
+
clearRunState(options.projectDir);
|
|
2635
|
+
}
|
|
2636
|
+
if (status === 0) {
|
|
2637
|
+
console.log(pc22.bold(pc22.green(`
|
|
2638
|
+
\u2705 Unit tests passed successfully.
|
|
2639
|
+
`)));
|
|
2640
|
+
} else {
|
|
2641
|
+
console.error(pc22.red(`
|
|
2642
|
+
\u274C Unit tests failed with exit code ${status}.
|
|
2643
|
+
`));
|
|
2644
|
+
}
|
|
2645
|
+
return status;
|
|
2646
|
+
};
|
|
2647
|
+
var runTestE2e = async (options) => {
|
|
2648
|
+
if (!options.skipBanner) {
|
|
2649
|
+
console.log(pc22.bold(pc22.blue(`
|
|
2650
|
+
========================================`)));
|
|
2651
|
+
console.log(pc22.bold(pc22.blue(`\u{1F6A6} STAGE: INTEGRATED E2E TESTS`)));
|
|
2652
|
+
console.log(pc22.bold(pc22.blue(`========================================
|
|
2653
|
+
`)));
|
|
2654
|
+
}
|
|
2655
|
+
const finalYamlConfig = compileEnvironment("e2e", options.projectDir, {
|
|
2656
|
+
silenceWarnings: options.silenceWarnings
|
|
2657
|
+
});
|
|
2658
|
+
const parsed = parse(finalYamlConfig);
|
|
2659
|
+
const projectName = parsed?.name || "e2e";
|
|
2660
|
+
if (options.debug) {
|
|
2661
|
+
console.log(
|
|
2662
|
+
pc22.yellow("Final merged YAML configuration:\n"),
|
|
2663
|
+
redactYamlSecrets(finalYamlConfig)
|
|
2664
|
+
);
|
|
2665
|
+
}
|
|
2666
|
+
if (options.dryRun) {
|
|
2667
|
+
console.log(pc22.green("[DRY-RUN] E2E tests simulated. Compose was not started."));
|
|
2668
|
+
return 0;
|
|
2669
|
+
}
|
|
2670
|
+
await checkHostPortCollisions(extractHostPorts(finalYamlConfig));
|
|
2671
|
+
await teardownCompose(finalYamlConfig, options.projectDir, {
|
|
2672
|
+
removeVolumes: true,
|
|
2673
|
+
silent: true
|
|
2674
|
+
});
|
|
2675
|
+
writeRunState(options.projectDir, {
|
|
2676
|
+
projectName,
|
|
2677
|
+
stage: "test-e2e",
|
|
2678
|
+
projectDir: options.projectDir
|
|
2679
|
+
});
|
|
2680
|
+
let status = 0;
|
|
2681
|
+
try {
|
|
2682
|
+
status = await runCompose(
|
|
2683
|
+
[
|
|
2684
|
+
"up",
|
|
2685
|
+
"--build",
|
|
2686
|
+
"--abort-on-container-exit",
|
|
2687
|
+
"--exit-code-from",
|
|
2688
|
+
"tester"
|
|
2689
|
+
],
|
|
2690
|
+
finalYamlConfig,
|
|
2691
|
+
options.projectDir,
|
|
2692
|
+
{ removeVolumes: true }
|
|
2693
|
+
);
|
|
2694
|
+
} finally {
|
|
2695
|
+
await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
|
|
2696
|
+
clearRunState(options.projectDir);
|
|
2697
|
+
}
|
|
2698
|
+
if (status === 0) {
|
|
2699
|
+
console.log(pc22.bold(pc22.green(`
|
|
2700
|
+
\u2705 E2E tests passed successfully.
|
|
2701
|
+
`)));
|
|
2702
|
+
} else {
|
|
2703
|
+
console.error(pc22.red(`
|
|
2704
|
+
\u274C E2E tests failed with exit code ${status}.
|
|
2705
|
+
`));
|
|
2706
|
+
}
|
|
2707
|
+
return status;
|
|
2708
|
+
};
|
|
2709
|
+
|
|
2710
|
+
// src/core/runners/runTest.ts
|
|
2711
|
+
var runTest = async (options) => {
|
|
2712
|
+
console.log(pc22.bold(pc22.blue(`
|
|
2713
|
+
========================================`)));
|
|
2714
|
+
console.log(pc22.bold(pc22.blue(`\u{1F9EA} [1/2] STAGE: UNIT & ISOLATED TESTS`)));
|
|
2715
|
+
console.log(pc22.bold(pc22.blue(`========================================
|
|
2716
|
+
`)));
|
|
2717
|
+
const unitStatus = await runTestUnit({ ...options, skipBanner: true });
|
|
2718
|
+
if (unitStatus !== 0) {
|
|
2719
|
+
console.error(
|
|
2720
|
+
pc22.red(
|
|
2721
|
+
`
|
|
2722
|
+
\u274C [1/2] Unit tests failed with exit code ${unitStatus}. Aborting E2E tests.
|
|
2723
|
+
`
|
|
2724
|
+
)
|
|
2725
|
+
);
|
|
2726
|
+
return unitStatus;
|
|
2727
|
+
}
|
|
2728
|
+
console.log(
|
|
2729
|
+
pc22.bold(pc22.green(`
|
|
2730
|
+
\u2705 [1/2] Unit tests passed successfully.
|
|
2731
|
+
`))
|
|
2732
|
+
);
|
|
2733
|
+
console.log(pc22.bold(pc22.blue(`========================================`)));
|
|
2734
|
+
console.log(pc22.bold(pc22.blue(`\u{1F6A6} [2/2] STAGE: INTEGRATED E2E TESTS`)));
|
|
2735
|
+
console.log(pc22.bold(pc22.blue(`========================================
|
|
2736
|
+
`)));
|
|
2737
|
+
const e2eStatus = await runTestE2e({ ...options, skipBanner: true });
|
|
2738
|
+
if (e2eStatus !== 0) {
|
|
2739
|
+
console.error(
|
|
2740
|
+
pc22.red(`
|
|
2741
|
+
\u274C [2/2] E2E tests failed with exit code ${e2eStatus}.
|
|
2742
|
+
`)
|
|
2743
|
+
);
|
|
2744
|
+
return e2eStatus;
|
|
2745
|
+
}
|
|
2746
|
+
console.log(pc22.bold(pc22.green(`
|
|
2747
|
+
\u2705 [2/2] E2E tests passed successfully.
|
|
2748
|
+
`)));
|
|
2749
|
+
console.log(
|
|
2750
|
+
pc22.bold(
|
|
2751
|
+
pc22.green(`\u{1F389} All test stages (unit + e2e) completed successfully!
|
|
2752
|
+
`)
|
|
2753
|
+
)
|
|
2754
|
+
);
|
|
2755
|
+
return 0;
|
|
2756
|
+
};
|
|
3659
2757
|
|
|
3660
2758
|
// src/commands/service/commands/up/handler.ts
|
|
3661
2759
|
async function handleServiceUp(rawStage, options = {}) {
|
|
3662
2760
|
const projectDir = resolveProjectDir(options.projectDir);
|
|
3663
2761
|
const stage = (rawStage || "dev").toLowerCase();
|
|
3664
|
-
const isFull = Boolean(options.full
|
|
2762
|
+
const isFull = Boolean(options.full);
|
|
3665
2763
|
const runOptions = {
|
|
3666
2764
|
projectDir,
|
|
3667
2765
|
debug: Boolean(options.debug),
|
|
@@ -3705,10 +2803,7 @@ var registerUpCommand = (cmd) => {
|
|
|
3705
2803
|
"Silence non-critical warnings like URL templating hints"
|
|
3706
2804
|
).option(
|
|
3707
2805
|
"--full",
|
|
3708
|
-
"Run dev
|
|
3709
|
-
).option(
|
|
3710
|
-
"--integrated",
|
|
3711
|
-
"Alias for --full"
|
|
2806
|
+
"Run dev with all declared local dependencies integrated"
|
|
3712
2807
|
).option(
|
|
3713
2808
|
"-C, --project-dir <dir>",
|
|
3714
2809
|
"Service project directory (defaults to cwd)"
|
|
@@ -3721,7 +2816,10 @@ Examples:
|
|
|
3721
2816
|
$ builder service up prod
|
|
3722
2817
|
$ builder service up test
|
|
3723
2818
|
$ builder service up test-unit
|
|
3724
|
-
$ builder service up test-e2e
|
|
2819
|
+
$ builder service up test-e2e
|
|
2820
|
+
|
|
2821
|
+
JSON overlays: test-unit uses build.json test; test-e2e uses build.json e2e.
|
|
2822
|
+
The test command runs unit tests before E2E.`
|
|
3725
2823
|
).action(
|
|
3726
2824
|
async (stage = "dev", options = {}) => {
|
|
3727
2825
|
const exitCode = await handleServiceUp(stage, {
|
|
@@ -3731,7 +2829,7 @@ Examples:
|
|
|
3731
2829
|
dryRun: options.dryRun,
|
|
3732
2830
|
skipChecks: options.skipChecks,
|
|
3733
2831
|
silenceWarnings: options.silenceWarnings,
|
|
3734
|
-
full: Boolean(options.full
|
|
2832
|
+
full: Boolean(options.full)
|
|
3735
2833
|
});
|
|
3736
2834
|
if (exitCode !== 0) {
|
|
3737
2835
|
process.exit(exitCode);
|
|
@@ -3804,7 +2902,7 @@ async function handleExportEnv(rawStage, options = {}) {
|
|
|
3804
2902
|
const files = [];
|
|
3805
2903
|
try {
|
|
3806
2904
|
for (const snapshot of snapshots) {
|
|
3807
|
-
let filename =
|
|
2905
|
+
let filename = path4.join(projectDir, `.env.${snapshot.stage}`);
|
|
3808
2906
|
while (true) {
|
|
3809
2907
|
let overwrite = false;
|
|
3810
2908
|
if (existsSync(filename)) {
|
|
@@ -3813,11 +2911,11 @@ async function handleExportEnv(rawStage, options = {}) {
|
|
|
3813
2911
|
if (!overwrite) {
|
|
3814
2912
|
const name = (await ask(`New filename for ${snapshot.stage} (relative to the service directory): `)).trim();
|
|
3815
2913
|
if (!name) continue;
|
|
3816
|
-
filename =
|
|
2914
|
+
filename = path4.resolve(projectDir, name);
|
|
3817
2915
|
continue;
|
|
3818
2916
|
}
|
|
3819
2917
|
}
|
|
3820
|
-
mkdirSync(
|
|
2918
|
+
mkdirSync(path4.dirname(filename), { recursive: true });
|
|
3821
2919
|
try {
|
|
3822
2920
|
writeFileSync(filename, snapshot.content, { encoding: "utf-8", flag: overwrite ? "w" : "wx", mode: 384 });
|
|
3823
2921
|
} catch (error) {
|
|
@@ -3838,7 +2936,7 @@ async function handleExportEnv(rawStage, options = {}) {
|
|
|
3838
2936
|
// src/commands/service/commands/export/command.ts
|
|
3839
2937
|
function registerExportCommand(service) {
|
|
3840
2938
|
const command = service.command("export").description("Export service configuration");
|
|
3841
|
-
command.command("env").description("Export the application's resolved environment for one or all stages").addArgument(new Argument("[stage]", "Stage to export (defaults to all four)").choices(["dev", "prod", "test", "e2e"])).option("-C, --project-dir <dir>", "Service project directory (defaults to cwd)").option("--full", "Export dev with mock dependencies and integrated infra mode").option("--
|
|
2939
|
+
command.command("env").description("Export the application's resolved environment for one or all stages").addArgument(new Argument("[stage]", "Stage to export (defaults to all four)").choices(["dev", "prod", "test", "e2e"])).option("-C, --project-dir <dir>", "Service project directory (defaults to cwd)").option("--full", "Export dev with mock dependencies and integrated infra mode").option("--silence-warnings", "Silence non-critical URL templating warnings").addHelpText("after", `
|
|
3842
2940
|
Examples:
|
|
3843
2941
|
$ builder service export env
|
|
3844
2942
|
$ builder service export env dev
|
|
@@ -3846,7 +2944,7 @@ Examples:
|
|
|
3846
2944
|
$ builder service export env dev --full`).action(async (stage, options) => {
|
|
3847
2945
|
await handleExportEnv(stage, {
|
|
3848
2946
|
projectDir: options.projectDir,
|
|
3849
|
-
full: Boolean(options.full
|
|
2947
|
+
full: Boolean(options.full),
|
|
3850
2948
|
silenceWarnings: options.silenceWarnings
|
|
3851
2949
|
});
|
|
3852
2950
|
});
|
|
@@ -3950,6 +3048,6 @@ ${formatted}
|
|
|
3950
3048
|
}
|
|
3951
3049
|
}
|
|
3952
3050
|
|
|
3953
|
-
export { NotFoundError, SERVICE_STAGES, ScriptError, buildJsonSchema, compileApplicationEnv, compileEnvironment, compileMeshEnvironment, createCli, meshSchema, runCli, runCompose, serializeApplicationEnv, teardownCompose, version };
|
|
3051
|
+
export { ConfigError, NotFoundError, PortConflictError, SERVICE_STAGES, ScriptError, buildJsonSchema, compileApplicationEnv, compileEnvironment, compileMeshEnvironment, createCli, meshSchema, runCli, runCompose, serializeApplicationEnv, teardownCompose, version };
|
|
3954
3052
|
//# sourceMappingURL=index.js.map
|
|
3955
3053
|
//# sourceMappingURL=index.js.map
|