@testmutant/cli 0.0.2 → 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/dist/index.js CHANGED
@@ -1,61 +1,578 @@
1
1
  #!/usr/bin/env node
2
+ #!/usr/bin/env node
2
3
  "use strict";
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- require("dotenv/config");
5
- const node_fs_1 = require("node:fs");
6
- const node_path_1 = require("node:path");
7
- const commander_1 = require("commander");
8
- const api_client_1 = require("./api-client");
9
- const config_1 = require("./config");
10
- const packageInfo = readPackageInfo();
11
- const program = new commander_1.Command();
12
- program
13
- .name("testmutant")
14
- .description("Run TestMutant workflows locally or in CI.")
15
- .version(packageInfo.version)
16
- .option("-k, --api-key <key>", `TestMutant API key. Defaults to ${config_1.API_KEY_ENV_VAR}.`)
17
- .option("-u, --api-url <url>", `TestMutant API base URL. Defaults to ${config_1.API_URL_ENV_VAR} or ${config_1.DEFAULT_API_URL}.`)
18
- .option("--timeout <ms>", "API request timeout in milliseconds.", "30000")
19
- .option("--json", "Print command output as JSON.");
20
- program
21
- .command("ping")
22
- .description("Verify the CLI can authenticate with the TestMutant API.")
23
- .action(async () => {
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) => {
24
470
  const options = program.opts();
25
- const config = (0, config_1.resolveConfig)(options);
26
- const client = new api_client_1.TestMutantApiClient({
27
- ...config,
28
- userAgent: `testmutant-cli/${packageInfo.version}`,
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}`
29
481
  });
30
- const ping = await client.ping();
31
482
  if (options.json) {
32
- console.log(JSON.stringify(ping, null, 2));
33
- return;
483
+ console.log(JSON.stringify(result, null, 2));
484
+ return;
34
485
  }
35
- console.log("Connected to TestMutant.");
36
- console.log(`Organization: ${ping.organizationName} (${ping.organizationId})`);
37
- console.log(`CLI API version: ${ping.cliApiVersion}`);
38
- });
486
+ console.log(`Run ID: ${result.runId}`);
487
+ console.log(`Status: ${result.status}`);
488
+ }
489
+ );
39
490
  program.showHelpAfterError();
40
491
  program.parseAsync(process.argv).catch((error) => {
41
- if (error instanceof config_1.CliError) {
42
- console.error(error.message);
43
- process.exitCode = error.exitCode;
44
- return;
45
- }
46
- if (error instanceof Error) {
47
- console.error(error.message);
48
- process.exitCode = 1;
49
- return;
50
- }
51
- console.error(String(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);
52
499
  process.exitCode = 1;
500
+ return;
501
+ }
502
+ console.error(String(error));
503
+ process.exitCode = 1;
53
504
  });
54
505
  function readPackageInfo() {
55
- const packageJsonPath = (0, node_path_1.join)(__dirname, "..", "package.json");
56
- const packageJson = JSON.parse((0, node_fs_1.readFileSync)(packageJsonPath, "utf8"));
57
- return {
58
- version: typeof packageJson.version === "string" ? packageJson.version : "0.0.0",
59
- };
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
+ };
60
578
  }
61
- //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@testmutant/cli",
3
- "version": "0.0.2",
3
+ "version": "1.0.0-alpha.4",
4
4
  "description": "TestMutant CLI.",
5
5
  "private": false,
6
6
  "main": "dist/index.js",
@@ -8,10 +8,19 @@
8
8
  "testmutant": "dist/index.js"
9
9
  },
10
10
  "scripts": {
11
- "build": "tsc -p tsconfig.json",
12
- "dev": "npm run build && node dist/index.js",
13
- "prepack": "npm run build",
14
- "test": "npm run build"
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"
15
24
  },
16
25
  "files": [
17
26
  "dist"
@@ -38,6 +47,9 @@
38
47
  },
39
48
  "devDependencies": {
40
49
  "@types/node": "^25.9.1",
50
+ "simple-git-hooks": "^2.13.1",
51
+ "tsup": "^8.5.1",
52
+ "tsx": "^4.22.4",
41
53
  "typescript": "^6.0.3"
42
54
  }
43
55
  }
@@ -1,15 +0,0 @@
1
- import type { operations } from "./generated/api";
2
- export type PingResponse = operations["CliV1_Ping"]["responses"][200]["content"]["application/json"];
3
- export type TestMutantApiClientOptions = {
4
- apiKey: string;
5
- apiUrl: string;
6
- timeoutMs: number;
7
- userAgent: string;
8
- };
9
- export declare class TestMutantApiClient {
10
- private readonly options;
11
- constructor(options: TestMutantApiClientOptions);
12
- ping(): Promise<PingResponse>;
13
- private getJson;
14
- private request;
15
- }