@qarmiqai/ci 0.0.0-stage → 0.1.1
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 +121 -2
- package/dist/args.d.ts +15 -0
- package/dist/args.js +69 -0
- package/dist/ci-environment.d.ts +8 -0
- package/dist/ci-environment.js +32 -0
- package/dist/cli.d.ts +9 -0
- package/dist/cli.js +75 -0
- package/dist/client.d.ts +16 -0
- package/dist/client.js +55 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/run.d.ts +18 -0
- package/dist/run.js +59 -0
- package/dist/types.d.ts +56 -0
- package/dist/types.js +17 -0
- package/package.json +41 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Qarmiq
|
|
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
CHANGED
|
@@ -1,3 +1,122 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @qarmiqai/ci
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Ask [Qarmiq](https://qarmiq.ai) to test from your CI pipeline, and act on its answer.
|
|
4
|
+
|
|
5
|
+
A Qarmiq **CI trigger** runs one collection of scenarios on one of your project's environments and answers:
|
|
6
|
+
|
|
7
|
+
| Verdict | Meaning | Exit code |
|
|
8
|
+
|---|---|---|
|
|
9
|
+
| `go` | every scenario passed | `0` |
|
|
10
|
+
| `stop` | a scenario failed | `1` |
|
|
11
|
+
| `review` | a scenario could not be decided, or the run did not finish in time; allowed, and a person should look | `0` (or `1` with `--on-review fail`) |
|
|
12
|
+
|
|
13
|
+
What happens next (merge, promote to production, notify) is your pipeline's decision. Qarmiq tests and reports; it never sees your code.
|
|
14
|
+
|
|
15
|
+
## Set up
|
|
16
|
+
|
|
17
|
+
1. In Qarmiq, open **Settings → CI** for your project and make a trigger: a collection, an environment, the device and browsers.
|
|
18
|
+
2. Copy the token it shows once, and add it to your CI's secrets as `QARMIQ_CI_TOKEN`.
|
|
19
|
+
3. Add one step after your deploy:
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
npx @qarmiqai/ci run --trigger <trigger id>
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
The step starts the trigger's run, waits for it, prints each scenario's result with a link to the run in Qarmiq, and exits by the verdict.
|
|
26
|
+
|
|
27
|
+
On **GitHub Actions**, **GitLab CI** and **Bitbucket Pipelines** the commit, branch, pull request and pipeline link are read from the CI's own variables. Anywhere else, pass them with `--sha`, `--ref` and the `--source-*` options.
|
|
28
|
+
|
|
29
|
+
### GitHub Actions
|
|
30
|
+
|
|
31
|
+
Use the action. It does what the CLI does, and also reports a **check** on the commit (neutral, not red, for `review`), keeps **one comment** on the pull request up to date, writes the job summary, and sets the outputs `verdict`, `run-url` and `run-key`.
|
|
32
|
+
|
|
33
|
+
```yaml
|
|
34
|
+
jobs:
|
|
35
|
+
qarmiq:
|
|
36
|
+
runs-on: ubuntu-latest
|
|
37
|
+
needs: deploy-staging
|
|
38
|
+
permissions:
|
|
39
|
+
contents: read
|
|
40
|
+
checks: write # the check on the commit
|
|
41
|
+
pull-requests: write # the comment on the pull request
|
|
42
|
+
steps:
|
|
43
|
+
- uses: qarmiqai/ci/github-action@v1
|
|
44
|
+
with:
|
|
45
|
+
token: ${{ secrets.QARMIQ_CI_TOKEN }}
|
|
46
|
+
trigger: <trigger id>
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
| Input | Default | |
|
|
50
|
+
|---|---|---|
|
|
51
|
+
| `token` | | The trigger's token, from a secret. Required. |
|
|
52
|
+
| `trigger` | | The trigger's id. Required. |
|
|
53
|
+
| `qarmiq-url` | `https://app.qarmiq.ai` | The Qarmiq origin. |
|
|
54
|
+
| `environment` | the trigger's | Another of the project's saved environments. |
|
|
55
|
+
| `rerun` | `false` | A fresh run even if this commit was already started. |
|
|
56
|
+
| `on-review` | `neutral` | `fail` to fail the job on `review`. |
|
|
57
|
+
| `comment` | `true` | `false` for no pull request comment. |
|
|
58
|
+
| `check-name` | `Qarmiq` | The check's name, e.g. for a required status check. |
|
|
59
|
+
|
|
60
|
+
On a pull request, the commit tested and reported on is the one the author pushed, not the merge commit GitHub makes. Without `checks: write` or `pull-requests: write` the action says so in a warning and carries on; the verdict still decides the step. To gate a merge on it, mark the check as required in branch protection.
|
|
61
|
+
|
|
62
|
+
The action is a thin layer over this package, bundled in `github-action/dist`, so there is nothing to install.
|
|
63
|
+
|
|
64
|
+
### GitLab CI
|
|
65
|
+
|
|
66
|
+
```yaml
|
|
67
|
+
qarmiq:
|
|
68
|
+
stage: test
|
|
69
|
+
image: node:22
|
|
70
|
+
script:
|
|
71
|
+
- npx @qarmiqai/ci run --trigger <trigger id>
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
with `QARMIQ_CI_TOKEN` as a masked CI/CD variable.
|
|
75
|
+
|
|
76
|
+
## Options
|
|
77
|
+
|
|
78
|
+
```
|
|
79
|
+
qarmiq-ci run --trigger <id> [options]
|
|
80
|
+
|
|
81
|
+
--environment <name> test another of the project's saved environments than the trigger's own
|
|
82
|
+
--sha <commit> the commit being tested (read from the CI when it can be)
|
|
83
|
+
--ref <branch> the branch or tag (read from the CI when it can be)
|
|
84
|
+
--rerun start a fresh run even if this commit was already started
|
|
85
|
+
--on-review allow|fail what "review" does to the exit code; allow by default
|
|
86
|
+
--wait <seconds> how long each status read is held open; 25 by default
|
|
87
|
+
--source-repo <repo> --source-pr <n> --source-url <url> --source-provider <name> --source-actor <who>
|
|
88
|
+
|
|
89
|
+
QARMIQ_CI_TOKEN the trigger's token (required)
|
|
90
|
+
QARMIQ_URL the Qarmiq origin (default https://app.qarmiq.ai)
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Exit code `2` means the step could not run: a missing token, bad options, or a refusal from Qarmiq, printed with its reason (for example a project's monthly limit of CI runs, with when to try again).
|
|
94
|
+
|
|
95
|
+
## Behaviour worth knowing
|
|
96
|
+
|
|
97
|
+
- **The same commit is not tested twice.** Starting a trigger again for a commit it already started, on the same environment, answers with that run. Pass `--rerun` for a fresh one.
|
|
98
|
+
- **A newer push replaces an older one.** Starting a trigger for a branch that already has a run in flight cancels the older run.
|
|
99
|
+
- **Cancelling the job cancels the run.** When the CI job is stopped, the run in Qarmiq is cancelled too.
|
|
100
|
+
- **A run never waits for ever.** Each trigger has its own maximum wait; a run still going past it is ended and answers `review`.
|
|
101
|
+
|
|
102
|
+
## Use it as a library
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
import { QarmiqCiClient, runTrigger, exitCodeFor } from "@qarmiqai/ci";
|
|
106
|
+
|
|
107
|
+
const client = new QarmiqCiClient({ baseUrl: "https://app.qarmiq.ai", token: process.env.QARMIQ_CI_TOKEN! });
|
|
108
|
+
const { status } = await runTrigger(client, { triggerId: "<trigger id>", request: { sha, ref } });
|
|
109
|
+
process.exit(exitCodeFor(status));
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
## The HTTP contract
|
|
113
|
+
|
|
114
|
+
Three calls, all with `Authorization: Bearer <token>`:
|
|
115
|
+
|
|
116
|
+
- `POST /api/ci/triggers/{trigger}/runs` with `{ sha?, ref?, environment?, rerun?, source? }` starts a run and answers its `status_url`.
|
|
117
|
+
- `GET /api/ci/runs/{run}?wait=<seconds>` answers its state, verdict and scenarios, held open while it runs.
|
|
118
|
+
- `DELETE /api/ci/runs/{run}` cancels it.
|
|
119
|
+
|
|
120
|
+
## License
|
|
121
|
+
|
|
122
|
+
MIT
|
package/dist/args.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { RunSource } from "./types.js";
|
|
2
|
+
export declare const USAGE = "usage: qarmiq-ci run --trigger <id> [options]\n\noptions:\n --environment <name> test another of the project's saved environments than the trigger's own\n --sha <commit> the commit being tested (read from the CI when it can be)\n --ref <branch> the branch or tag (read from the CI when it can be)\n --rerun start a fresh run even if this commit was already started\n --on-review allow|fail what \"review\" (undecided) does to the exit code; allow by default\n --wait <seconds> how long each status read is held open; 25 by default\n --source-repo <repo> --source-pr <n> --source-url <url> --source-provider <name> --source-actor <who>\n\nenvironment:\n QARMIQ_CI_TOKEN the trigger's token (required)\n QARMIQ_URL the Qarmiq origin (default https://app.qarmiq.ai)\n\nexit: 0 go (and review, unless --on-review fail), 1 stop or no verdict, 2 could not run";
|
|
3
|
+
export interface CliArgs {
|
|
4
|
+
trigger: string;
|
|
5
|
+
environment?: string;
|
|
6
|
+
sha?: string;
|
|
7
|
+
ref?: string;
|
|
8
|
+
rerun: boolean;
|
|
9
|
+
onReview: "allow" | "fail";
|
|
10
|
+
wait: number;
|
|
11
|
+
source: RunSource;
|
|
12
|
+
}
|
|
13
|
+
export declare function parseArgs(argv: readonly string[]): CliArgs | {
|
|
14
|
+
error: string;
|
|
15
|
+
};
|
package/dist/args.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
export const USAGE = `usage: qarmiq-ci run --trigger <id> [options]
|
|
2
|
+
|
|
3
|
+
options:
|
|
4
|
+
--environment <name> test another of the project's saved environments than the trigger's own
|
|
5
|
+
--sha <commit> the commit being tested (read from the CI when it can be)
|
|
6
|
+
--ref <branch> the branch or tag (read from the CI when it can be)
|
|
7
|
+
--rerun start a fresh run even if this commit was already started
|
|
8
|
+
--on-review allow|fail what "review" (undecided) does to the exit code; allow by default
|
|
9
|
+
--wait <seconds> how long each status read is held open; 25 by default
|
|
10
|
+
--source-repo <repo> --source-pr <n> --source-url <url> --source-provider <name> --source-actor <who>
|
|
11
|
+
|
|
12
|
+
environment:
|
|
13
|
+
QARMIQ_CI_TOKEN the trigger's token (required)
|
|
14
|
+
QARMIQ_URL the Qarmiq origin (default https://app.qarmiq.ai)
|
|
15
|
+
|
|
16
|
+
exit: 0 go (and review, unless --on-review fail), 1 stop or no verdict, 2 could not run`;
|
|
17
|
+
const SOURCE_FLAGS = {
|
|
18
|
+
"--source-provider": "provider",
|
|
19
|
+
"--source-repo": "repo",
|
|
20
|
+
"--source-pr": "pr",
|
|
21
|
+
"--source-url": "url",
|
|
22
|
+
"--source-actor": "actor",
|
|
23
|
+
};
|
|
24
|
+
export function parseArgs(argv) {
|
|
25
|
+
const [command, ...rest] = argv;
|
|
26
|
+
if (command !== "run")
|
|
27
|
+
return { error: USAGE };
|
|
28
|
+
let trigger;
|
|
29
|
+
const parsed = { rerun: false, onReview: "allow", wait: 25, source: {} };
|
|
30
|
+
for (let i = 0; i < rest.length; i++) {
|
|
31
|
+
const flag = rest[i];
|
|
32
|
+
if (flag === "--rerun") {
|
|
33
|
+
parsed.rerun = true;
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
if (flag === "--help" || flag === "-h")
|
|
37
|
+
return { error: USAGE };
|
|
38
|
+
const value = rest[i + 1];
|
|
39
|
+
if (value === undefined || value.startsWith("--"))
|
|
40
|
+
return { error: `${flag} needs a value\n\n${USAGE}` };
|
|
41
|
+
i += 1;
|
|
42
|
+
if (flag === "--trigger")
|
|
43
|
+
trigger = value;
|
|
44
|
+
else if (flag === "--environment")
|
|
45
|
+
parsed.environment = value;
|
|
46
|
+
else if (flag === "--sha")
|
|
47
|
+
parsed.sha = value;
|
|
48
|
+
else if (flag === "--ref")
|
|
49
|
+
parsed.ref = value;
|
|
50
|
+
else if (flag === "--on-review") {
|
|
51
|
+
if (value !== "allow" && value !== "fail")
|
|
52
|
+
return { error: `--on-review is allow or fail, not "${value}"` };
|
|
53
|
+
parsed.onReview = value;
|
|
54
|
+
}
|
|
55
|
+
else if (flag === "--wait") {
|
|
56
|
+
const seconds = Number(value);
|
|
57
|
+
if (!Number.isInteger(seconds) || seconds < 0)
|
|
58
|
+
return { error: `--wait is a whole number of seconds, not "${value}"` };
|
|
59
|
+
parsed.wait = seconds;
|
|
60
|
+
}
|
|
61
|
+
else if (SOURCE_FLAGS[flag])
|
|
62
|
+
parsed.source[SOURCE_FLAGS[flag]] = value;
|
|
63
|
+
else
|
|
64
|
+
return { error: `unknown option ${flag}\n\n${USAGE}` };
|
|
65
|
+
}
|
|
66
|
+
if (!trigger)
|
|
67
|
+
return { error: `--trigger is required\n\n${USAGE}` };
|
|
68
|
+
return { trigger, ...parsed };
|
|
69
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { RunSource } from "./types.js";
|
|
2
|
+
export interface DetectedBuild {
|
|
3
|
+
sha?: string;
|
|
4
|
+
ref?: string;
|
|
5
|
+
source: RunSource;
|
|
6
|
+
}
|
|
7
|
+
export declare function detectBuild(env: Record<string, string | undefined>): DetectedBuild;
|
|
8
|
+
export declare function compact<T extends object>(value: T): T;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export function detectBuild(env) {
|
|
2
|
+
if (env.GITHUB_ACTIONS === "true") {
|
|
3
|
+
const pr = env.GITHUB_REF?.match(/^refs\/pull\/(\d+)\//)?.[1];
|
|
4
|
+
const url = env.GITHUB_SERVER_URL && env.GITHUB_REPOSITORY && env.GITHUB_RUN_ID ? `${env.GITHUB_SERVER_URL}/${env.GITHUB_REPOSITORY}/actions/runs/${env.GITHUB_RUN_ID}` : undefined;
|
|
5
|
+
return {
|
|
6
|
+
sha: env.GITHUB_SHA,
|
|
7
|
+
// On a pull request GITHUB_REF_NAME is "<n>/merge"; the branch the change lives on is GITHUB_HEAD_REF.
|
|
8
|
+
ref: env.GITHUB_HEAD_REF || env.GITHUB_REF_NAME,
|
|
9
|
+
source: compact({ provider: "github", repo: env.GITHUB_REPOSITORY, pr, url, actor: env.GITHUB_ACTOR }),
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
if (env.GITLAB_CI === "true") {
|
|
13
|
+
return {
|
|
14
|
+
sha: env.CI_COMMIT_SHA,
|
|
15
|
+
ref: env.CI_MERGE_REQUEST_SOURCE_BRANCH_NAME || env.CI_COMMIT_REF_NAME,
|
|
16
|
+
source: compact({ provider: "gitlab", repo: env.CI_PROJECT_PATH, pr: env.CI_MERGE_REQUEST_IID, url: env.CI_JOB_URL, actor: env.GITLAB_USER_LOGIN }),
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
if (env.BITBUCKET_BUILD_NUMBER) {
|
|
20
|
+
const url = env.BITBUCKET_GIT_HTTP_ORIGIN && env.BITBUCKET_BUILD_NUMBER ? `${env.BITBUCKET_GIT_HTTP_ORIGIN}/pipelines/results/${env.BITBUCKET_BUILD_NUMBER}` : undefined;
|
|
21
|
+
return {
|
|
22
|
+
sha: env.BITBUCKET_COMMIT,
|
|
23
|
+
ref: env.BITBUCKET_BRANCH,
|
|
24
|
+
source: compact({ provider: "bitbucket", repo: env.BITBUCKET_REPO_FULL_NAME, pr: env.BITBUCKET_PR_ID, url }),
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
return { source: {} };
|
|
28
|
+
}
|
|
29
|
+
// Drops absent and empty fields, so what is sent is only what is known.
|
|
30
|
+
export function compact(value) {
|
|
31
|
+
return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined && v !== ""));
|
|
32
|
+
}
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
export interface CliIo {
|
|
3
|
+
out: (line: string) => void;
|
|
4
|
+
err: (line: string) => void;
|
|
5
|
+
fetch?: typeof fetch;
|
|
6
|
+
signal?: AbortSignal;
|
|
7
|
+
sleep?: (ms: number) => Promise<void>;
|
|
8
|
+
}
|
|
9
|
+
export declare function main(argv: readonly string[], env: Record<string, string | undefined>, io: CliIo): Promise<number>;
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { realpathSync } from "node:fs";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { parseArgs } from "./args.js";
|
|
5
|
+
import { compact, detectBuild } from "./ci-environment.js";
|
|
6
|
+
import { QarmiqCiClient } from "./client.js";
|
|
7
|
+
import { describeStatus, exitCodeFor, runTrigger } from "./run.js";
|
|
8
|
+
import { QarmiqRefusal } from "./types.js";
|
|
9
|
+
const DEFAULT_URL = "https://app.qarmiq.ai";
|
|
10
|
+
// `qarmiq-ci run --trigger <id>`: start the trigger's run, wait for it, print the verdict, exit by it. Everything the CI already knows
|
|
11
|
+
// (commit, branch, where the pipeline run lives) is read from its environment when not given, so the common call is the trigger alone.
|
|
12
|
+
export async function main(argv, env, io) {
|
|
13
|
+
const args = parseArgs(argv);
|
|
14
|
+
if ("error" in args) {
|
|
15
|
+
io.err(args.error);
|
|
16
|
+
return 2;
|
|
17
|
+
}
|
|
18
|
+
const token = env.QARMIQ_CI_TOKEN;
|
|
19
|
+
if (!token) {
|
|
20
|
+
io.err("QARMIQ_CI_TOKEN is not set: add the trigger's token to your CI's secrets and expose it to this step.");
|
|
21
|
+
return 2;
|
|
22
|
+
}
|
|
23
|
+
const detected = detectBuild(env);
|
|
24
|
+
const request = compact({
|
|
25
|
+
environment: args.environment,
|
|
26
|
+
sha: args.sha ?? detected.sha,
|
|
27
|
+
ref: args.ref ?? detected.ref,
|
|
28
|
+
rerun: args.rerun || undefined,
|
|
29
|
+
source: compact({ ...detected.source, ...args.source }),
|
|
30
|
+
});
|
|
31
|
+
const client = new QarmiqCiClient({ baseUrl: env.QARMIQ_URL || DEFAULT_URL, token, fetch: io.fetch });
|
|
32
|
+
try {
|
|
33
|
+
const { status } = await runTrigger(client, {
|
|
34
|
+
triggerId: args.trigger,
|
|
35
|
+
request,
|
|
36
|
+
waitSeconds: args.wait,
|
|
37
|
+
signal: io.signal,
|
|
38
|
+
sleep: io.sleep,
|
|
39
|
+
onStart: (started) => io.out(`${started.deduplicated ? "Already started for this commit" : "Started"} ${started.run.key}: ${started.run.url}`),
|
|
40
|
+
});
|
|
41
|
+
io.out(describeStatus(status));
|
|
42
|
+
if (status.verdict === "review" && args.onReview === "allow")
|
|
43
|
+
io.out("Qarmiq could not decide every scenario; a person should look.");
|
|
44
|
+
return exitCodeFor(status, args.onReview);
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
if (error instanceof QarmiqRefusal) {
|
|
48
|
+
const retry = error.retryAfterSeconds ? ` Try again in ${error.retryAfterSeconds} s.` : "";
|
|
49
|
+
io.err(`Qarmiq refused (${error.code}): ${error.message}${retry}`);
|
|
50
|
+
return 2;
|
|
51
|
+
}
|
|
52
|
+
io.err(`Could not reach Qarmiq: ${error instanceof Error ? error.message : String(error)}`);
|
|
53
|
+
return 2;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
// Run as a program (the bin), not when imported by tests or the GitHub action.
|
|
57
|
+
function invokedDirectly() {
|
|
58
|
+
const entry = process.argv[1];
|
|
59
|
+
if (!entry)
|
|
60
|
+
return false;
|
|
61
|
+
try {
|
|
62
|
+
return realpathSync(entry) === realpathSync(fileURLToPath(import.meta.url));
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
// The entry path cannot be resolved (it was deleted, or is not a file): this module is not the program.
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
if (invokedDirectly()) {
|
|
70
|
+
const controller = new AbortController();
|
|
71
|
+
// A cancelled CI job sends SIGTERM (or SIGINT locally): stop waiting and cancel the run on Qarmiq, then exit by what it answers.
|
|
72
|
+
process.once("SIGTERM", () => controller.abort());
|
|
73
|
+
process.once("SIGINT", () => controller.abort());
|
|
74
|
+
main(process.argv.slice(2), process.env, { out: (l) => console.log(l), err: (l) => console.error(l), signal: controller.signal }).then((code) => process.exit(code));
|
|
75
|
+
}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type RunStatus, type StartRequest, type StartResponse } from "./types.js";
|
|
2
|
+
export interface ClientOptions {
|
|
3
|
+
baseUrl: string;
|
|
4
|
+
token: string;
|
|
5
|
+
fetch?: typeof fetch;
|
|
6
|
+
}
|
|
7
|
+
export declare class QarmiqCiClient {
|
|
8
|
+
private readonly baseUrl;
|
|
9
|
+
private readonly token;
|
|
10
|
+
private readonly fetchImpl;
|
|
11
|
+
constructor(options: ClientOptions);
|
|
12
|
+
start(triggerId: string, request?: StartRequest): Promise<StartResponse>;
|
|
13
|
+
status(runId: string, waitSeconds?: number): Promise<RunStatus>;
|
|
14
|
+
cancel(runId: string): Promise<RunStatus>;
|
|
15
|
+
private call;
|
|
16
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { QarmiqRefusal } from "./types.js";
|
|
2
|
+
// The three calls. A failure the server explains becomes a QarmiqRefusal with the server's own code and words; anything else (a
|
|
3
|
+
// network error) is thrown as it is, so the pipeline's log shows what happened.
|
|
4
|
+
export class QarmiqCiClient {
|
|
5
|
+
baseUrl;
|
|
6
|
+
token;
|
|
7
|
+
fetchImpl;
|
|
8
|
+
constructor(options) {
|
|
9
|
+
this.baseUrl = options.baseUrl.replace(/\/+$/, "");
|
|
10
|
+
this.token = options.token;
|
|
11
|
+
this.fetchImpl = options.fetch ?? fetch;
|
|
12
|
+
}
|
|
13
|
+
async start(triggerId, request = {}) {
|
|
14
|
+
const url = `${this.baseUrl}/api/ci/triggers/${encodeURIComponent(triggerId)}/runs`;
|
|
15
|
+
return (await this.call(url, { method: "POST", body: JSON.stringify(request) }));
|
|
16
|
+
}
|
|
17
|
+
// One read, held open on the server for up to `waitSeconds` while the run is still in flight.
|
|
18
|
+
async status(runId, waitSeconds = 0) {
|
|
19
|
+
const url = new URL(`${this.baseUrl}/api/ci/runs/${encodeURIComponent(runId)}`);
|
|
20
|
+
if (waitSeconds > 0)
|
|
21
|
+
url.searchParams.set("wait", String(Math.floor(waitSeconds)));
|
|
22
|
+
return (await this.call(url.toString(), { method: "GET" }));
|
|
23
|
+
}
|
|
24
|
+
async cancel(runId) {
|
|
25
|
+
const url = `${this.baseUrl}/api/ci/runs/${encodeURIComponent(runId)}`;
|
|
26
|
+
return (await this.call(url, { method: "DELETE" }));
|
|
27
|
+
}
|
|
28
|
+
async call(url, init) {
|
|
29
|
+
const headers = new Headers({ authorization: `Bearer ${this.token}`, accept: "application/json" });
|
|
30
|
+
if (init.body !== undefined)
|
|
31
|
+
headers.set("content-type", "application/json");
|
|
32
|
+
const response = await this.fetchImpl(url, { ...init, headers });
|
|
33
|
+
const text = await response.text();
|
|
34
|
+
let body = null;
|
|
35
|
+
if (text) {
|
|
36
|
+
try {
|
|
37
|
+
body = JSON.parse(text);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
// Not JSON: the refusal below carries the status the server answered.
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
if (response.ok)
|
|
44
|
+
return body;
|
|
45
|
+
const explained = (body ?? {});
|
|
46
|
+
const fallbackCode = response.status === 401 ? "unauthorized" : response.status === 404 ? "not_found" : `http_${response.status}`;
|
|
47
|
+
// A refusal with a code answers { error: code, message }; a plain one answers { error: message }.
|
|
48
|
+
const hasCode = typeof explained.message === "string";
|
|
49
|
+
const code = hasCode && typeof explained.error === "string" ? explained.error : fallbackCode;
|
|
50
|
+
const message = hasCode ? explained.message : typeof explained.error === "string" ? explained.error : `Qarmiq answered ${response.status}`;
|
|
51
|
+
const header = Number(response.headers.get("retry-after"));
|
|
52
|
+
const retryAfter = typeof explained.retry_after === "number" ? explained.retry_after : Number.isFinite(header) && header > 0 ? header : null;
|
|
53
|
+
throw new QarmiqRefusal(response.status, code, message, retryAfter);
|
|
54
|
+
}
|
|
55
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { QarmiqCiClient, type ClientOptions } from "./client.js";
|
|
2
|
+
export { describeStatus, exitCodeFor, runTrigger, type RunOptions, type RunOutcome } from "./run.js";
|
|
3
|
+
export { compact, detectBuild, type DetectedBuild } from "./ci-environment.js";
|
|
4
|
+
export { ACTIVE_STATES, QarmiqRefusal, type CiRunState, type CiVerdict, type RunRef, type RunSource, type RunStatus, type ScenarioVerdict, type StartRequest, type StartResponse, } from "./types.js";
|
package/dist/index.js
ADDED
package/dist/run.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { QarmiqCiClient } from "./client.js";
|
|
2
|
+
import { type RunStatus, type StartRequest, type StartResponse } from "./types.js";
|
|
3
|
+
export interface RunOptions {
|
|
4
|
+
triggerId: string;
|
|
5
|
+
request?: StartRequest;
|
|
6
|
+
waitSeconds?: number;
|
|
7
|
+
onStart?: (started: StartResponse) => void | Promise<void>;
|
|
8
|
+
onStatus?: (status: RunStatus) => void | Promise<void>;
|
|
9
|
+
signal?: AbortSignal;
|
|
10
|
+
sleep?: (ms: number) => Promise<void>;
|
|
11
|
+
}
|
|
12
|
+
export interface RunOutcome {
|
|
13
|
+
started: StartResponse;
|
|
14
|
+
status: RunStatus;
|
|
15
|
+
}
|
|
16
|
+
export declare function runTrigger(client: QarmiqCiClient, options: RunOptions): Promise<RunOutcome>;
|
|
17
|
+
export declare function exitCodeFor(status: RunStatus, onReview?: "allow" | "fail"): 0 | 1;
|
|
18
|
+
export declare function describeStatus(status: RunStatus): string;
|
package/dist/run.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { ACTIVE_STATES, QarmiqRefusal } from "./types.js";
|
|
2
|
+
// How many status reads in a row may fail before the wait is given up. A pipeline that lost one poll should not lose the verdict.
|
|
3
|
+
const MAX_READ_FAILURES = 5;
|
|
4
|
+
// Starts the trigger's run and waits until it is over: the one sequence every CI does. Nothing here decides pass or fail; the verdict is
|
|
5
|
+
// Qarmiq's, read back as the server wrote it.
|
|
6
|
+
export async function runTrigger(client, options) {
|
|
7
|
+
const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
8
|
+
const started = await client.start(options.triggerId, options.request ?? {});
|
|
9
|
+
await options.onStart?.(started);
|
|
10
|
+
const waitSeconds = options.waitSeconds ?? 25;
|
|
11
|
+
let failures = 0;
|
|
12
|
+
for (;;) {
|
|
13
|
+
if (options.signal?.aborted) {
|
|
14
|
+
const status = await client.cancel(started.run.id);
|
|
15
|
+
await options.onStatus?.(status);
|
|
16
|
+
return { started, status };
|
|
17
|
+
}
|
|
18
|
+
let status;
|
|
19
|
+
try {
|
|
20
|
+
status = await client.status(started.run.id, waitSeconds);
|
|
21
|
+
failures = 0;
|
|
22
|
+
}
|
|
23
|
+
catch (error) {
|
|
24
|
+
// A refusal the server explained (a revoked token, a run it does not know) will not change by asking again.
|
|
25
|
+
if (error instanceof QarmiqRefusal && error.status !== 429 && error.status < 500)
|
|
26
|
+
throw error;
|
|
27
|
+
failures += 1;
|
|
28
|
+
if (failures >= MAX_READ_FAILURES)
|
|
29
|
+
throw error;
|
|
30
|
+
const retryAfter = error instanceof QarmiqRefusal && error.retryAfterSeconds ? error.retryAfterSeconds * 1000 : 0;
|
|
31
|
+
await sleep(Math.max(retryAfter, Math.min(30_000, 2_000 * 2 ** (failures - 1))));
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
await options.onStatus?.(status);
|
|
35
|
+
if (!ACTIVE_STATES.has(status.state))
|
|
36
|
+
return { started, status };
|
|
37
|
+
// The server held the read open already; with no wait asked for, a short pause keeps this from becoming a tight loop.
|
|
38
|
+
if (waitSeconds <= 0)
|
|
39
|
+
await sleep(2_000);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
// What a pipeline does with the verdict. "review" is Qarmiq's "allowed, a person should look": a success with a warning, unless the
|
|
43
|
+
// pipeline asked for it to fail.
|
|
44
|
+
export function exitCodeFor(status, onReview = "allow") {
|
|
45
|
+
if (status.verdict === "go")
|
|
46
|
+
return 0;
|
|
47
|
+
if (status.verdict === "review")
|
|
48
|
+
return onReview === "fail" ? 1 : 0;
|
|
49
|
+
// stop, or a run that ended with no verdict (cancelled, superseded): never a pass.
|
|
50
|
+
return 1;
|
|
51
|
+
}
|
|
52
|
+
// The verdict and its scenarios in a few plain lines, for a pipeline's log.
|
|
53
|
+
export function describeStatus(status) {
|
|
54
|
+
const head = status.verdict ? `${status.verdict}: ${status.reason ?? ""}`.trim() : `${status.state}${status.reason ? `: ${status.reason}` : ""}`;
|
|
55
|
+
// A scenario with no verdict is still pending while the run goes on; once the run is over, it ended without a result.
|
|
56
|
+
const none = ACTIVE_STATES.has(status.state) ? "pending" : "no result";
|
|
57
|
+
const lines = status.scenarios.map((s) => ` ${(s.verdict ?? none).padEnd(12)} ${s.ref} ${s.statement}`);
|
|
58
|
+
return [head, ...lines, `Run: ${status.run.url}`].join("\n");
|
|
59
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
export type CiVerdict = "go" | "stop" | "review";
|
|
2
|
+
export type CiRunState = "queued" | "running" | "finished" | "cancelled" | "timed_out" | "superseded";
|
|
3
|
+
export type ScenarioVerdict = "passed" | "failed" | "inconclusive" | null;
|
|
4
|
+
export interface RunSource {
|
|
5
|
+
provider?: string;
|
|
6
|
+
repo?: string;
|
|
7
|
+
pr?: string;
|
|
8
|
+
url?: string;
|
|
9
|
+
actor?: string;
|
|
10
|
+
}
|
|
11
|
+
export interface StartRequest {
|
|
12
|
+
environment?: string;
|
|
13
|
+
ref?: string;
|
|
14
|
+
sha?: string;
|
|
15
|
+
rerun?: boolean;
|
|
16
|
+
source?: RunSource;
|
|
17
|
+
}
|
|
18
|
+
export interface RunRef {
|
|
19
|
+
id: string;
|
|
20
|
+
key: string;
|
|
21
|
+
url: string;
|
|
22
|
+
}
|
|
23
|
+
export interface StartResponse {
|
|
24
|
+
run: RunRef;
|
|
25
|
+
status_url: string;
|
|
26
|
+
state: CiRunState;
|
|
27
|
+
deduplicated: boolean;
|
|
28
|
+
}
|
|
29
|
+
export interface RunStatus {
|
|
30
|
+
state: CiRunState;
|
|
31
|
+
verdict: CiVerdict | null;
|
|
32
|
+
reason: string | null;
|
|
33
|
+
summary: {
|
|
34
|
+
scenarios: number;
|
|
35
|
+
passed: number;
|
|
36
|
+
failed: number;
|
|
37
|
+
inconclusive: number;
|
|
38
|
+
pending: number;
|
|
39
|
+
};
|
|
40
|
+
scenarios: Array<{
|
|
41
|
+
id: string;
|
|
42
|
+
ref: string;
|
|
43
|
+
statement: string;
|
|
44
|
+
verdict: ScenarioVerdict;
|
|
45
|
+
}>;
|
|
46
|
+
run: RunRef;
|
|
47
|
+
started_at: string;
|
|
48
|
+
finished_at: string | null;
|
|
49
|
+
}
|
|
50
|
+
export declare class QarmiqRefusal extends Error {
|
|
51
|
+
readonly status: number;
|
|
52
|
+
readonly code: string;
|
|
53
|
+
readonly retryAfterSeconds: number | null;
|
|
54
|
+
constructor(status: number, code: string, message: string, retryAfterSeconds: number | null);
|
|
55
|
+
}
|
|
56
|
+
export declare const ACTIVE_STATES: ReadonlySet<CiRunState>;
|
package/dist/types.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// The wire contract of Qarmiq's CI endpoints, as the server answers them. This package knows Qarmiq only through these three calls,
|
|
2
|
+
// the way any pipeline would: one trigger token, no other credential, no other surface.
|
|
3
|
+
// A refusal the server explained: the status it answered, its code (rate_limited, concurrency, monthly_cap, empty_collection, ...),
|
|
4
|
+
// its message in plain words, and when to try again if it said.
|
|
5
|
+
export class QarmiqRefusal extends Error {
|
|
6
|
+
status;
|
|
7
|
+
code;
|
|
8
|
+
retryAfterSeconds;
|
|
9
|
+
constructor(status, code, message, retryAfterSeconds) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.status = status;
|
|
12
|
+
this.code = code;
|
|
13
|
+
this.retryAfterSeconds = retryAfterSeconds;
|
|
14
|
+
this.name = "QarmiqRefusal";
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export const ACTIVE_STATES = new Set(["queued", "running"]);
|
package/package.json
CHANGED
|
@@ -1,6 +1,43 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@qarmiqai/ci",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Ask Qarmiq to test from any CI: start a trigger's run, wait for its verdict, and exit by go, stop or review.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "https://github.com/qarmiqai/ci.git"
|
|
9
|
+
},
|
|
10
|
+
"type": "module",
|
|
11
|
+
"engines": {
|
|
12
|
+
"node": ">=20"
|
|
13
|
+
},
|
|
14
|
+
"main": "./dist/index.js",
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"exports": {
|
|
17
|
+
".": {
|
|
18
|
+
"types": "./dist/index.d.ts",
|
|
19
|
+
"import": "./dist/index.js"
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"bin": {
|
|
23
|
+
"qarmiq-ci": "./dist/cli.js"
|
|
24
|
+
},
|
|
25
|
+
"files": [
|
|
26
|
+
"dist",
|
|
27
|
+
"README.md",
|
|
28
|
+
"LICENSE"
|
|
29
|
+
],
|
|
30
|
+
"scripts": {
|
|
31
|
+
"build": "tsc -p tsconfig.json",
|
|
32
|
+
"build:action": "esbuild github-action/src/index.ts --bundle --platform=node --target=node22 --format=esm --outfile=github-action/dist/index.js --legal-comments=none",
|
|
33
|
+
"typecheck": "tsc -p tsconfig.action.json",
|
|
34
|
+
"test": "vitest run",
|
|
35
|
+
"prepack": "npm run build"
|
|
36
|
+
},
|
|
37
|
+
"devDependencies": {
|
|
38
|
+
"@types/node": "^22.10.0",
|
|
39
|
+
"esbuild": "^0.25.12",
|
|
40
|
+
"typescript": "^5.7.0",
|
|
41
|
+
"vitest": "^4.1.11"
|
|
42
|
+
}
|
|
43
|
+
}
|