@testsprite/testsprite-cli 0.6.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +52 -31
- package/dist/commands/agent.js +91 -45
- package/dist/commands/ci.d.ts +88 -0
- package/dist/commands/ci.js +429 -0
- package/dist/commands/doctor.d.ts +1 -1
- package/dist/commands/doctor.js +104 -8
- package/dist/commands/init.js +8 -0
- package/dist/commands/project.d.ts +78 -0
- package/dist/commands/project.js +429 -5
- package/dist/commands/schedule.d.ts +120 -0
- package/dist/commands/schedule.js +487 -0
- package/dist/commands/test.d.ts +176 -2
- package/dist/commands/test.js +2235 -609
- package/dist/commands/testlist.d.ts +88 -0
- package/dist/commands/testlist.js +753 -0
- package/dist/commands/tunnel.d.ts +72 -0
- package/dist/commands/tunnel.js +367 -0
- package/dist/index.js +113 -40
- package/dist/lib/agent-targets.d.ts +13 -4
- package/dist/lib/agent-targets.js +11 -2
- package/dist/lib/conflict-reason.d.ts +30 -0
- package/dist/lib/conflict-reason.js +45 -0
- package/dist/lib/credentials.js +42 -1
- package/dist/lib/cron.d.ts +40 -0
- package/dist/lib/cron.js +190 -0
- package/dist/lib/dry-run/samples.d.ts +9 -0
- package/dist/lib/dry-run/samples.js +293 -55
- package/dist/lib/errors.d.ts +9 -0
- package/dist/lib/errors.js +11 -0
- package/dist/lib/gh-output.d.ts +33 -1
- package/dist/lib/gh-output.js +97 -27
- package/dist/lib/http.d.ts +119 -0
- package/dist/lib/http.js +243 -2
- package/dist/lib/interrupt.d.ts +38 -13
- package/dist/lib/interrupt.js +130 -15
- package/dist/lib/junit-report.d.ts +20 -2
- package/dist/lib/junit-report.js +38 -5
- package/dist/lib/local-target.d.ts +95 -0
- package/dist/lib/local-target.js +184 -0
- package/dist/lib/plan-poll.d.ts +171 -0
- package/dist/lib/plan-poll.js +442 -0
- package/dist/lib/plans.types.d.ts +130 -0
- package/dist/lib/plans.types.js +31 -0
- package/dist/lib/poll-support.d.ts +26 -0
- package/dist/lib/poll-support.js +65 -0
- package/dist/lib/poll.d.ts +1 -0
- package/dist/lib/poll.js +2 -40
- package/dist/lib/proxy.d.ts +16 -0
- package/dist/lib/proxy.js +19 -1
- package/dist/lib/response-schemas.d.ts +20 -0
- package/dist/lib/response-schemas.js +55 -1
- package/dist/lib/run-progress.d.ts +41 -0
- package/dist/lib/run-progress.js +56 -0
- package/dist/lib/runs.types.d.ts +32 -3
- package/dist/lib/secret-file.d.ts +15 -0
- package/dist/lib/secret-file.js +82 -0
- package/dist/lib/target-url-preflight.d.ts +91 -0
- package/dist/lib/target-url-preflight.js +259 -0
- package/dist/lib/target-url.d.ts +63 -9
- package/dist/lib/target-url.js +283 -62
- package/dist/lib/telemetry.d.ts +11 -0
- package/dist/lib/telemetry.js +1 -0
- package/dist/lib/testlist.types.d.ts +77 -0
- package/dist/lib/testlist.types.js +9 -0
- package/dist/lib/ticker.d.ts +8 -0
- package/dist/lib/ticker.js +3 -0
- package/dist/lib/tunnel-session.d.ts +129 -0
- package/dist/lib/tunnel-session.js +232 -0
- package/dist/lib/tunnel.types.d.ts +54 -0
- package/dist/lib/tunnel.types.js +8 -0
- package/dist/lib/v3-advisory.d.ts +35 -22
- package/dist/lib/v3-advisory.js +44 -24
- package/dist/lib/wait-exit.d.ts +29 -0
- package/dist/lib/wait-exit.js +103 -0
- package/dist/vendor/tunnel-client/client.d.ts +83 -0
- package/dist/vendor/tunnel-client/client.js +871 -0
- package/dist/vendor/tunnel-client/config.d.ts +41 -0
- package/dist/vendor/tunnel-client/config.js +42 -0
- package/dist/vendor/tunnel-client/index.d.ts +9 -0
- package/dist/vendor/tunnel-client/index.js +9 -0
- package/dist/vendor/tunnel-client/lodash-lite.d.ts +14 -0
- package/dist/vendor/tunnel-client/lodash-lite.js +24 -0
- package/dist/vendor/tunnel-client/protocol.d.ts +60 -0
- package/dist/vendor/tunnel-client/protocol.js +143 -0
- package/dist/vendor/tunnel-client/types.d.ts +96 -0
- package/dist/vendor/tunnel-client/types.js +10 -0
- package/dist/vendor/tunnel-client/ws-compat.d.ts +206 -0
- package/dist/vendor/tunnel-client/ws-compat.js +316 -0
- package/dist/version-guard.d.ts +10 -7
- package/dist/version-guard.js +37 -9
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +2 -1
- package/skills/testsprite-onboard.skill.md +60 -4
- package/skills/testsprite-verify.codex.md +22 -16
- package/skills/testsprite-verify.skill.md +27 -18
|
@@ -0,0 +1,429 @@
|
|
|
1
|
+
import { promises as nodeFs } from 'node:fs';
|
|
2
|
+
import { spawnSync as nodeSpawnSync } from 'node:child_process';
|
|
3
|
+
import * as path from 'node:path';
|
|
4
|
+
import { Command } from 'commander';
|
|
5
|
+
import { makeHttpClient, parseRequestTimeoutFlag, } from '../lib/client-factory.js';
|
|
6
|
+
import { CLIError, localValidationError } from '../lib/errors.js';
|
|
7
|
+
import { loadConfig } from '../lib/config.js';
|
|
8
|
+
import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
|
|
9
|
+
import { assertNotLocal } from '../lib/target-url.js';
|
|
10
|
+
import { VERSION } from '../version.js';
|
|
11
|
+
// ── constants ────────────────────────────────────────────────────────────────
|
|
12
|
+
/** Platforms `ci init` can scaffold. One today; the positional arg leaves room. */
|
|
13
|
+
const SUPPORTED_PLATFORMS = ['github'];
|
|
14
|
+
/** Default location a GitHub Actions workflow must live to be picked up. */
|
|
15
|
+
const DEFAULT_WORKFLOW_PATH = '.github/workflows/testsprite.yml';
|
|
16
|
+
/** Default terminal-verdict wait, matching the CLI's own `test run` default. */
|
|
17
|
+
const DEFAULT_TIMEOUT_SECONDS = 600;
|
|
18
|
+
/** The repo secret the generated workflow reads the API key from. */
|
|
19
|
+
const API_KEY_SECRET_NAME = 'TESTSPRITE_API_KEY';
|
|
20
|
+
/** The published composite action the workflow delegates to, pinned to a tag. */
|
|
21
|
+
const ACTION_REF = 'TestSprite/testsprite-action@v1';
|
|
22
|
+
/** The CLI's built-in production endpoint (mirrors `config.ts`). Used to decide
|
|
23
|
+
* whether the generated workflow needs an explicit `endpoint-url`. */
|
|
24
|
+
const DEFAULT_API_URL = 'https://api.testsprite.com';
|
|
25
|
+
const defaultCiFs = {
|
|
26
|
+
// `target`/`dir` are the workflow output path (default `.github/workflows/testsprite.yml`,
|
|
27
|
+
// or the caller's `--path`), resolved from cwd — a scaffold target the user is writing into
|
|
28
|
+
// their own repo, never external/network input. Same risk profile as agent-install scaffolding.
|
|
29
|
+
writeFile: (target, data, opts) =>
|
|
30
|
+
// eslint-disable-next-line security/detect-non-literal-fs-filename -- see above: caller-supplied scaffold output path, not external input.
|
|
31
|
+
nodeFs.writeFile(target, data, { encoding: 'utf8', flag: opts?.exclusive ? 'wx' : 'w' }),
|
|
32
|
+
mkdir: async (dir) => {
|
|
33
|
+
// eslint-disable-next-line security/detect-non-literal-fs-filename -- parent dir of the scaffold output path (above).
|
|
34
|
+
await nodeFs.mkdir(dir, { recursive: true });
|
|
35
|
+
},
|
|
36
|
+
// eslint-disable-next-line security/detect-non-literal-fs-filename -- reads back the scaffold output path for the --force backup, same path as writeFile.
|
|
37
|
+
readFile: target => nodeFs.readFile(target, 'utf8'),
|
|
38
|
+
};
|
|
39
|
+
const defaultSpawn = (cmd, args, opts) => nodeSpawnSync(cmd, args, {
|
|
40
|
+
input: opts.input,
|
|
41
|
+
cwd: opts.cwd,
|
|
42
|
+
encoding: 'utf8',
|
|
43
|
+
shell: false,
|
|
44
|
+
windowsHide: true,
|
|
45
|
+
});
|
|
46
|
+
// ── helpers ──────────────────────────────────────────────────────────────────
|
|
47
|
+
function resolveCommonOptions(command) {
|
|
48
|
+
const g = command.optsWithGlobals();
|
|
49
|
+
return {
|
|
50
|
+
profile: g.profile ?? 'default',
|
|
51
|
+
output: resolveOutputMode(g.output),
|
|
52
|
+
endpointUrl: g.endpointUrl,
|
|
53
|
+
debug: g.debug ?? false,
|
|
54
|
+
verbose: g.verbose ?? false,
|
|
55
|
+
dryRun: g.dryRun ?? false,
|
|
56
|
+
requestTimeoutMs: parseRequestTimeoutFlag(g.requestTimeout),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
function makeClient(opts, deps) {
|
|
60
|
+
return makeHttpClient(opts, {
|
|
61
|
+
env: deps.env,
|
|
62
|
+
credentialsPath: deps.credentialsPath,
|
|
63
|
+
fetchImpl: deps.fetchImpl,
|
|
64
|
+
stderr: deps.stderr,
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
export function parseTimeoutSeconds(raw) {
|
|
68
|
+
if (raw === undefined)
|
|
69
|
+
return DEFAULT_TIMEOUT_SECONDS;
|
|
70
|
+
const n = Number(raw);
|
|
71
|
+
if (!Number.isInteger(n) || n < 1 || n > 3600) {
|
|
72
|
+
throw localValidationError('timeout', 'must be an integer between 1 and 3600 seconds');
|
|
73
|
+
}
|
|
74
|
+
return n;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Reject a value that will be interpolated into a double-quoted YAML scalar in
|
|
78
|
+
* the generated workflow. `"` breaks the scalar, a newline breaks the mapping,
|
|
79
|
+
* and `` ` ``/`$` (which also covers `${{ … }}`, evaluated by Actions before the
|
|
80
|
+
* job runs) or `\` could change what the workflow does. A filter is a substring
|
|
81
|
+
* of a test name and a project id/URL never needs any of these, so refusing is
|
|
82
|
+
* safe and keeps the scaffold from ever emitting a workflow GitHub can't parse.
|
|
83
|
+
*/
|
|
84
|
+
function assertSafeWorkflowValue(field, value) {
|
|
85
|
+
if (/[\r\n"`$\\]/.test(value)) {
|
|
86
|
+
throw localValidationError(field, 'must not contain quotes, backticks, $, backslashes, or newlines', undefined, 'field');
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* The endpoint the workflow should pin, or undefined for the default production
|
|
91
|
+
* host. Resolved the SAME way the CLI resolves it at runtime (`loadConfig`:
|
|
92
|
+
* flag > TESTSPRITE_API_URL > credentials file > built-in default), so a caller
|
|
93
|
+
* whose profile points at a non-prod backend gets a workflow that targets the
|
|
94
|
+
* same backend their `ci init` just auto-detected the project from — instead of
|
|
95
|
+
* silently emitting a prod workflow that 404s in CI.
|
|
96
|
+
*/
|
|
97
|
+
function resolveEndpointUrl(opts, deps) {
|
|
98
|
+
const { apiUrl } = loadConfig({
|
|
99
|
+
profile: opts.profile,
|
|
100
|
+
endpointUrl: opts.endpointUrl,
|
|
101
|
+
env: deps.env,
|
|
102
|
+
credentialsPath: deps.credentialsPath,
|
|
103
|
+
});
|
|
104
|
+
const strip = (u) => u.replace(/\/+$/, '');
|
|
105
|
+
return strip(apiUrl) === strip(DEFAULT_API_URL) ? undefined : apiUrl;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* The repo's default branch, so the `push` trigger fires there and not on every
|
|
109
|
+
* feature-branch push (each run costs credits). Best-effort via `git`; falls
|
|
110
|
+
* back to `main` on any failure (not a git repo yet, no `origin`, git absent).
|
|
111
|
+
*/
|
|
112
|
+
function detectDefaultBranch(cwd, spawn) {
|
|
113
|
+
try {
|
|
114
|
+
const res = spawn('git', ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'], { cwd });
|
|
115
|
+
if (!res.error && res.status === 0) {
|
|
116
|
+
const ref = (res.stdout ?? '').trim().replace(/^origin\//, '');
|
|
117
|
+
if (ref && !/[\r\n"`$\\[\]]/.test(ref))
|
|
118
|
+
return ref;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
/* fall through to the default */
|
|
123
|
+
}
|
|
124
|
+
return 'main';
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Build the GitHub Actions workflow. It delegates to the published
|
|
128
|
+
* `TestSprite/testsprite-action` (design A) rather than inlining the CLI, so the
|
|
129
|
+
* partial-run guard (`allow-partial: false` by default), the JUnit upload, the
|
|
130
|
+
* annotations, and the CLI-version pin all come from one maintained place.
|
|
131
|
+
*/
|
|
132
|
+
export function buildGithubWorkflow(input) {
|
|
133
|
+
assertSafeWorkflowValue('project', input.projectId);
|
|
134
|
+
if (input.filter)
|
|
135
|
+
assertSafeWorkflowValue('filter', input.filter);
|
|
136
|
+
if (input.endpointUrl)
|
|
137
|
+
assertSafeWorkflowValue('endpoint-url', input.endpointUrl);
|
|
138
|
+
const withLines = [
|
|
139
|
+
` api-key: \${{ secrets.${API_KEY_SECRET_NAME} }}`,
|
|
140
|
+
` project: "${input.projectId}"`,
|
|
141
|
+
` cli-version: "${input.cliVersion}"`,
|
|
142
|
+
` timeout: "${input.timeoutSeconds}"`,
|
|
143
|
+
...(input.filter ? [` filter: "${input.filter}"`] : []),
|
|
144
|
+
...(input.endpointUrl ? [` endpoint-url: "${input.endpointUrl}"`] : []),
|
|
145
|
+
];
|
|
146
|
+
return `# Generated by \`testsprite ci init github\`. Gates this repo on TestSprite tests.
|
|
147
|
+
# The run, the JUnit report, the annotations, and the skipped-test guard all live
|
|
148
|
+
# in ${ACTION_REF}; regenerate with \`testsprite ci init github --force\`.
|
|
149
|
+
# Note: tests run against the project's CONFIGURED environment, not this PR's code
|
|
150
|
+
# (there is no checkout) — a green check means the tests passed, not that the diff is safe.
|
|
151
|
+
name: TestSprite
|
|
152
|
+
|
|
153
|
+
on:
|
|
154
|
+
push:
|
|
155
|
+
branches: ["${input.defaultBranch}"]
|
|
156
|
+
pull_request:
|
|
157
|
+
|
|
158
|
+
# The job only needs to read the checkout metadata.
|
|
159
|
+
permissions:
|
|
160
|
+
contents: read
|
|
161
|
+
|
|
162
|
+
jobs:
|
|
163
|
+
testsprite:
|
|
164
|
+
runs-on: ubuntu-latest
|
|
165
|
+
# Fork PRs run without repository secrets, so the API key would be empty and
|
|
166
|
+
# this check permanently red. Skip forks (a maintainer's push still runs it).
|
|
167
|
+
if: \${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }}
|
|
168
|
+
steps:
|
|
169
|
+
- uses: ${ACTION_REF}
|
|
170
|
+
with:
|
|
171
|
+
${withLines.join('\n')}
|
|
172
|
+
`;
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Resolve the project id the workflow pins. An explicit `--project` always wins.
|
|
176
|
+
* Otherwise, list the caller's projects: exactly one ⇒ use it; zero ⇒ ask them to
|
|
177
|
+
* create one; more than one ⇒ ask them to pass `--project` (never guess). Under
|
|
178
|
+
* `--dry-run` we make no network call — a preview uses a placeholder id.
|
|
179
|
+
*/
|
|
180
|
+
async function resolveProjectId(opts, deps) {
|
|
181
|
+
if (opts.project)
|
|
182
|
+
return opts.project;
|
|
183
|
+
if (opts.dryRun)
|
|
184
|
+
return '<your-project-id>';
|
|
185
|
+
const client = makeClient(opts, deps);
|
|
186
|
+
// pageSize=2 is enough to distinguish none / exactly-one / more-than-one
|
|
187
|
+
// without paginating: a full page (or a nextToken) means "more than one".
|
|
188
|
+
const page = await client.get('/projects?pageSize=2');
|
|
189
|
+
const items = page.items ?? [];
|
|
190
|
+
const only = items[0];
|
|
191
|
+
if (!only) {
|
|
192
|
+
throw localValidationError('project', 'no projects found for this API key — create one (testsprite project create) or pass --project <id>');
|
|
193
|
+
}
|
|
194
|
+
if (items.length > 1 || page.nextToken) {
|
|
195
|
+
throw localValidationError('project', 'multiple projects found — pass --project <id> to pick one (list them with: testsprite project list)');
|
|
196
|
+
}
|
|
197
|
+
return only.id;
|
|
198
|
+
}
|
|
199
|
+
/** Walk `<path>.bak`, `.bak.1`, … until a free slot; write the prior content there. */
|
|
200
|
+
async function backupExisting(fs, target, prior) {
|
|
201
|
+
for (let i = 0; i < 100; i++) {
|
|
202
|
+
const candidate = i === 0 ? `${target}.bak` : `${target}.bak.${i}`;
|
|
203
|
+
try {
|
|
204
|
+
await fs.writeFile(candidate, prior, { exclusive: true });
|
|
205
|
+
return candidate;
|
|
206
|
+
}
|
|
207
|
+
catch (err) {
|
|
208
|
+
if (err.code === 'EEXIST')
|
|
209
|
+
continue;
|
|
210
|
+
throw err;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
throw new CLIError('Could not find a free .bak slot to back up the existing workflow.', 1);
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Optionally set the repo secret via `gh` (soft dependency — never fails the
|
|
217
|
+
* scaffold). Reads the API key from the resolved profile/env and passes it on
|
|
218
|
+
* STDIN (not argv, so it can't leak via the process list). Absent/unauthed `gh`,
|
|
219
|
+
* or a missing key, degrades to the printed instruction. Runs in `cwd` so `gh`
|
|
220
|
+
* infers the right repo when `--repo` is omitted.
|
|
221
|
+
*/
|
|
222
|
+
function trySetSecret(opts, deps, cwd) {
|
|
223
|
+
const spawn = deps.spawn ?? defaultSpawn;
|
|
224
|
+
const { apiKey } = loadConfig({
|
|
225
|
+
profile: opts.profile,
|
|
226
|
+
endpointUrl: opts.endpointUrl,
|
|
227
|
+
env: deps.env,
|
|
228
|
+
credentialsPath: deps.credentialsPath,
|
|
229
|
+
});
|
|
230
|
+
if (!apiKey) {
|
|
231
|
+
return { attempted: true, set: false, reason: 'no API key resolved from profile or env' };
|
|
232
|
+
}
|
|
233
|
+
const args = ['secret', 'set', API_KEY_SECRET_NAME];
|
|
234
|
+
if (opts.repo)
|
|
235
|
+
args.push('--repo', opts.repo);
|
|
236
|
+
let result;
|
|
237
|
+
try {
|
|
238
|
+
result = spawn('gh', args, { input: apiKey, cwd });
|
|
239
|
+
}
|
|
240
|
+
catch (err) {
|
|
241
|
+
return { attempted: true, set: false, reason: `failed to run gh: ${err.message}` };
|
|
242
|
+
}
|
|
243
|
+
if (result.error) {
|
|
244
|
+
const code = result.error.code;
|
|
245
|
+
const reason = code === 'ENOENT' ? 'gh CLI not found on PATH' : `gh failed: ${result.error.message}`;
|
|
246
|
+
return { attempted: true, set: false, reason };
|
|
247
|
+
}
|
|
248
|
+
if (result.status !== 0) {
|
|
249
|
+
// gh's stderr can be multi-line and echo back input; keep only the first
|
|
250
|
+
// line so a stray token can never sprawl into the JSON `reason`.
|
|
251
|
+
const stderr = (result.stderr ?? '').split('\n')[0]?.trim() ?? '';
|
|
252
|
+
return {
|
|
253
|
+
attempted: true,
|
|
254
|
+
set: false,
|
|
255
|
+
reason: `gh exited ${result.status}${stderr ? `: ${stderr}` : ''} (is gh authenticated?)`,
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
return { attempted: true, set: true, reason: null };
|
|
259
|
+
}
|
|
260
|
+
// ── orchestrator ─────────────────────────────────────────────────────────────
|
|
261
|
+
export async function runCiInit(opts, deps = {}) {
|
|
262
|
+
const stdout = deps.stdout ?? ((line) => process.stdout.write(`${line}\n`));
|
|
263
|
+
const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
|
|
264
|
+
const fs = deps.fs ?? defaultCiFs;
|
|
265
|
+
const spawn = deps.spawn ?? defaultSpawn;
|
|
266
|
+
const cwd = deps.cwd ?? process.cwd();
|
|
267
|
+
const out = new Output(opts.output, { stdout, stderr });
|
|
268
|
+
if (!SUPPORTED_PLATFORMS.includes(opts.platform)) {
|
|
269
|
+
throw localValidationError('platform', `unsupported "${opts.platform}" — supported: ${SUPPORTED_PLATFORMS.join(', ')}`, undefined, 'field');
|
|
270
|
+
}
|
|
271
|
+
const platform = opts.platform;
|
|
272
|
+
// Validate the caller's own inputs up front — BEFORE the project-list round
|
|
273
|
+
// trip — so a bad --filter/--project fails fast without a wasted request.
|
|
274
|
+
if (opts.filter)
|
|
275
|
+
assertSafeWorkflowValue('filter', opts.filter);
|
|
276
|
+
if (opts.project)
|
|
277
|
+
assertSafeWorkflowValue('project', opts.project);
|
|
278
|
+
const projectId = await resolveProjectId(opts, deps);
|
|
279
|
+
const endpointUrl = resolveEndpointUrl(opts, deps);
|
|
280
|
+
const defaultBranch = detectDefaultBranch(cwd, spawn);
|
|
281
|
+
const workflow = buildGithubWorkflow({
|
|
282
|
+
projectId,
|
|
283
|
+
filter: opts.filter,
|
|
284
|
+
timeoutSeconds: opts.timeoutSeconds,
|
|
285
|
+
endpointUrl,
|
|
286
|
+
cliVersion: VERSION,
|
|
287
|
+
defaultBranch,
|
|
288
|
+
});
|
|
289
|
+
const relPath = opts.workflowPath;
|
|
290
|
+
const absPath = path.isAbsolute(relPath) ? relPath : path.join(cwd, relPath);
|
|
291
|
+
// A loopback / private endpoint pinned into a committed workflow is
|
|
292
|
+
// unreachable from a GitHub-hosted runner (the check reds on first push with
|
|
293
|
+
// nothing explaining why). Reuse `assertNotLocal`'s classifier to WARN — not
|
|
294
|
+
// error, since a self-hosted runner legitimately reaches such hosts.
|
|
295
|
+
let endpointWarning = null;
|
|
296
|
+
if (endpointUrl) {
|
|
297
|
+
try {
|
|
298
|
+
assertNotLocal(endpointUrl);
|
|
299
|
+
}
|
|
300
|
+
catch {
|
|
301
|
+
endpointWarning = `the workflow pins ${endpointUrl}, which a GitHub-hosted runner cannot reach — pass --endpoint-url <public-url>, or run this workflow on a self-hosted runner.`;
|
|
302
|
+
stderr(`[warn] ${endpointWarning}`);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
const baseSummary = {
|
|
306
|
+
platform,
|
|
307
|
+
path: relPath,
|
|
308
|
+
action: ACTION_REF,
|
|
309
|
+
projectId,
|
|
310
|
+
filter: opts.filter ?? null,
|
|
311
|
+
endpointUrl: endpointUrl ?? null,
|
|
312
|
+
endpointWarning,
|
|
313
|
+
timeoutSeconds: opts.timeoutSeconds,
|
|
314
|
+
};
|
|
315
|
+
// --dry-run: preview to stderr, emit the summary, and make no writes / no gh call.
|
|
316
|
+
if (opts.dryRun) {
|
|
317
|
+
stderr('[dry-run] would write the workflow below — no files changed, no secret set:');
|
|
318
|
+
stderr('');
|
|
319
|
+
for (const line of workflow.split('\n'))
|
|
320
|
+
stderr(` ${line}`);
|
|
321
|
+
const summary = {
|
|
322
|
+
...baseSummary,
|
|
323
|
+
wrote: false,
|
|
324
|
+
status: 'preview',
|
|
325
|
+
backupPath: null,
|
|
326
|
+
secret: { name: API_KEY_SECRET_NAME, attempted: false, set: false, reason: null },
|
|
327
|
+
};
|
|
328
|
+
out.print(summary, d => renderCiInitText(d));
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
await fs.mkdir(path.dirname(absPath));
|
|
332
|
+
let backupPath = null;
|
|
333
|
+
let wrote = true;
|
|
334
|
+
try {
|
|
335
|
+
await fs.writeFile(absPath, workflow, { exclusive: true });
|
|
336
|
+
}
|
|
337
|
+
catch (err) {
|
|
338
|
+
const code = err.code;
|
|
339
|
+
if (code === 'EISDIR') {
|
|
340
|
+
throw localValidationError('path', `${relPath} is a directory, not a file — pass --path <file> to a writable location`, undefined, 'field');
|
|
341
|
+
}
|
|
342
|
+
if (code !== 'EEXIST')
|
|
343
|
+
throw err;
|
|
344
|
+
const prior = await fs.readFile(absPath);
|
|
345
|
+
if (prior === workflow) {
|
|
346
|
+
// Already exactly what we'd write — no rewrite, no `.bak` churn. This also
|
|
347
|
+
// makes re-running (with or without --force) on identical content a no-op
|
|
348
|
+
// rather than an error, so it never burns a backup slot.
|
|
349
|
+
wrote = false;
|
|
350
|
+
}
|
|
351
|
+
else if (!opts.force) {
|
|
352
|
+
throw localValidationError('path', `${relPath} already exists — re-run with --force to overwrite (a .bak backup is kept)`, undefined, 'field');
|
|
353
|
+
}
|
|
354
|
+
else {
|
|
355
|
+
backupPath = await backupExisting(fs, absPath, prior);
|
|
356
|
+
await fs.writeFile(absPath, workflow, { exclusive: false });
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
const secret = opts.setSecret
|
|
360
|
+
? trySetSecret(opts, deps, cwd)
|
|
361
|
+
: { attempted: false, set: false, reason: null };
|
|
362
|
+
if (opts.setSecret && !secret.set) {
|
|
363
|
+
stderr(`[warn] could not set the ${API_KEY_SECRET_NAME} secret (${secret.reason}).`);
|
|
364
|
+
}
|
|
365
|
+
const summary = {
|
|
366
|
+
...baseSummary,
|
|
367
|
+
wrote,
|
|
368
|
+
status: wrote ? 'written' : 'unchanged',
|
|
369
|
+
backupPath: backupPath ? path.relative(cwd, backupPath) : null,
|
|
370
|
+
secret: { name: API_KEY_SECRET_NAME, ...secret },
|
|
371
|
+
};
|
|
372
|
+
out.print(summary, d => renderCiInitText(d));
|
|
373
|
+
}
|
|
374
|
+
// ── text rendering ───────────────────────────────────────────────────────────
|
|
375
|
+
export function renderCiInitText(s) {
|
|
376
|
+
const lines = [];
|
|
377
|
+
const verb = s.status === 'written'
|
|
378
|
+
? `Wrote ${s.path}`
|
|
379
|
+
: s.status === 'preview'
|
|
380
|
+
? `Would write ${s.path}`
|
|
381
|
+
: `${s.path} is already up to date`;
|
|
382
|
+
lines.push(`${verb} (${s.action}, project ${s.projectId}).`);
|
|
383
|
+
if (s.backupPath)
|
|
384
|
+
lines.push(`Backed up the previous file to ${s.backupPath}.`);
|
|
385
|
+
lines.push('');
|
|
386
|
+
lines.push('Next steps:');
|
|
387
|
+
if (s.secret.set) {
|
|
388
|
+
lines.push(` ✓ ${s.secret.name} repo secret set via gh.`);
|
|
389
|
+
lines.push(` → Commit and push ${s.path}, then open a PR to see the check.`);
|
|
390
|
+
}
|
|
391
|
+
else {
|
|
392
|
+
lines.push(` 1. Add the ${s.secret.name} repo secret (the workflow reads the key from it):`);
|
|
393
|
+
lines.push(` gh secret set ${s.secret.name} # paste your key when prompted`);
|
|
394
|
+
lines.push(' …or in the GitHub UI: Settings → Secrets and variables → Actions.');
|
|
395
|
+
lines.push(` 2. Commit and push ${s.path}, then open a PR to see the check.`);
|
|
396
|
+
}
|
|
397
|
+
return lines.join('\n');
|
|
398
|
+
}
|
|
399
|
+
// ── command builder ──────────────────────────────────────────────────────────
|
|
400
|
+
export function createCiCommand(deps = {}) {
|
|
401
|
+
const ci = new Command('ci').description('Scaffold CI integration for TestSprite');
|
|
402
|
+
ci.command('init <platform>')
|
|
403
|
+
.description('Write a CI workflow that runs your TestSprite tests (platform: github)')
|
|
404
|
+
.option('--project <id>', 'project id to run (auto-detected if you have exactly one)')
|
|
405
|
+
.option('--filter <substr>', 'only run tests whose name contains this substring')
|
|
406
|
+
.option('--timeout <s>', 'max seconds to wait for a terminal verdict (1-3600)', String(DEFAULT_TIMEOUT_SECONDS))
|
|
407
|
+
.option('--path <file>', 'output path for the workflow', DEFAULT_WORKFLOW_PATH)
|
|
408
|
+
.option('--force', 'overwrite an existing workflow (a .bak backup is kept)', false)
|
|
409
|
+
.option('--set-secret', `set the ${API_KEY_SECRET_NAME} repo secret via gh (if installed + authenticated); OVERWRITES an existing secret of that name`, false)
|
|
410
|
+
.option('--repo <owner/name>', 'target repo for --set-secret (gh infers from the cwd if omitted)')
|
|
411
|
+
.addHelpText('after', GLOBAL_OPTS_HINT)
|
|
412
|
+
.action(async (platform, cmdOpts, command) => {
|
|
413
|
+
const common = resolveCommonOptions(command);
|
|
414
|
+
const opts = {
|
|
415
|
+
...common,
|
|
416
|
+
platform,
|
|
417
|
+
project: cmdOpts.project,
|
|
418
|
+
filter: cmdOpts.filter,
|
|
419
|
+
timeoutSeconds: parseTimeoutSeconds(cmdOpts.timeout),
|
|
420
|
+
workflowPath: cmdOpts.path ?? DEFAULT_WORKFLOW_PATH,
|
|
421
|
+
force: cmdOpts.force ?? false,
|
|
422
|
+
setSecret: cmdOpts.setSecret ?? false,
|
|
423
|
+
repo: cmdOpts.repo,
|
|
424
|
+
};
|
|
425
|
+
await runCiInit(opts, deps);
|
|
426
|
+
});
|
|
427
|
+
return ci;
|
|
428
|
+
}
|
|
429
|
+
//# sourceMappingURL=ci.js.map
|
|
@@ -38,7 +38,7 @@ export interface DoctorDeps {
|
|
|
38
38
|
stderr?: (line: string) => void;
|
|
39
39
|
/** Project dir for the skill check. Defaults to `process.cwd()`. */
|
|
40
40
|
cwd?: string;
|
|
41
|
-
/** Runtime version string (e.g. "22.
|
|
41
|
+
/** Runtime version string (e.g. "22.13.0"). Defaults to `process.versions.node`. */
|
|
42
42
|
nodeVersion?: string;
|
|
43
43
|
existsSync?: (p: string) => boolean;
|
|
44
44
|
readFileSync?: (p: string) => string;
|
package/dist/commands/doctor.js
CHANGED
|
@@ -17,13 +17,13 @@
|
|
|
17
17
|
import { Command } from 'commander';
|
|
18
18
|
import { assertValidEndpointUrl, makeHttpClient, } from '../lib/client-factory.js';
|
|
19
19
|
import { loadConfig } from '../lib/config.js';
|
|
20
|
-
import { ApiError, CLIError, localValidationError } from '../lib/errors.js';
|
|
20
|
+
import { ApiError, CLIError, RequestTimeoutError, localValidationError } from '../lib/errors.js';
|
|
21
21
|
import { formatOrgBinding, formatOrgsSummary, formatPersonalScopeHint } from '../lib/org-render.js';
|
|
22
22
|
import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
|
|
23
23
|
import { isVerifySkillInstalled } from '../lib/skill-nudge.js';
|
|
24
24
|
import { emitV3RoutingAdvisory, routingLabel } from '../lib/v3-advisory.js';
|
|
25
25
|
import { VERSION } from '../version.js';
|
|
26
|
-
import {
|
|
26
|
+
import { SUPPORTED_NODE_RANGE, shouldRejectNodeVersion } from '../version-guard.js';
|
|
27
27
|
export async function runDoctor(opts, deps = {}) {
|
|
28
28
|
const out = makeOutput(opts.output, deps);
|
|
29
29
|
const env = deps.env ?? process.env;
|
|
@@ -76,6 +76,10 @@ export async function runDoctor(opts, deps = {}) {
|
|
|
76
76
|
if (personalScopeHint) {
|
|
77
77
|
checks.push({ name: 'Workspace scope', status: 'warn', detail: personalScopeHint });
|
|
78
78
|
}
|
|
79
|
+
checks.push(await checkLocalTunnel(opts, deps, {
|
|
80
|
+
hasKey,
|
|
81
|
+
endpointOk: endpointCheck.status === 'ok',
|
|
82
|
+
}));
|
|
79
83
|
checks.push(checkSkill(cwd, deps));
|
|
80
84
|
const failures = checks.filter(check => check.status === 'fail').length;
|
|
81
85
|
const warnings = checks.filter(check => check.status === 'warn').length;
|
|
@@ -93,17 +97,14 @@ export async function runDoctor(opts, deps = {}) {
|
|
|
93
97
|
return report;
|
|
94
98
|
}
|
|
95
99
|
function checkNodeVersion(nodeVersion) {
|
|
96
|
-
// Reuse the CLI
|
|
97
|
-
// entrypoint enforces at startup, rather than a divergent hardcoded check.
|
|
98
|
-
// The precise engines floor (20.19+/22.13+/24+) is enforced by npm at install
|
|
99
|
-
// time via .npmrc engine-strict. sourceRef: src/version-guard.ts.
|
|
100
|
+
// Reuse the CLI runtime guard so doctor and startup enforce and describe the same range.
|
|
100
101
|
const rejected = shouldRejectNodeVersion(nodeVersion);
|
|
101
102
|
return {
|
|
102
103
|
name: 'Node.js',
|
|
103
104
|
status: rejected ? 'fail' : 'ok',
|
|
104
105
|
detail: rejected
|
|
105
|
-
? `v${nodeVersion} is
|
|
106
|
-
: `v${nodeVersion} (
|
|
106
|
+
? `v${nodeVersion} is outside the supported Node range ${SUPPORTED_NODE_RANGE}; upgrade Node.js`
|
|
107
|
+
: `v${nodeVersion} (supported range: ${SUPPORTED_NODE_RANGE})`,
|
|
107
108
|
};
|
|
108
109
|
}
|
|
109
110
|
function checkEndpoint(apiUrl) {
|
|
@@ -192,6 +193,101 @@ async function checkConnectivity(opts, deps, ctx) {
|
|
|
192
193
|
};
|
|
193
194
|
}
|
|
194
195
|
}
|
|
196
|
+
/**
|
|
197
|
+
* Can this key open a tunnel to this machine (`test run --local`)?
|
|
198
|
+
*
|
|
199
|
+
* A READ, not a mint. `GET /tunnel/<random-uuid>` runs the same scope guard
|
|
200
|
+
* and the same environment-configured check as the mint, and answers 404 for
|
|
201
|
+
* an id nobody owns — so it proves everything that matters without consuming
|
|
202
|
+
* one of the caller's few concurrent live bindings or any rate-limit budget on
|
|
203
|
+
* a diagnostic.
|
|
204
|
+
*
|
|
205
|
+
* The case this exists for: `run:tunnel` is the first scope deliberately kept
|
|
206
|
+
* OUT of the grandfather grant, so a key minted before it — most keys in the
|
|
207
|
+
* wild — gets a 403 the first time someone tries `--local`, and the remedy is
|
|
208
|
+
* to mint a NEW key rather than to re-authenticate. Nothing else in the CLI
|
|
209
|
+
* says that until a run has already been refused.
|
|
210
|
+
*
|
|
211
|
+
* Never `fail`: a caller who does not use `--local` should not see `doctor`
|
|
212
|
+
* exit 1 over a surface that is not even configured in their environment.
|
|
213
|
+
*/
|
|
214
|
+
async function checkLocalTunnel(opts, deps, ctx) {
|
|
215
|
+
const name = 'Local tunnel';
|
|
216
|
+
if (opts.dryRun)
|
|
217
|
+
return { name, status: 'warn', detail: 'skipped under --dry-run' };
|
|
218
|
+
if (!ctx.hasKey)
|
|
219
|
+
return { name, status: 'warn', detail: 'skipped; no API key to test with' };
|
|
220
|
+
if (!ctx.endpointOk)
|
|
221
|
+
return { name, status: 'warn', detail: 'skipped; endpoint URL is invalid' };
|
|
222
|
+
const controller = new AbortController();
|
|
223
|
+
const probeTimer = setTimeout(() => {
|
|
224
|
+
controller.abort(new RequestTimeoutError(DOCTOR_TUNNEL_PROBE_TIMEOUT_MS));
|
|
225
|
+
}, DOCTOR_TUNNEL_PROBE_TIMEOUT_MS);
|
|
226
|
+
probeTimer.unref();
|
|
227
|
+
try {
|
|
228
|
+
const client = makeHttpClient({ ...opts, requestTimeoutMs: DOCTOR_TUNNEL_PROBE_TIMEOUT_MS }, {
|
|
229
|
+
env: deps.env,
|
|
230
|
+
credentialsPath: deps.credentialsPath,
|
|
231
|
+
fetchImpl: deps.fetchImpl,
|
|
232
|
+
stderr: deps.stderr,
|
|
233
|
+
// The retry sleeper listens to the client shutdown signal, so using
|
|
234
|
+
// the probe deadline here bounds attempts and Retry-After sleeps as
|
|
235
|
+
// one operation rather than timing each fetch independently.
|
|
236
|
+
shutdownSignal: controller.signal,
|
|
237
|
+
});
|
|
238
|
+
// A well-formed id that cannot name anyone's binding. A 200 here would
|
|
239
|
+
// mean the server handed us someone else's client, so it is reported as
|
|
240
|
+
// the anomaly it would be rather than quietly passing.
|
|
241
|
+
await client.getTunnelStatus(TUNNEL_PROBE_CLIENT_ID);
|
|
242
|
+
return {
|
|
243
|
+
name,
|
|
244
|
+
status: 'warn',
|
|
245
|
+
detail: 'unexpected: the server resolved a probe id that should belong to nobody',
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
catch (error) {
|
|
249
|
+
if (!(error instanceof ApiError)) {
|
|
250
|
+
return {
|
|
251
|
+
name,
|
|
252
|
+
status: 'warn',
|
|
253
|
+
detail: `could not check (${error instanceof Error ? error.message : String(error)})`,
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
if (error.code === 'NOT_FOUND') {
|
|
257
|
+
return { name, status: 'ok', detail: 'available; this key can open a tunnel (--local)' };
|
|
258
|
+
}
|
|
259
|
+
if (error.code === 'AUTH_FORBIDDEN') {
|
|
260
|
+
return {
|
|
261
|
+
name,
|
|
262
|
+
status: 'warn',
|
|
263
|
+
detail: 'this API key cannot open a tunnel — it predates the `run:tunnel` scope. ' +
|
|
264
|
+
'Mint a new API key in the dashboard to use `test run --local`.',
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
if (error.code === 'UNAVAILABLE') {
|
|
268
|
+
return {
|
|
269
|
+
name,
|
|
270
|
+
status: 'warn',
|
|
271
|
+
detail: '`test run --local` is not available on this endpoint',
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
return { name, status: 'warn', detail: `could not check (${error.code})` };
|
|
275
|
+
}
|
|
276
|
+
finally {
|
|
277
|
+
clearTimeout(probeTimer);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* A syntactically valid UUID that the mint route can never produce for anyone:
|
|
282
|
+
* it is fixed, so it belongs to nobody, and the surface collapses unknown /
|
|
283
|
+
* other-tenant / expired into one 404 by design.
|
|
284
|
+
*/
|
|
285
|
+
const TUNNEL_PROBE_CLIENT_ID = '00000000-0000-4000-8000-000000000000';
|
|
286
|
+
// A diagnostic status read should complete quickly; three seconds allows
|
|
287
|
+
// ordinary DNS/TLS latency while keeping `doctor` useful when this optional,
|
|
288
|
+
// warn-only surface is hung. This stays independent of the 120–600s business
|
|
289
|
+
// request deadline because waiting longer cannot change the check's outcome.
|
|
290
|
+
const DOCTOR_TUNNEL_PROBE_TIMEOUT_MS = 3_000;
|
|
195
291
|
const STATUS_LABEL = {
|
|
196
292
|
ok: '[OK] ',
|
|
197
293
|
warn: '[WARN]',
|
package/dist/commands/init.js
CHANGED
|
@@ -321,6 +321,14 @@ function renderInitText(data) {
|
|
|
321
321
|
lines.push(' agent: skipped (--no-agent)');
|
|
322
322
|
}
|
|
323
323
|
lines.push('');
|
|
324
|
+
// DEV-279: an agent session already open when the skills landed won't re-read
|
|
325
|
+
// them. `agent install` emits the same line on stderr; setup owns its summary,
|
|
326
|
+
// so it goes here. Only when bytes actually changed — `aggregateInstallAction`
|
|
327
|
+
// reports 'installed'/'updated' for that, 'dry-run'/'skipped' otherwise.
|
|
328
|
+
if (s.agent && (s.agent.action === 'installed' || s.agent.action === 'updated')) {
|
|
329
|
+
lines.push(` [hint] Reopen (or restart) your coding agent (${s.agent.target}) so it picks up the newly installed TestSprite skill(s).`);
|
|
330
|
+
lines.push('');
|
|
331
|
+
}
|
|
324
332
|
lines.push('Next steps:');
|
|
325
333
|
lines.push(' # 1. Create your first project (frontend example) — prints a projectId');
|
|
326
334
|
lines.push(' testsprite project create --type frontend --name "My App" --url https://your-app.com');
|