@testmutant/cli 0.0.1 → 1.0.0-alpha.4
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/LICENSE +21 -0
- package/README.md +100 -0
- package/dist/action.js +483 -0
- package/dist/index.js +578 -0
- package/package.json +41 -5
- package/src/index.js +0 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Sleepycat Software LLC
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the “Software”), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
# TestMutant CLI
|
|
2
|
+
|
|
3
|
+
Command-line tools for using TestMutant locally and in CI.
|
|
4
|
+
|
|
5
|
+
## Requirements
|
|
6
|
+
|
|
7
|
+
- Node.js 20 or newer
|
|
8
|
+
- A TestMutant API key
|
|
9
|
+
|
|
10
|
+
## Installation
|
|
11
|
+
|
|
12
|
+
Run the CLI without installing it globally:
|
|
13
|
+
|
|
14
|
+
```sh
|
|
15
|
+
npx @testmutant/cli --help
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Or install it globally:
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
npm install -g @testmutant/cli
|
|
22
|
+
testmutant ping
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Configuration
|
|
26
|
+
|
|
27
|
+
The CLI reads configuration from environment variables or command-line flags.
|
|
28
|
+
|
|
29
|
+
| Environment variable | Flag | Description |
|
|
30
|
+
| --- | --- | --- |
|
|
31
|
+
| `TESTMUTANT_API_KEY` | `--api-key <key>` | TestMutant API key used to authenticate requests. |
|
|
32
|
+
| `TESTMUTANT_API_URL` | `--api-url <url>` | TestMutant API base URL. Defaults to `http://localhost:5086`. |
|
|
33
|
+
| `TESTMUTANT_REPOSITORY_PROVIDER` | | Optional repository provider override for `testmutant ci`. |
|
|
34
|
+
| `TESTMUTANT_REPOSITORY_FULL_NAME` | | Optional repository full name override for `testmutant ci`. |
|
|
35
|
+
| `TESTMUTANT_BASE_URL` | | Optional environment URL recorded by `testmutant ci`. |
|
|
36
|
+
| `TESTMUTANT_ENVIRONMENT` | | Optional environment name recorded by `testmutant ci`. |
|
|
37
|
+
| | `--timeout <ms>` | API request timeout in milliseconds. Defaults to `30000`. |
|
|
38
|
+
| | `--json` | Print command output as JSON. |
|
|
39
|
+
|
|
40
|
+
You can also put environment variables in a `.env` file in the directory where
|
|
41
|
+
you run the CLI:
|
|
42
|
+
|
|
43
|
+
```env
|
|
44
|
+
TESTMUTANT_API_KEY=tm_key_...
|
|
45
|
+
TESTMUTANT_API_URL=http://localhost:5086
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Local Usage
|
|
49
|
+
|
|
50
|
+
Verify that the CLI can connect to TestMutant:
|
|
51
|
+
|
|
52
|
+
```sh
|
|
53
|
+
TESTMUTANT_API_KEY=tm_key_... testmutant ping
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Use a non-default API URL:
|
|
57
|
+
|
|
58
|
+
```sh
|
|
59
|
+
TESTMUTANT_API_KEY=tm_key_... TESTMUTANT_API_URL=https://api.example.com testmutant ping
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Pass configuration directly as flags:
|
|
63
|
+
|
|
64
|
+
```sh
|
|
65
|
+
testmutant --api-key tm_key_... --api-url http://localhost:5086 ping
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Print machine-readable output:
|
|
69
|
+
|
|
70
|
+
```sh
|
|
71
|
+
testmutant --json ping
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## CI Usage
|
|
75
|
+
|
|
76
|
+
Store `TESTMUTANT_API_KEY` as a secret in your CI provider.
|
|
77
|
+
Example GitHub Actions step:
|
|
78
|
+
|
|
79
|
+
```yaml
|
|
80
|
+
- name: Record TestMutant CI run
|
|
81
|
+
run: npx @testmutant/cli --json ci
|
|
82
|
+
env:
|
|
83
|
+
TESTMUTANT_API_KEY: ${{ secrets.TESTMUTANT_API_KEY }}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Commands
|
|
87
|
+
|
|
88
|
+
### `testmutant ping`
|
|
89
|
+
|
|
90
|
+
Verifies that the CLI can authenticate with the TestMutant API and prints the
|
|
91
|
+
connected organization and CLI API version.
|
|
92
|
+
|
|
93
|
+
### `testmutant ci`
|
|
94
|
+
|
|
95
|
+
Detects repository, branch, commit, and CI provider metadata, creates a
|
|
96
|
+
TestMutant run, immediately completes it, and prints the run id and status.
|
|
97
|
+
|
|
98
|
+
## License
|
|
99
|
+
|
|
100
|
+
MIT. Copyright (c) 2026 Sleepycat Software LLC.
|
package/dist/action.js
ADDED
|
@@ -0,0 +1,483 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
|
|
4
|
+
// src/action.ts
|
|
5
|
+
var import_config4 = require("dotenv/config");
|
|
6
|
+
var import_node_fs2 = require("fs");
|
|
7
|
+
var import_node_path = require("path");
|
|
8
|
+
|
|
9
|
+
// src/config.ts
|
|
10
|
+
var DEFAULT_API_URL = "http://localhost:5086";
|
|
11
|
+
var API_KEY_ENV_VAR = "TESTMUTANT_API_KEY";
|
|
12
|
+
var API_URL_ENV_VAR = "TESTMUTANT_API_URL";
|
|
13
|
+
var CliError = class extends Error {
|
|
14
|
+
constructor(message, exitCode = 1) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.exitCode = exitCode;
|
|
17
|
+
this.name = "CliError";
|
|
18
|
+
}
|
|
19
|
+
exitCode;
|
|
20
|
+
};
|
|
21
|
+
function resolveConfig(input = {}) {
|
|
22
|
+
const apiKey = input.apiKey ?? process.env[API_KEY_ENV_VAR];
|
|
23
|
+
const apiUrl = input.apiUrl ?? process.env[API_URL_ENV_VAR] ?? DEFAULT_API_URL;
|
|
24
|
+
const timeoutMs = parseTimeout(input.timeout);
|
|
25
|
+
if (!apiKey) {
|
|
26
|
+
throw new CliError(
|
|
27
|
+
`Missing API key. Set ${API_KEY_ENV_VAR} or pass --api-key.`,
|
|
28
|
+
2
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
return {
|
|
32
|
+
apiKey,
|
|
33
|
+
apiUrl: normalizeApiUrl(apiUrl),
|
|
34
|
+
timeoutMs
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
function normalizeApiUrl(value) {
|
|
38
|
+
let url;
|
|
39
|
+
try {
|
|
40
|
+
url = new URL(value);
|
|
41
|
+
} catch {
|
|
42
|
+
throw new CliError(`Invalid API URL: ${value}`, 2);
|
|
43
|
+
}
|
|
44
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
45
|
+
throw new CliError("API URL must start with http:// or https://.", 2);
|
|
46
|
+
}
|
|
47
|
+
return url.toString().replace(/\/$/, "");
|
|
48
|
+
}
|
|
49
|
+
function parseTimeout(value) {
|
|
50
|
+
if (!value) {
|
|
51
|
+
return 3e4;
|
|
52
|
+
}
|
|
53
|
+
const timeoutMs = Number(value);
|
|
54
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) {
|
|
55
|
+
throw new CliError("Timeout must be a positive integer in milliseconds.", 2);
|
|
56
|
+
}
|
|
57
|
+
return timeoutMs;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// src/api-client.ts
|
|
61
|
+
var TestMutantApiClient = class {
|
|
62
|
+
constructor(options) {
|
|
63
|
+
this.options = options;
|
|
64
|
+
}
|
|
65
|
+
options;
|
|
66
|
+
async ping() {
|
|
67
|
+
return this.postJson("/api/cli/v1/ping", {
|
|
68
|
+
repositoryProvider: null,
|
|
69
|
+
repositoryFullName: null
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
async createRun(request) {
|
|
73
|
+
return this.postJson(
|
|
74
|
+
"/api/cli/v1/runs",
|
|
75
|
+
request,
|
|
76
|
+
201
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
async completeRun(runId, request) {
|
|
80
|
+
return this.postJson(
|
|
81
|
+
`/api/cli/v1/runs/${encodeURIComponent(runId)}/complete`,
|
|
82
|
+
request
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
async postJson(path, body, expectedStatus = 200) {
|
|
86
|
+
const response = await this.request(path, body);
|
|
87
|
+
if (response.status === 401) {
|
|
88
|
+
throw new CliError("Unauthorized. Check your TestMutant API key.", 3);
|
|
89
|
+
}
|
|
90
|
+
if (response.status !== expectedStatus) {
|
|
91
|
+
const detail = await readErrorDetail(response);
|
|
92
|
+
throw new CliError(
|
|
93
|
+
`TestMutant API request failed with HTTP ${response.status}.${detail}`
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
try {
|
|
97
|
+
return await response.json();
|
|
98
|
+
} catch {
|
|
99
|
+
throw new CliError("TestMutant API returned invalid JSON.");
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
async request(path, body) {
|
|
103
|
+
const controller = new AbortController();
|
|
104
|
+
const timeout = setTimeout(() => controller.abort(), this.options.timeoutMs);
|
|
105
|
+
try {
|
|
106
|
+
return await fetch(new URL(path, this.options.apiUrl), {
|
|
107
|
+
method: "POST",
|
|
108
|
+
body: JSON.stringify(body),
|
|
109
|
+
signal: controller.signal,
|
|
110
|
+
headers: {
|
|
111
|
+
accept: "application/json",
|
|
112
|
+
"content-type": "application/json",
|
|
113
|
+
authorization: `Bearer ${this.options.apiKey}`,
|
|
114
|
+
"user-agent": this.options.userAgent
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
} catch (error) {
|
|
118
|
+
if (error instanceof Error && error.name === "AbortError") {
|
|
119
|
+
throw new CliError(
|
|
120
|
+
`TestMutant API request timed out after ${this.options.timeoutMs} ms.`
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
124
|
+
throw new CliError(`Could not reach TestMutant API. ${message}`);
|
|
125
|
+
} finally {
|
|
126
|
+
clearTimeout(timeout);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
async function readErrorDetail(response) {
|
|
131
|
+
const body = await response.text();
|
|
132
|
+
if (!body) {
|
|
133
|
+
return "";
|
|
134
|
+
}
|
|
135
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
136
|
+
if (contentType.includes("json")) {
|
|
137
|
+
try {
|
|
138
|
+
const problem = JSON.parse(body);
|
|
139
|
+
const parts = [
|
|
140
|
+
typeof problem.title === "string" ? problem.title : null,
|
|
141
|
+
typeof problem.detail === "string" ? problem.detail : null,
|
|
142
|
+
formatValidationErrors(problem.errors)
|
|
143
|
+
].filter((part) => Boolean(part));
|
|
144
|
+
if (parts.length > 0) {
|
|
145
|
+
return ` ${truncate(parts.join(" "), 500)}`;
|
|
146
|
+
}
|
|
147
|
+
} catch {
|
|
148
|
+
return ` ${truncate(body, 500)}`;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return ` ${truncate(body, 500)}`;
|
|
152
|
+
}
|
|
153
|
+
function formatValidationErrors(errors) {
|
|
154
|
+
if (!errors || typeof errors !== "object") {
|
|
155
|
+
return null;
|
|
156
|
+
}
|
|
157
|
+
const messages = [];
|
|
158
|
+
for (const [field, value] of Object.entries(errors)) {
|
|
159
|
+
if (Array.isArray(value)) {
|
|
160
|
+
for (const item of value) {
|
|
161
|
+
if (typeof item === "string") {
|
|
162
|
+
messages.push(`${field}: ${item}`);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return messages.length > 0 ? messages.join(" ") : null;
|
|
168
|
+
}
|
|
169
|
+
function truncate(value, maxLength) {
|
|
170
|
+
if (value.length <= maxLength) {
|
|
171
|
+
return value;
|
|
172
|
+
}
|
|
173
|
+
return `${value.slice(0, maxLength)}...`;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// src/ci-metadata.ts
|
|
177
|
+
var import_node_child_process = require("child_process");
|
|
178
|
+
var import_node_fs = require("fs");
|
|
179
|
+
function buildCreateRunRequest(options = {}) {
|
|
180
|
+
const env = process.env;
|
|
181
|
+
const gitRepository = getGitRepositoryMetadata();
|
|
182
|
+
const repositoryProvider = normalize(options.repositoryProvider) ?? normalize(env.TESTMUTANT_REPOSITORY_PROVIDER) ?? detectRepositoryProvider(env) ?? gitRepository.provider;
|
|
183
|
+
const repositoryFullName = normalize(options.repositoryFullName) ?? normalize(env.TESTMUTANT_REPOSITORY_FULL_NAME) ?? detectRepositoryFullName(env) ?? gitRepository.fullName;
|
|
184
|
+
if (!repositoryFullName) {
|
|
185
|
+
throw new CliError(
|
|
186
|
+
"Could not determine repository full name from CI environment or git remote origin.",
|
|
187
|
+
2
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
return {
|
|
191
|
+
mode: normalize(options.mode) ?? "Advisory",
|
|
192
|
+
runKind: normalize(options.runKind) ?? "Advisory",
|
|
193
|
+
repositoryProvider: repositoryProvider ?? "GitHub",
|
|
194
|
+
repositoryFullName,
|
|
195
|
+
baseUrl: normalizeUrl(options.baseUrl) ?? detectBaseUrl(env),
|
|
196
|
+
environmentName: normalize(options.environmentName) ?? detectEnvironmentName(env),
|
|
197
|
+
branch: detectBranch(env) ?? git(["rev-parse", "--abbrev-ref", "HEAD"]),
|
|
198
|
+
commitSha: detectCommitSha(env) ?? git(["rev-parse", "HEAD"]),
|
|
199
|
+
pullRequestNumber: detectPullRequestNumber(env),
|
|
200
|
+
ciProvider: detectCiProvider(env),
|
|
201
|
+
ciRunId: detectCiRunId(env)
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
function detectRepositoryProvider(env) {
|
|
205
|
+
if (env.GITHUB_ACTIONS || env.GITHUB_REPOSITORY) {
|
|
206
|
+
return "GitHub";
|
|
207
|
+
}
|
|
208
|
+
if (env.GITLAB_CI || env.CI_PROJECT_PATH) {
|
|
209
|
+
return "GitLab";
|
|
210
|
+
}
|
|
211
|
+
if (env.BITBUCKET_BUILD_NUMBER || env.BITBUCKET_REPO_FULL_NAME) {
|
|
212
|
+
return "Bitbucket";
|
|
213
|
+
}
|
|
214
|
+
if (env.TF_BUILD || env.BUILD_REPOSITORY_URI) {
|
|
215
|
+
return "AzureDevOps";
|
|
216
|
+
}
|
|
217
|
+
return null;
|
|
218
|
+
}
|
|
219
|
+
function detectRepositoryFullName(env) {
|
|
220
|
+
if (env.GITHUB_REPOSITORY) {
|
|
221
|
+
return normalize(env.GITHUB_REPOSITORY);
|
|
222
|
+
}
|
|
223
|
+
if (env.GITLAB_CI && env.CI_PROJECT_PATH) {
|
|
224
|
+
return normalize(env.CI_PROJECT_PATH);
|
|
225
|
+
}
|
|
226
|
+
if (env.BITBUCKET_REPO_FULL_NAME) {
|
|
227
|
+
return normalize(env.BITBUCKET_REPO_FULL_NAME);
|
|
228
|
+
}
|
|
229
|
+
if (env.CIRCLE_PROJECT_USERNAME && env.CIRCLE_PROJECT_REPONAME) {
|
|
230
|
+
return `${env.CIRCLE_PROJECT_USERNAME}/${env.CIRCLE_PROJECT_REPONAME}`;
|
|
231
|
+
}
|
|
232
|
+
if (env.BUILD_REPOSITORY_NAME) {
|
|
233
|
+
return normalize(env.BUILD_REPOSITORY_NAME);
|
|
234
|
+
}
|
|
235
|
+
return null;
|
|
236
|
+
}
|
|
237
|
+
function detectBranch(env) {
|
|
238
|
+
return normalize(env.GITHUB_HEAD_REF) ?? normalize(env.GITHUB_REF_NAME) ?? branchFromGitRef(env.GITHUB_REF) ?? normalize(env.CI_COMMIT_REF_NAME) ?? normalize(env.BITBUCKET_BRANCH) ?? normalize(env.CIRCLE_BRANCH) ?? normalize(env.BUILDKITE_BRANCH) ?? normalize(env.BUILD_SOURCEBRANCHNAME) ?? branchFromGitRef(env.BUILD_SOURCEBRANCH);
|
|
239
|
+
}
|
|
240
|
+
function detectCommitSha(env) {
|
|
241
|
+
return normalize(env.GITHUB_SHA) ?? normalize(env.CI_COMMIT_SHA) ?? normalize(env.BITBUCKET_COMMIT) ?? normalize(env.CIRCLE_SHA1) ?? normalize(env.BUILDKITE_COMMIT) ?? normalize(env.BUILD_SOURCEVERSION);
|
|
242
|
+
}
|
|
243
|
+
function detectPullRequestNumber(env) {
|
|
244
|
+
return numberFromValue(env.GITHUB_REF?.match(/^refs\/pull\/(\d+)\//)?.[1]) ?? githubEventPullRequestNumber(env) ?? numberFromValue(env.CI_MERGE_REQUEST_IID) ?? numberFromValue(env.BITBUCKET_PR_ID) ?? numberFromValue(env.CIRCLE_PULL_REQUEST?.split("/").pop()) ?? numberFromValue(env.BUILDKITE_PULL_REQUEST) ?? numberFromValue(env.SYSTEM_PULLREQUEST_PULLREQUESTNUMBER);
|
|
245
|
+
}
|
|
246
|
+
function detectCiProvider(env) {
|
|
247
|
+
if (env.GITHUB_ACTIONS) {
|
|
248
|
+
return "GitHubActions";
|
|
249
|
+
}
|
|
250
|
+
if (env.GITLAB_CI) {
|
|
251
|
+
return "GitLabCI";
|
|
252
|
+
}
|
|
253
|
+
if (env.BITBUCKET_BUILD_NUMBER) {
|
|
254
|
+
return "BitbucketPipelines";
|
|
255
|
+
}
|
|
256
|
+
if (env.CIRCLECI) {
|
|
257
|
+
return "CircleCI";
|
|
258
|
+
}
|
|
259
|
+
if (env.BUILDKITE) {
|
|
260
|
+
return "Buildkite";
|
|
261
|
+
}
|
|
262
|
+
if (env.TF_BUILD) {
|
|
263
|
+
return "AzurePipelines";
|
|
264
|
+
}
|
|
265
|
+
if (env.JENKINS_URL) {
|
|
266
|
+
return "Jenkins";
|
|
267
|
+
}
|
|
268
|
+
return env.CI ? "CI" : null;
|
|
269
|
+
}
|
|
270
|
+
function detectCiRunId(env) {
|
|
271
|
+
return normalize(env.GITHUB_RUN_ID) ?? normalize(env.CI_PIPELINE_ID) ?? normalize(env.BITBUCKET_BUILD_NUMBER) ?? normalize(env.CIRCLE_WORKFLOW_ID) ?? normalize(env.CIRCLE_BUILD_NUM) ?? normalize(env.BUILDKITE_BUILD_ID) ?? normalize(env.BUILD_BUILDID) ?? normalize(env.BUILD_TAG) ?? normalize(env.BUILD_NUMBER);
|
|
272
|
+
}
|
|
273
|
+
function detectBaseUrl(env) {
|
|
274
|
+
return normalizeUrl(env.TESTMUTANT_BASE_URL) ?? normalizeUrl(env.DEPLOY_URL) ?? normalizeUrl(env.URL) ?? normalizeUrl(env.VERCEL_BRANCH_URL) ?? normalizeUrl(env.VERCEL_URL) ?? normalizeUrl(env.CF_PAGES_URL) ?? normalizeUrl(env.RENDER_EXTERNAL_URL);
|
|
275
|
+
}
|
|
276
|
+
function detectEnvironmentName(env) {
|
|
277
|
+
return normalize(env.TESTMUTANT_ENVIRONMENT) ?? normalize(env.CI_ENVIRONMENT_NAME) ?? normalize(env.VERCEL_ENV) ?? normalize(env.NETLIFY_CONTEXT) ?? normalize(env.CF_PAGES_BRANCH);
|
|
278
|
+
}
|
|
279
|
+
function githubEventPullRequestNumber(env) {
|
|
280
|
+
const eventPath = normalize(env.GITHUB_EVENT_PATH);
|
|
281
|
+
if (!eventPath || !(0, import_node_fs.existsSync)(eventPath)) {
|
|
282
|
+
return null;
|
|
283
|
+
}
|
|
284
|
+
try {
|
|
285
|
+
const event = JSON.parse((0, import_node_fs.readFileSync)(eventPath, "utf8"));
|
|
286
|
+
return numberFromValue(event.pull_request?.number) ?? numberFromValue(event.number);
|
|
287
|
+
} catch {
|
|
288
|
+
return null;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
function getGitRepositoryMetadata() {
|
|
292
|
+
const remote = git(["remote", "get-url", "origin"]);
|
|
293
|
+
return remote ? parseGitRemoteUrl(remote) : { provider: null, fullName: null };
|
|
294
|
+
}
|
|
295
|
+
function parseGitRemoteUrl(remoteUrl) {
|
|
296
|
+
const remote = remoteUrl.trim();
|
|
297
|
+
const url = parseRemoteAsUrl(remote);
|
|
298
|
+
const host = url?.host ?? parseScpRemoteHost(remote);
|
|
299
|
+
const path = url?.pathname ?? parseScpRemotePath(remote);
|
|
300
|
+
const fullName = path?.replace(/^\/+/, "").replace(/\.git$/i, "").replace(/^v\d+\//i, "");
|
|
301
|
+
return {
|
|
302
|
+
provider: host ? providerFromHost(host) : null,
|
|
303
|
+
fullName: normalize(fullName)
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
function parseRemoteAsUrl(remote) {
|
|
307
|
+
try {
|
|
308
|
+
return new URL(remote.replace(/^git\+/, ""));
|
|
309
|
+
} catch {
|
|
310
|
+
return null;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
function parseScpRemoteHost(remote) {
|
|
314
|
+
return remote.match(/^(?:[^@]+@)?([^:]+):(.+)$/)?.[1] ?? null;
|
|
315
|
+
}
|
|
316
|
+
function parseScpRemotePath(remote) {
|
|
317
|
+
return remote.match(/^(?:[^@]+@)?([^:]+):(.+)$/)?.[2] ?? null;
|
|
318
|
+
}
|
|
319
|
+
function providerFromHost(host) {
|
|
320
|
+
const normalized = host.toLowerCase();
|
|
321
|
+
if (normalized.includes("github")) {
|
|
322
|
+
return "GitHub";
|
|
323
|
+
}
|
|
324
|
+
if (normalized.includes("gitlab")) {
|
|
325
|
+
return "GitLab";
|
|
326
|
+
}
|
|
327
|
+
if (normalized.includes("bitbucket")) {
|
|
328
|
+
return "Bitbucket";
|
|
329
|
+
}
|
|
330
|
+
if (normalized.includes("dev.azure") || normalized.includes("visualstudio")) {
|
|
331
|
+
return "AzureDevOps";
|
|
332
|
+
}
|
|
333
|
+
return null;
|
|
334
|
+
}
|
|
335
|
+
function branchFromGitRef(value) {
|
|
336
|
+
const ref = normalize(value);
|
|
337
|
+
if (!ref) {
|
|
338
|
+
return null;
|
|
339
|
+
}
|
|
340
|
+
return ref.match(/^refs\/heads\/(.+)$/)?.[1] ?? ref.match(/^refs\/tags\/(.+)$/)?.[1] ?? null;
|
|
341
|
+
}
|
|
342
|
+
function normalizeUrl(value) {
|
|
343
|
+
const normalized = normalize(value);
|
|
344
|
+
if (!normalized) {
|
|
345
|
+
return null;
|
|
346
|
+
}
|
|
347
|
+
if (/^https?:\/\//i.test(normalized)) {
|
|
348
|
+
return normalized;
|
|
349
|
+
}
|
|
350
|
+
return `https://${normalized}`;
|
|
351
|
+
}
|
|
352
|
+
function numberFromValue(value) {
|
|
353
|
+
if (typeof value === "number" && Number.isInteger(value) && value > 0) {
|
|
354
|
+
return value;
|
|
355
|
+
}
|
|
356
|
+
if (typeof value !== "string") {
|
|
357
|
+
return null;
|
|
358
|
+
}
|
|
359
|
+
if (value.toLowerCase() === "false") {
|
|
360
|
+
return null;
|
|
361
|
+
}
|
|
362
|
+
const parsed = Number(value);
|
|
363
|
+
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
|
|
364
|
+
}
|
|
365
|
+
function normalize(value) {
|
|
366
|
+
const trimmed = value?.trim();
|
|
367
|
+
return trimmed ? trimmed : null;
|
|
368
|
+
}
|
|
369
|
+
function git(args) {
|
|
370
|
+
try {
|
|
371
|
+
const safeDirectory = process.cwd().replace(/\\/g, "/");
|
|
372
|
+
return normalize(
|
|
373
|
+
(0, import_node_child_process.execFileSync)("git", ["-c", `safe.directory=${safeDirectory}`, ...args], {
|
|
374
|
+
encoding: "utf8",
|
|
375
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
376
|
+
})
|
|
377
|
+
);
|
|
378
|
+
} catch {
|
|
379
|
+
return null;
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// src/run-ci.ts
|
|
384
|
+
async function runCi(options) {
|
|
385
|
+
applyOptionEnvironmentOverrides(options);
|
|
386
|
+
const config = resolveConfig({
|
|
387
|
+
apiKey: options.apiKey,
|
|
388
|
+
apiUrl: options.apiUrl,
|
|
389
|
+
timeout: options.timeout
|
|
390
|
+
});
|
|
391
|
+
const client = new TestMutantApiClient({
|
|
392
|
+
...config,
|
|
393
|
+
userAgent: options.userAgent
|
|
394
|
+
});
|
|
395
|
+
const createRunRequest = buildCreateRunRequest({
|
|
396
|
+
mode: options.mode,
|
|
397
|
+
repositoryProvider: options.provider,
|
|
398
|
+
repositoryFullName: options.repository,
|
|
399
|
+
baseUrl: options.baseUrl,
|
|
400
|
+
environmentName: options.environmentName
|
|
401
|
+
});
|
|
402
|
+
const created = await client.createRun(createRunRequest);
|
|
403
|
+
const completed = await client.completeRun(created.runId, {
|
|
404
|
+
status: "Passed",
|
|
405
|
+
summary: "CI metadata captured.",
|
|
406
|
+
results: {
|
|
407
|
+
kind: "advisory",
|
|
408
|
+
message: "TestMutant CLI vertical slice completed successfully.",
|
|
409
|
+
repositoryFullName: createRunRequest.repositoryFullName,
|
|
410
|
+
branch: createRunRequest.branch,
|
|
411
|
+
commitSha: createRunRequest.commitSha,
|
|
412
|
+
ciProvider: createRunRequest.ciProvider,
|
|
413
|
+
ciRunId: createRunRequest.ciRunId,
|
|
414
|
+
generatedAtUtc: (/* @__PURE__ */ new Date()).toISOString()
|
|
415
|
+
},
|
|
416
|
+
resultJson: null,
|
|
417
|
+
errorMessage: null
|
|
418
|
+
});
|
|
419
|
+
return {
|
|
420
|
+
runId: completed.runId,
|
|
421
|
+
status: completed.status
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
function applyOptionEnvironmentOverrides(options) {
|
|
425
|
+
if (options.apiKey) {
|
|
426
|
+
process.env[API_KEY_ENV_VAR] = options.apiKey;
|
|
427
|
+
}
|
|
428
|
+
if (options.apiUrl) {
|
|
429
|
+
process.env[API_URL_ENV_VAR] = options.apiUrl;
|
|
430
|
+
}
|
|
431
|
+
if (!process.env[API_URL_ENV_VAR]) {
|
|
432
|
+
process.env[API_URL_ENV_VAR] = DEFAULT_API_URL;
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
// src/action.ts
|
|
437
|
+
var packageInfo = readPackageInfo();
|
|
438
|
+
main().catch((error) => {
|
|
439
|
+
if (error instanceof CliError) {
|
|
440
|
+
fail(error.message);
|
|
441
|
+
}
|
|
442
|
+
if (error instanceof Error) {
|
|
443
|
+
fail(
|
|
444
|
+
process.env.TESTMUTANT_DEBUG === "1" && error.stack ? error.stack : error.message
|
|
445
|
+
);
|
|
446
|
+
}
|
|
447
|
+
fail(String(error));
|
|
448
|
+
});
|
|
449
|
+
async function main() {
|
|
450
|
+
const result = await runCi({
|
|
451
|
+
apiKey: process.env.TESTMUTANT_API_KEY,
|
|
452
|
+
apiUrl: getInput("api_url"),
|
|
453
|
+
mode: getInput("mode") ?? "Advisory",
|
|
454
|
+
repository: getInput("repository"),
|
|
455
|
+
provider: getInput("provider") ?? "GitHub",
|
|
456
|
+
baseUrl: getInput("base_url"),
|
|
457
|
+
environmentName: getInput("environment_name"),
|
|
458
|
+
userAgent: `testmutant-action/${packageInfo.version}`
|
|
459
|
+
});
|
|
460
|
+
console.log("TestMutant run completed.");
|
|
461
|
+
console.log(`Run ID: ${result.runId}`);
|
|
462
|
+
console.log(`Status: ${result.status}`);
|
|
463
|
+
}
|
|
464
|
+
function getInput(name) {
|
|
465
|
+
const value = process.env[`INPUT_${name.toUpperCase()}`];
|
|
466
|
+
return value?.trim() ? value.trim() : void 0;
|
|
467
|
+
}
|
|
468
|
+
function fail(message) {
|
|
469
|
+
console.error(message);
|
|
470
|
+
console.error(`::error::${escapeGithubAnnotation(message)}`);
|
|
471
|
+
process.exit(1);
|
|
472
|
+
}
|
|
473
|
+
function escapeGithubAnnotation(value) {
|
|
474
|
+
return value.replaceAll("%", "%25").replaceAll("\r", "%0D").replaceAll("\n", "%0A");
|
|
475
|
+
}
|
|
476
|
+
function readPackageInfo() {
|
|
477
|
+
const packageJsonPath = (0, import_node_path.join)(__dirname, "..", "package.json");
|
|
478
|
+
const packageJson = JSON.parse((0, import_node_fs2.readFileSync)(packageJsonPath, "utf8"));
|
|
479
|
+
return {
|
|
480
|
+
name: typeof packageJson.name === "string" ? packageJson.name : "@testmutant/cli",
|
|
481
|
+
version: typeof packageJson.version === "string" ? packageJson.version : "0.0.0"
|
|
482
|
+
};
|
|
483
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,578 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
#!/usr/bin/env node
|
|
3
|
+
"use strict";
|
|
4
|
+
|
|
5
|
+
// src/index.ts
|
|
6
|
+
var import_config4 = require("dotenv/config");
|
|
7
|
+
var import_node_fs2 = require("fs");
|
|
8
|
+
var import_node_path = require("path");
|
|
9
|
+
|
|
10
|
+
// src/config.ts
|
|
11
|
+
var DEFAULT_API_URL = "http://localhost:5086";
|
|
12
|
+
var API_KEY_ENV_VAR = "TESTMUTANT_API_KEY";
|
|
13
|
+
var API_URL_ENV_VAR = "TESTMUTANT_API_URL";
|
|
14
|
+
var CliError = class extends Error {
|
|
15
|
+
constructor(message, exitCode = 1) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.exitCode = exitCode;
|
|
18
|
+
this.name = "CliError";
|
|
19
|
+
}
|
|
20
|
+
exitCode;
|
|
21
|
+
};
|
|
22
|
+
function resolveConfig(input = {}) {
|
|
23
|
+
const apiKey = input.apiKey ?? process.env[API_KEY_ENV_VAR];
|
|
24
|
+
const apiUrl = input.apiUrl ?? process.env[API_URL_ENV_VAR] ?? DEFAULT_API_URL;
|
|
25
|
+
const timeoutMs = parseTimeout(input.timeout);
|
|
26
|
+
if (!apiKey) {
|
|
27
|
+
throw new CliError(
|
|
28
|
+
`Missing API key. Set ${API_KEY_ENV_VAR} or pass --api-key.`,
|
|
29
|
+
2
|
|
30
|
+
);
|
|
31
|
+
}
|
|
32
|
+
return {
|
|
33
|
+
apiKey,
|
|
34
|
+
apiUrl: normalizeApiUrl(apiUrl),
|
|
35
|
+
timeoutMs
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
function normalizeApiUrl(value) {
|
|
39
|
+
let url;
|
|
40
|
+
try {
|
|
41
|
+
url = new URL(value);
|
|
42
|
+
} catch {
|
|
43
|
+
throw new CliError(`Invalid API URL: ${value}`, 2);
|
|
44
|
+
}
|
|
45
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
46
|
+
throw new CliError("API URL must start with http:// or https://.", 2);
|
|
47
|
+
}
|
|
48
|
+
return url.toString().replace(/\/$/, "");
|
|
49
|
+
}
|
|
50
|
+
function parseTimeout(value) {
|
|
51
|
+
if (!value) {
|
|
52
|
+
return 3e4;
|
|
53
|
+
}
|
|
54
|
+
const timeoutMs = Number(value);
|
|
55
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) {
|
|
56
|
+
throw new CliError("Timeout must be a positive integer in milliseconds.", 2);
|
|
57
|
+
}
|
|
58
|
+
return timeoutMs;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// src/api-client.ts
|
|
62
|
+
var TestMutantApiClient = class {
|
|
63
|
+
constructor(options) {
|
|
64
|
+
this.options = options;
|
|
65
|
+
}
|
|
66
|
+
options;
|
|
67
|
+
async ping() {
|
|
68
|
+
return this.postJson("/api/cli/v1/ping", {
|
|
69
|
+
repositoryProvider: null,
|
|
70
|
+
repositoryFullName: null
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
async createRun(request) {
|
|
74
|
+
return this.postJson(
|
|
75
|
+
"/api/cli/v1/runs",
|
|
76
|
+
request,
|
|
77
|
+
201
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
async completeRun(runId, request) {
|
|
81
|
+
return this.postJson(
|
|
82
|
+
`/api/cli/v1/runs/${encodeURIComponent(runId)}/complete`,
|
|
83
|
+
request
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
async postJson(path, body, expectedStatus = 200) {
|
|
87
|
+
const response = await this.request(path, body);
|
|
88
|
+
if (response.status === 401) {
|
|
89
|
+
throw new CliError("Unauthorized. Check your TestMutant API key.", 3);
|
|
90
|
+
}
|
|
91
|
+
if (response.status !== expectedStatus) {
|
|
92
|
+
const detail = await readErrorDetail(response);
|
|
93
|
+
throw new CliError(
|
|
94
|
+
`TestMutant API request failed with HTTP ${response.status}.${detail}`
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
try {
|
|
98
|
+
return await response.json();
|
|
99
|
+
} catch {
|
|
100
|
+
throw new CliError("TestMutant API returned invalid JSON.");
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
async request(path, body) {
|
|
104
|
+
const controller = new AbortController();
|
|
105
|
+
const timeout = setTimeout(() => controller.abort(), this.options.timeoutMs);
|
|
106
|
+
try {
|
|
107
|
+
return await fetch(new URL(path, this.options.apiUrl), {
|
|
108
|
+
method: "POST",
|
|
109
|
+
body: JSON.stringify(body),
|
|
110
|
+
signal: controller.signal,
|
|
111
|
+
headers: {
|
|
112
|
+
accept: "application/json",
|
|
113
|
+
"content-type": "application/json",
|
|
114
|
+
authorization: `Bearer ${this.options.apiKey}`,
|
|
115
|
+
"user-agent": this.options.userAgent
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
} catch (error) {
|
|
119
|
+
if (error instanceof Error && error.name === "AbortError") {
|
|
120
|
+
throw new CliError(
|
|
121
|
+
`TestMutant API request timed out after ${this.options.timeoutMs} ms.`
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
125
|
+
throw new CliError(`Could not reach TestMutant API. ${message}`);
|
|
126
|
+
} finally {
|
|
127
|
+
clearTimeout(timeout);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
async function readErrorDetail(response) {
|
|
132
|
+
const body = await response.text();
|
|
133
|
+
if (!body) {
|
|
134
|
+
return "";
|
|
135
|
+
}
|
|
136
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
137
|
+
if (contentType.includes("json")) {
|
|
138
|
+
try {
|
|
139
|
+
const problem = JSON.parse(body);
|
|
140
|
+
const parts = [
|
|
141
|
+
typeof problem.title === "string" ? problem.title : null,
|
|
142
|
+
typeof problem.detail === "string" ? problem.detail : null,
|
|
143
|
+
formatValidationErrors(problem.errors)
|
|
144
|
+
].filter((part) => Boolean(part));
|
|
145
|
+
if (parts.length > 0) {
|
|
146
|
+
return ` ${truncate(parts.join(" "), 500)}`;
|
|
147
|
+
}
|
|
148
|
+
} catch {
|
|
149
|
+
return ` ${truncate(body, 500)}`;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return ` ${truncate(body, 500)}`;
|
|
153
|
+
}
|
|
154
|
+
function formatValidationErrors(errors) {
|
|
155
|
+
if (!errors || typeof errors !== "object") {
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
const messages = [];
|
|
159
|
+
for (const [field, value] of Object.entries(errors)) {
|
|
160
|
+
if (Array.isArray(value)) {
|
|
161
|
+
for (const item of value) {
|
|
162
|
+
if (typeof item === "string") {
|
|
163
|
+
messages.push(`${field}: ${item}`);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return messages.length > 0 ? messages.join(" ") : null;
|
|
169
|
+
}
|
|
170
|
+
function truncate(value, maxLength) {
|
|
171
|
+
if (value.length <= maxLength) {
|
|
172
|
+
return value;
|
|
173
|
+
}
|
|
174
|
+
return `${value.slice(0, maxLength)}...`;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// src/ci-metadata.ts
|
|
178
|
+
var import_node_child_process = require("child_process");
|
|
179
|
+
var import_node_fs = require("fs");
|
|
180
|
+
function buildCreateRunRequest(options = {}) {
|
|
181
|
+
const env = process.env;
|
|
182
|
+
const gitRepository = getGitRepositoryMetadata();
|
|
183
|
+
const repositoryProvider = normalize(options.repositoryProvider) ?? normalize(env.TESTMUTANT_REPOSITORY_PROVIDER) ?? detectRepositoryProvider(env) ?? gitRepository.provider;
|
|
184
|
+
const repositoryFullName = normalize(options.repositoryFullName) ?? normalize(env.TESTMUTANT_REPOSITORY_FULL_NAME) ?? detectRepositoryFullName(env) ?? gitRepository.fullName;
|
|
185
|
+
if (!repositoryFullName) {
|
|
186
|
+
throw new CliError(
|
|
187
|
+
"Could not determine repository full name from CI environment or git remote origin.",
|
|
188
|
+
2
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
return {
|
|
192
|
+
mode: normalize(options.mode) ?? "Advisory",
|
|
193
|
+
runKind: normalize(options.runKind) ?? "Advisory",
|
|
194
|
+
repositoryProvider: repositoryProvider ?? "GitHub",
|
|
195
|
+
repositoryFullName,
|
|
196
|
+
baseUrl: normalizeUrl(options.baseUrl) ?? detectBaseUrl(env),
|
|
197
|
+
environmentName: normalize(options.environmentName) ?? detectEnvironmentName(env),
|
|
198
|
+
branch: detectBranch(env) ?? git(["rev-parse", "--abbrev-ref", "HEAD"]),
|
|
199
|
+
commitSha: detectCommitSha(env) ?? git(["rev-parse", "HEAD"]),
|
|
200
|
+
pullRequestNumber: detectPullRequestNumber(env),
|
|
201
|
+
ciProvider: detectCiProvider(env),
|
|
202
|
+
ciRunId: detectCiRunId(env)
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
function detectRepositoryProvider(env) {
|
|
206
|
+
if (env.GITHUB_ACTIONS || env.GITHUB_REPOSITORY) {
|
|
207
|
+
return "GitHub";
|
|
208
|
+
}
|
|
209
|
+
if (env.GITLAB_CI || env.CI_PROJECT_PATH) {
|
|
210
|
+
return "GitLab";
|
|
211
|
+
}
|
|
212
|
+
if (env.BITBUCKET_BUILD_NUMBER || env.BITBUCKET_REPO_FULL_NAME) {
|
|
213
|
+
return "Bitbucket";
|
|
214
|
+
}
|
|
215
|
+
if (env.TF_BUILD || env.BUILD_REPOSITORY_URI) {
|
|
216
|
+
return "AzureDevOps";
|
|
217
|
+
}
|
|
218
|
+
return null;
|
|
219
|
+
}
|
|
220
|
+
function detectRepositoryFullName(env) {
|
|
221
|
+
if (env.GITHUB_REPOSITORY) {
|
|
222
|
+
return normalize(env.GITHUB_REPOSITORY);
|
|
223
|
+
}
|
|
224
|
+
if (env.GITLAB_CI && env.CI_PROJECT_PATH) {
|
|
225
|
+
return normalize(env.CI_PROJECT_PATH);
|
|
226
|
+
}
|
|
227
|
+
if (env.BITBUCKET_REPO_FULL_NAME) {
|
|
228
|
+
return normalize(env.BITBUCKET_REPO_FULL_NAME);
|
|
229
|
+
}
|
|
230
|
+
if (env.CIRCLE_PROJECT_USERNAME && env.CIRCLE_PROJECT_REPONAME) {
|
|
231
|
+
return `${env.CIRCLE_PROJECT_USERNAME}/${env.CIRCLE_PROJECT_REPONAME}`;
|
|
232
|
+
}
|
|
233
|
+
if (env.BUILD_REPOSITORY_NAME) {
|
|
234
|
+
return normalize(env.BUILD_REPOSITORY_NAME);
|
|
235
|
+
}
|
|
236
|
+
return null;
|
|
237
|
+
}
|
|
238
|
+
function detectBranch(env) {
|
|
239
|
+
return normalize(env.GITHUB_HEAD_REF) ?? normalize(env.GITHUB_REF_NAME) ?? branchFromGitRef(env.GITHUB_REF) ?? normalize(env.CI_COMMIT_REF_NAME) ?? normalize(env.BITBUCKET_BRANCH) ?? normalize(env.CIRCLE_BRANCH) ?? normalize(env.BUILDKITE_BRANCH) ?? normalize(env.BUILD_SOURCEBRANCHNAME) ?? branchFromGitRef(env.BUILD_SOURCEBRANCH);
|
|
240
|
+
}
|
|
241
|
+
function detectCommitSha(env) {
|
|
242
|
+
return normalize(env.GITHUB_SHA) ?? normalize(env.CI_COMMIT_SHA) ?? normalize(env.BITBUCKET_COMMIT) ?? normalize(env.CIRCLE_SHA1) ?? normalize(env.BUILDKITE_COMMIT) ?? normalize(env.BUILD_SOURCEVERSION);
|
|
243
|
+
}
|
|
244
|
+
function detectPullRequestNumber(env) {
|
|
245
|
+
return numberFromValue(env.GITHUB_REF?.match(/^refs\/pull\/(\d+)\//)?.[1]) ?? githubEventPullRequestNumber(env) ?? numberFromValue(env.CI_MERGE_REQUEST_IID) ?? numberFromValue(env.BITBUCKET_PR_ID) ?? numberFromValue(env.CIRCLE_PULL_REQUEST?.split("/").pop()) ?? numberFromValue(env.BUILDKITE_PULL_REQUEST) ?? numberFromValue(env.SYSTEM_PULLREQUEST_PULLREQUESTNUMBER);
|
|
246
|
+
}
|
|
247
|
+
function detectCiProvider(env) {
|
|
248
|
+
if (env.GITHUB_ACTIONS) {
|
|
249
|
+
return "GitHubActions";
|
|
250
|
+
}
|
|
251
|
+
if (env.GITLAB_CI) {
|
|
252
|
+
return "GitLabCI";
|
|
253
|
+
}
|
|
254
|
+
if (env.BITBUCKET_BUILD_NUMBER) {
|
|
255
|
+
return "BitbucketPipelines";
|
|
256
|
+
}
|
|
257
|
+
if (env.CIRCLECI) {
|
|
258
|
+
return "CircleCI";
|
|
259
|
+
}
|
|
260
|
+
if (env.BUILDKITE) {
|
|
261
|
+
return "Buildkite";
|
|
262
|
+
}
|
|
263
|
+
if (env.TF_BUILD) {
|
|
264
|
+
return "AzurePipelines";
|
|
265
|
+
}
|
|
266
|
+
if (env.JENKINS_URL) {
|
|
267
|
+
return "Jenkins";
|
|
268
|
+
}
|
|
269
|
+
return env.CI ? "CI" : null;
|
|
270
|
+
}
|
|
271
|
+
function detectCiRunId(env) {
|
|
272
|
+
return normalize(env.GITHUB_RUN_ID) ?? normalize(env.CI_PIPELINE_ID) ?? normalize(env.BITBUCKET_BUILD_NUMBER) ?? normalize(env.CIRCLE_WORKFLOW_ID) ?? normalize(env.CIRCLE_BUILD_NUM) ?? normalize(env.BUILDKITE_BUILD_ID) ?? normalize(env.BUILD_BUILDID) ?? normalize(env.BUILD_TAG) ?? normalize(env.BUILD_NUMBER);
|
|
273
|
+
}
|
|
274
|
+
function detectBaseUrl(env) {
|
|
275
|
+
return normalizeUrl(env.TESTMUTANT_BASE_URL) ?? normalizeUrl(env.DEPLOY_URL) ?? normalizeUrl(env.URL) ?? normalizeUrl(env.VERCEL_BRANCH_URL) ?? normalizeUrl(env.VERCEL_URL) ?? normalizeUrl(env.CF_PAGES_URL) ?? normalizeUrl(env.RENDER_EXTERNAL_URL);
|
|
276
|
+
}
|
|
277
|
+
function detectEnvironmentName(env) {
|
|
278
|
+
return normalize(env.TESTMUTANT_ENVIRONMENT) ?? normalize(env.CI_ENVIRONMENT_NAME) ?? normalize(env.VERCEL_ENV) ?? normalize(env.NETLIFY_CONTEXT) ?? normalize(env.CF_PAGES_BRANCH);
|
|
279
|
+
}
|
|
280
|
+
function githubEventPullRequestNumber(env) {
|
|
281
|
+
const eventPath = normalize(env.GITHUB_EVENT_PATH);
|
|
282
|
+
if (!eventPath || !(0, import_node_fs.existsSync)(eventPath)) {
|
|
283
|
+
return null;
|
|
284
|
+
}
|
|
285
|
+
try {
|
|
286
|
+
const event = JSON.parse((0, import_node_fs.readFileSync)(eventPath, "utf8"));
|
|
287
|
+
return numberFromValue(event.pull_request?.number) ?? numberFromValue(event.number);
|
|
288
|
+
} catch {
|
|
289
|
+
return null;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
function getGitRepositoryMetadata() {
|
|
293
|
+
const remote = git(["remote", "get-url", "origin"]);
|
|
294
|
+
return remote ? parseGitRemoteUrl(remote) : { provider: null, fullName: null };
|
|
295
|
+
}
|
|
296
|
+
function parseGitRemoteUrl(remoteUrl) {
|
|
297
|
+
const remote = remoteUrl.trim();
|
|
298
|
+
const url = parseRemoteAsUrl(remote);
|
|
299
|
+
const host = url?.host ?? parseScpRemoteHost(remote);
|
|
300
|
+
const path = url?.pathname ?? parseScpRemotePath(remote);
|
|
301
|
+
const fullName = path?.replace(/^\/+/, "").replace(/\.git$/i, "").replace(/^v\d+\//i, "");
|
|
302
|
+
return {
|
|
303
|
+
provider: host ? providerFromHost(host) : null,
|
|
304
|
+
fullName: normalize(fullName)
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
function parseRemoteAsUrl(remote) {
|
|
308
|
+
try {
|
|
309
|
+
return new URL(remote.replace(/^git\+/, ""));
|
|
310
|
+
} catch {
|
|
311
|
+
return null;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
function parseScpRemoteHost(remote) {
|
|
315
|
+
return remote.match(/^(?:[^@]+@)?([^:]+):(.+)$/)?.[1] ?? null;
|
|
316
|
+
}
|
|
317
|
+
function parseScpRemotePath(remote) {
|
|
318
|
+
return remote.match(/^(?:[^@]+@)?([^:]+):(.+)$/)?.[2] ?? null;
|
|
319
|
+
}
|
|
320
|
+
function providerFromHost(host) {
|
|
321
|
+
const normalized = host.toLowerCase();
|
|
322
|
+
if (normalized.includes("github")) {
|
|
323
|
+
return "GitHub";
|
|
324
|
+
}
|
|
325
|
+
if (normalized.includes("gitlab")) {
|
|
326
|
+
return "GitLab";
|
|
327
|
+
}
|
|
328
|
+
if (normalized.includes("bitbucket")) {
|
|
329
|
+
return "Bitbucket";
|
|
330
|
+
}
|
|
331
|
+
if (normalized.includes("dev.azure") || normalized.includes("visualstudio")) {
|
|
332
|
+
return "AzureDevOps";
|
|
333
|
+
}
|
|
334
|
+
return null;
|
|
335
|
+
}
|
|
336
|
+
function branchFromGitRef(value) {
|
|
337
|
+
const ref = normalize(value);
|
|
338
|
+
if (!ref) {
|
|
339
|
+
return null;
|
|
340
|
+
}
|
|
341
|
+
return ref.match(/^refs\/heads\/(.+)$/)?.[1] ?? ref.match(/^refs\/tags\/(.+)$/)?.[1] ?? null;
|
|
342
|
+
}
|
|
343
|
+
function normalizeUrl(value) {
|
|
344
|
+
const normalized = normalize(value);
|
|
345
|
+
if (!normalized) {
|
|
346
|
+
return null;
|
|
347
|
+
}
|
|
348
|
+
if (/^https?:\/\//i.test(normalized)) {
|
|
349
|
+
return normalized;
|
|
350
|
+
}
|
|
351
|
+
return `https://${normalized}`;
|
|
352
|
+
}
|
|
353
|
+
function numberFromValue(value) {
|
|
354
|
+
if (typeof value === "number" && Number.isInteger(value) && value > 0) {
|
|
355
|
+
return value;
|
|
356
|
+
}
|
|
357
|
+
if (typeof value !== "string") {
|
|
358
|
+
return null;
|
|
359
|
+
}
|
|
360
|
+
if (value.toLowerCase() === "false") {
|
|
361
|
+
return null;
|
|
362
|
+
}
|
|
363
|
+
const parsed = Number(value);
|
|
364
|
+
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
|
|
365
|
+
}
|
|
366
|
+
function normalize(value) {
|
|
367
|
+
const trimmed = value?.trim();
|
|
368
|
+
return trimmed ? trimmed : null;
|
|
369
|
+
}
|
|
370
|
+
function git(args) {
|
|
371
|
+
try {
|
|
372
|
+
const safeDirectory = process.cwd().replace(/\\/g, "/");
|
|
373
|
+
return normalize(
|
|
374
|
+
(0, import_node_child_process.execFileSync)("git", ["-c", `safe.directory=${safeDirectory}`, ...args], {
|
|
375
|
+
encoding: "utf8",
|
|
376
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
377
|
+
})
|
|
378
|
+
);
|
|
379
|
+
} catch {
|
|
380
|
+
return null;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// src/run-ci.ts
|
|
385
|
+
async function runCi(options) {
|
|
386
|
+
applyOptionEnvironmentOverrides(options);
|
|
387
|
+
const config = resolveConfig({
|
|
388
|
+
apiKey: options.apiKey,
|
|
389
|
+
apiUrl: options.apiUrl,
|
|
390
|
+
timeout: options.timeout
|
|
391
|
+
});
|
|
392
|
+
const client = new TestMutantApiClient({
|
|
393
|
+
...config,
|
|
394
|
+
userAgent: options.userAgent
|
|
395
|
+
});
|
|
396
|
+
const createRunRequest = buildCreateRunRequest({
|
|
397
|
+
mode: options.mode,
|
|
398
|
+
repositoryProvider: options.provider,
|
|
399
|
+
repositoryFullName: options.repository,
|
|
400
|
+
baseUrl: options.baseUrl,
|
|
401
|
+
environmentName: options.environmentName
|
|
402
|
+
});
|
|
403
|
+
const created = await client.createRun(createRunRequest);
|
|
404
|
+
const completed = await client.completeRun(created.runId, {
|
|
405
|
+
status: "Passed",
|
|
406
|
+
summary: "CI metadata captured.",
|
|
407
|
+
results: {
|
|
408
|
+
kind: "advisory",
|
|
409
|
+
message: "TestMutant CLI vertical slice completed successfully.",
|
|
410
|
+
repositoryFullName: createRunRequest.repositoryFullName,
|
|
411
|
+
branch: createRunRequest.branch,
|
|
412
|
+
commitSha: createRunRequest.commitSha,
|
|
413
|
+
ciProvider: createRunRequest.ciProvider,
|
|
414
|
+
ciRunId: createRunRequest.ciRunId,
|
|
415
|
+
generatedAtUtc: (/* @__PURE__ */ new Date()).toISOString()
|
|
416
|
+
},
|
|
417
|
+
resultJson: null,
|
|
418
|
+
errorMessage: null
|
|
419
|
+
});
|
|
420
|
+
return {
|
|
421
|
+
runId: completed.runId,
|
|
422
|
+
status: completed.status
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
function applyOptionEnvironmentOverrides(options) {
|
|
426
|
+
if (options.apiKey) {
|
|
427
|
+
process.env[API_KEY_ENV_VAR] = options.apiKey;
|
|
428
|
+
}
|
|
429
|
+
if (options.apiUrl) {
|
|
430
|
+
process.env[API_URL_ENV_VAR] = options.apiUrl;
|
|
431
|
+
}
|
|
432
|
+
if (!process.env[API_URL_ENV_VAR]) {
|
|
433
|
+
process.env[API_URL_ENV_VAR] = DEFAULT_API_URL;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// src/index.ts
|
|
438
|
+
var import_commander = require("commander");
|
|
439
|
+
var packageInfo = readPackageInfo();
|
|
440
|
+
var program = new import_commander.Command();
|
|
441
|
+
program.name("testmutant").description("Run TestMutant workflows locally or in CI.").version(packageInfo.version).option("-k, --api-key <key>", `TestMutant API key. Defaults to ${API_KEY_ENV_VAR}.`).option(
|
|
442
|
+
"-u, --api-url <url>",
|
|
443
|
+
`TestMutant API base URL. Defaults to ${API_URL_ENV_VAR} or ${DEFAULT_API_URL}.`
|
|
444
|
+
).option("--timeout <ms>", "API request timeout in milliseconds.", "30000").option("--json", "Print command output as JSON.");
|
|
445
|
+
program.hook("preAction", async () => {
|
|
446
|
+
const options = program.opts();
|
|
447
|
+
if (options.json) {
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
await printUpdateReminder(packageInfo);
|
|
451
|
+
});
|
|
452
|
+
program.command("ping").description("Verify the CLI can authenticate with the TestMutant API.").action(async () => {
|
|
453
|
+
const options = program.opts();
|
|
454
|
+
const config = resolveConfig(options);
|
|
455
|
+
const client = new TestMutantApiClient({
|
|
456
|
+
...config,
|
|
457
|
+
userAgent: `testmutant-cli/${packageInfo.version}`
|
|
458
|
+
});
|
|
459
|
+
const ping = await client.ping();
|
|
460
|
+
if (options.json) {
|
|
461
|
+
console.log(JSON.stringify(ping, null, 2));
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
464
|
+
console.log("Connected to TestMutant.");
|
|
465
|
+
console.log(`Organization: ${ping.organizationName} (${ping.organizationId})`);
|
|
466
|
+
console.log(`CLI API version: ${ping.cliApiVersion}`);
|
|
467
|
+
});
|
|
468
|
+
program.command("ci").description("Create and complete a TestMutant CI run.").option("--mode <mode>", "Run mode.", "Advisory").option("--repository <repository>", "Repository full name override, e.g. owner/repo.").option("--provider <provider>", "Repository provider.", "GitHub").option("--base-url <url>", "Application base URL.").option("--environment <name>", "Environment name.").action(
|
|
469
|
+
async (commandOptions) => {
|
|
470
|
+
const options = program.opts();
|
|
471
|
+
const result = await runCi({
|
|
472
|
+
apiKey: options.apiKey,
|
|
473
|
+
apiUrl: options.apiUrl,
|
|
474
|
+
timeout: options.timeout,
|
|
475
|
+
mode: commandOptions.mode,
|
|
476
|
+
repository: commandOptions.repository,
|
|
477
|
+
provider: commandOptions.provider,
|
|
478
|
+
baseUrl: commandOptions.baseUrl,
|
|
479
|
+
environmentName: commandOptions.environment,
|
|
480
|
+
userAgent: `testmutant-cli/${packageInfo.version}`
|
|
481
|
+
});
|
|
482
|
+
if (options.json) {
|
|
483
|
+
console.log(JSON.stringify(result, null, 2));
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
486
|
+
console.log(`Run ID: ${result.runId}`);
|
|
487
|
+
console.log(`Status: ${result.status}`);
|
|
488
|
+
}
|
|
489
|
+
);
|
|
490
|
+
program.showHelpAfterError();
|
|
491
|
+
program.parseAsync(process.argv).catch((error) => {
|
|
492
|
+
if (error instanceof CliError) {
|
|
493
|
+
console.error(error.message);
|
|
494
|
+
process.exitCode = error.exitCode;
|
|
495
|
+
return;
|
|
496
|
+
}
|
|
497
|
+
if (error instanceof Error) {
|
|
498
|
+
console.error(error.message);
|
|
499
|
+
process.exitCode = 1;
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
console.error(String(error));
|
|
503
|
+
process.exitCode = 1;
|
|
504
|
+
});
|
|
505
|
+
function readPackageInfo() {
|
|
506
|
+
const packageJsonPath = (0, import_node_path.join)(__dirname, "..", "package.json");
|
|
507
|
+
const packageJson = JSON.parse((0, import_node_fs2.readFileSync)(packageJsonPath, "utf8"));
|
|
508
|
+
return {
|
|
509
|
+
name: typeof packageJson.name === "string" ? packageJson.name : "@testmutant/cli",
|
|
510
|
+
version: typeof packageJson.version === "string" ? packageJson.version : "0.0.0"
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
async function printUpdateReminder(packageInfo2) {
|
|
514
|
+
const latestVersion = await fetchLatestPackageVersion(packageInfo2.name);
|
|
515
|
+
if (!latestVersion || !isNewerVersion(latestVersion, packageInfo2.version)) {
|
|
516
|
+
return;
|
|
517
|
+
}
|
|
518
|
+
console.log(
|
|
519
|
+
`There is a newer TestMutant CLI version available (${packageInfo2.version} -> ${latestVersion}). Run npm install -g ${packageInfo2.name}@latest to update.`
|
|
520
|
+
);
|
|
521
|
+
console.log("");
|
|
522
|
+
}
|
|
523
|
+
async function fetchLatestPackageVersion(packageName) {
|
|
524
|
+
const controller = new AbortController();
|
|
525
|
+
const timeout = setTimeout(() => controller.abort(), 1e3);
|
|
526
|
+
try {
|
|
527
|
+
const response = await fetch(
|
|
528
|
+
`https://registry.npmjs.org/${encodeURIComponent(packageName)}/latest`,
|
|
529
|
+
{
|
|
530
|
+
headers: { accept: "application/json" },
|
|
531
|
+
signal: controller.signal
|
|
532
|
+
}
|
|
533
|
+
);
|
|
534
|
+
if (!response.ok) {
|
|
535
|
+
return null;
|
|
536
|
+
}
|
|
537
|
+
const body = await response.json();
|
|
538
|
+
return typeof body.version === "string" ? body.version : null;
|
|
539
|
+
} catch {
|
|
540
|
+
return null;
|
|
541
|
+
} finally {
|
|
542
|
+
clearTimeout(timeout);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
function isNewerVersion(candidate, current) {
|
|
546
|
+
const candidateVersion = parseSemver(candidate);
|
|
547
|
+
const currentVersion = parseSemver(current);
|
|
548
|
+
if (!candidateVersion || !currentVersion) {
|
|
549
|
+
return candidate !== current;
|
|
550
|
+
}
|
|
551
|
+
for (const key of ["major", "minor", "patch"]) {
|
|
552
|
+
if (candidateVersion[key] > currentVersion[key]) {
|
|
553
|
+
return true;
|
|
554
|
+
}
|
|
555
|
+
if (candidateVersion[key] < currentVersion[key]) {
|
|
556
|
+
return false;
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
if (!candidateVersion.prerelease && currentVersion.prerelease) {
|
|
560
|
+
return true;
|
|
561
|
+
}
|
|
562
|
+
if (candidateVersion.prerelease && !currentVersion.prerelease) {
|
|
563
|
+
return false;
|
|
564
|
+
}
|
|
565
|
+
return Boolean(candidateVersion.prerelease && currentVersion.prerelease) && candidateVersion.prerelease > currentVersion.prerelease;
|
|
566
|
+
}
|
|
567
|
+
function parseSemver(value) {
|
|
568
|
+
const match = value.trim().match(/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.+)?$/);
|
|
569
|
+
if (!match) {
|
|
570
|
+
return null;
|
|
571
|
+
}
|
|
572
|
+
return {
|
|
573
|
+
major: Number(match[1]),
|
|
574
|
+
minor: Number(match[2]),
|
|
575
|
+
patch: Number(match[3]),
|
|
576
|
+
prerelease: match[4] ?? ""
|
|
577
|
+
};
|
|
578
|
+
}
|
package/package.json
CHANGED
|
@@ -1,19 +1,55 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@testmutant/cli",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "1.0.0-alpha.4",
|
|
4
4
|
"description": "TestMutant CLI.",
|
|
5
5
|
"private": false,
|
|
6
|
+
"main": "dist/index.js",
|
|
6
7
|
"bin": {
|
|
7
|
-
"testmutant": "
|
|
8
|
+
"testmutant": "dist/index.js"
|
|
8
9
|
},
|
|
9
10
|
"scripts": {
|
|
10
|
-
"
|
|
11
|
+
"dev": "tsx src/index.ts",
|
|
12
|
+
"build": "tsup",
|
|
13
|
+
"typecheck": "tsc --noEmit",
|
|
14
|
+
"test": "node --import tsx --test tests/*.test.ts",
|
|
15
|
+
"check": "npm run typecheck && npm test && npm run build",
|
|
16
|
+
"check:dist": "git diff --exit-code -- dist",
|
|
17
|
+
"ci": "node dist/index.js ci",
|
|
18
|
+
"release:alpha": "npm version prerelease --preid alpha --no-git-tag-version && npm run check",
|
|
19
|
+
"release:stable": "npm version 1.0.0 --no-git-tag-version && npm run check",
|
|
20
|
+
"prepublishOnly": "npm run check"
|
|
21
|
+
},
|
|
22
|
+
"simple-git-hooks": {
|
|
23
|
+
"pre-push": "npm run typecheck && npm test && npm run build && git diff --exit-code -- dist"
|
|
24
|
+
},
|
|
25
|
+
"files": [
|
|
26
|
+
"dist"
|
|
27
|
+
],
|
|
28
|
+
"engines": {
|
|
29
|
+
"node": ">=20"
|
|
11
30
|
},
|
|
12
31
|
"keywords": [],
|
|
13
32
|
"author": "",
|
|
14
|
-
"license": "
|
|
33
|
+
"license": "MIT",
|
|
34
|
+
"repository": {
|
|
35
|
+
"type": "git",
|
|
36
|
+
"url": "git+https://github.com/TestMutant/cli.git"
|
|
37
|
+
},
|
|
15
38
|
"type": "commonjs",
|
|
16
39
|
"publishConfig": {
|
|
17
|
-
"access": "public"
|
|
40
|
+
"access": "public",
|
|
41
|
+
"registry": "https://registry.npmjs.org/",
|
|
42
|
+
"provenance": true
|
|
43
|
+
},
|
|
44
|
+
"dependencies": {
|
|
45
|
+
"commander": "^14.0.3",
|
|
46
|
+
"dotenv": "^17.4.2"
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"@types/node": "^25.9.1",
|
|
50
|
+
"simple-git-hooks": "^2.13.1",
|
|
51
|
+
"tsup": "^8.5.1",
|
|
52
|
+
"tsx": "^4.22.4",
|
|
53
|
+
"typescript": "^6.0.3"
|
|
18
54
|
}
|
|
19
55
|
}
|
package/src/index.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
console.log("TestMutant CLI placeholder.");
|