@testsprite/testsprite-cli 0.1.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/LICENSE +201 -0
- package/README.md +190 -0
- package/dist/assets/agent-skill/testsprite-verify.codex.md +119 -0
- package/dist/assets/agent-skill/testsprite-verify.skill.md +423 -0
- package/dist/commands/agent.d.ts +51 -0
- package/dist/commands/agent.js +552 -0
- package/dist/commands/auth.d.ts +38 -0
- package/dist/commands/auth.js +247 -0
- package/dist/commands/init.d.ts +63 -0
- package/dist/commands/init.js +350 -0
- package/dist/commands/project.d.ts +72 -0
- package/dist/commands/project.js +400 -0
- package/dist/commands/test.d.ts +1245 -0
- package/dist/commands/test.js +6214 -0
- package/dist/commands/usage.d.ts +63 -0
- package/dist/commands/usage.js +156 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +146 -0
- package/dist/lib/agent-targets.d.ts +50 -0
- package/dist/lib/agent-targets.js +99 -0
- package/dist/lib/bundle.d.ts +178 -0
- package/dist/lib/bundle.js +600 -0
- package/dist/lib/client-factory.d.ts +72 -0
- package/dist/lib/client-factory.js +120 -0
- package/dist/lib/config.d.ts +24 -0
- package/dist/lib/config.js +30 -0
- package/dist/lib/credentials.d.ts +17 -0
- package/dist/lib/credentials.js +122 -0
- package/dist/lib/dry-run/fetch.d.ts +18 -0
- package/dist/lib/dry-run/fetch.js +52 -0
- package/dist/lib/dry-run/samples.d.ts +50 -0
- package/dist/lib/dry-run/samples.js +676 -0
- package/dist/lib/errors.d.ts +118 -0
- package/dist/lib/errors.js +388 -0
- package/dist/lib/facade.d.ts +48 -0
- package/dist/lib/facade.js +104 -0
- package/dist/lib/failing-fe-resolver.d.ts +60 -0
- package/dist/lib/failing-fe-resolver.js +103 -0
- package/dist/lib/http.d.ts +255 -0
- package/dist/lib/http.js +608 -0
- package/dist/lib/output.d.ts +55 -0
- package/dist/lib/output.js +70 -0
- package/dist/lib/pagination.d.ts +56 -0
- package/dist/lib/pagination.js +81 -0
- package/dist/lib/poll.d.ts +88 -0
- package/dist/lib/poll.js +221 -0
- package/dist/lib/prompt.d.ts +8 -0
- package/dist/lib/prompt.js +97 -0
- package/dist/lib/rate-throttle.d.ts +49 -0
- package/dist/lib/rate-throttle.js +75 -0
- package/dist/lib/render-error.d.ts +15 -0
- package/dist/lib/render-error.js +44 -0
- package/dist/lib/runs.types.d.ts +344 -0
- package/dist/lib/runs.types.js +25 -0
- package/dist/lib/target-url.d.ts +25 -0
- package/dist/lib/target-url.js +127 -0
- package/dist/lib/ticker.d.ts +37 -0
- package/dist/lib/ticker.js +63 -0
- package/dist/lib/validate.d.ts +82 -0
- package/dist/lib/validate.js +165 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +2 -0
- package/package.json +65 -0
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import { Command } from 'commander';
|
|
2
|
+
import { emitDryRunBanner, makeHttpClient, } from '../lib/client-factory.js';
|
|
3
|
+
import { ApiError, CLIError } from '../lib/errors.js';
|
|
4
|
+
import { facadeBaseUrl } from '../lib/facade.js';
|
|
5
|
+
import { HttpClient } from '../lib/http.js';
|
|
6
|
+
import { defaultCredentialsPath, deleteProfile, readProfile, writeProfile, } from '../lib/credentials.js';
|
|
7
|
+
import { loadConfig } from '../lib/config.js';
|
|
8
|
+
import { GLOBAL_OPTS_HINT, Output } from '../lib/output.js';
|
|
9
|
+
import { promptSecret } from '../lib/prompt.js';
|
|
10
|
+
const DEFAULT_API_URL = 'https://api.testsprite.com';
|
|
11
|
+
const FROM_ENV_MISSING_KEY = 'TESTSPRITE_API_KEY is not set in the environment. Set it and re-run with --from-env, or omit --from-env to enter the key interactively.';
|
|
12
|
+
export async function runConfigure(opts, deps = {}) {
|
|
13
|
+
const env = deps.env ?? process.env;
|
|
14
|
+
const credentialsPath = deps.credentialsPath ?? defaultCredentialsPath();
|
|
15
|
+
const out = makeOutput(opts.output, deps);
|
|
16
|
+
const prelude = deps.preludeWrite ?? ((chunk) => process.stdout.write(chunk));
|
|
17
|
+
const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
|
|
18
|
+
// Normalize the env endpoint: an empty / whitespace-only TESTSPRITE_API_URL is
|
|
19
|
+
// treated as unset. Without this, `''` (e.g. `export TESTSPRITE_API_URL=` in a
|
|
20
|
+
// shell profile) is non-nullish and would short-circuit the `??` chains below to
|
|
21
|
+
// an empty endpoint instead of falling through to the profile / prod default.
|
|
22
|
+
const envApiUrl = env.TESTSPRITE_API_URL?.trim() || undefined;
|
|
23
|
+
// Dry-run: do not prompt, do not read env, do not write credentials.
|
|
24
|
+
// Print the canned success shape so an agent sees exactly the JSON it
|
|
25
|
+
// would get on a real configure (modulo the endpoint string).
|
|
26
|
+
if (opts.dryRun) {
|
|
27
|
+
emitDryRunBanner(stderr);
|
|
28
|
+
const apiUrl = opts.endpointUrl ?? envApiUrl ?? DEFAULT_API_URL;
|
|
29
|
+
stderr(`[dry-run] would write credentials for profile="${opts.profile}" to ${credentialsPath}`);
|
|
30
|
+
out.print({ profile: opts.profile, apiUrl, status: 'configured' }, data => {
|
|
31
|
+
const d = data;
|
|
32
|
+
return `Profile "${d.profile}" configured (dry-run). Endpoint: ${d.apiUrl}`;
|
|
33
|
+
});
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
let apiKey;
|
|
37
|
+
// Read the existing profile once — used for apiUrl inheritance in both
|
|
38
|
+
// --from-env and interactive paths when no explicit URL is supplied.
|
|
39
|
+
const existingProfile = readProfile(opts.profile, { path: credentialsPath });
|
|
40
|
+
// The API endpoint is resolved SILENTLY and is never prompted for. Public
|
|
41
|
+
// users must not be asked to configure an endpoint at install time — the prod
|
|
42
|
+
// default is always correct for them. Internal/staging point elsewhere via the
|
|
43
|
+
// global `--endpoint-url` flag or the `TESTSPRITE_API_URL` env var.
|
|
44
|
+
//
|
|
45
|
+
// Precedence: --endpoint-url flag > TESTSPRITE_API_URL > existing profile's
|
|
46
|
+
// api_url > built-in prod default. The existing-profile fallback mirrors
|
|
47
|
+
// lib/config.ts runtime resolution so a machine already pointed at a non-default
|
|
48
|
+
// api_url doesn't silently validate a new key against the default endpoint.
|
|
49
|
+
const resolvedFromProfile = existingProfile?.apiUrl;
|
|
50
|
+
const apiUrl = opts.endpointUrl ?? envApiUrl ?? resolvedFromProfile ?? DEFAULT_API_URL;
|
|
51
|
+
if (opts.fromEnv) {
|
|
52
|
+
apiKey = env.TESTSPRITE_API_KEY?.trim();
|
|
53
|
+
if (!apiKey)
|
|
54
|
+
throw validationError('TESTSPRITE_API_KEY', FROM_ENV_MISSING_KEY);
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
const promptApi = deps.prompt ?? { secret: (q) => promptSecret(q) };
|
|
58
|
+
prelude(`Configuring profile "${opts.profile}".\n`);
|
|
59
|
+
// Only the API key is prompted — the endpoint defaults to prod (see above).
|
|
60
|
+
apiKey = (await promptApi.secret('TestSprite API key: ')).trim();
|
|
61
|
+
if (!apiKey)
|
|
62
|
+
throw new CLIError('No API key provided.', 5);
|
|
63
|
+
}
|
|
64
|
+
// Advisory: when the endpoint was silently inherited from an existing profile
|
|
65
|
+
// (not an explicit flag/env), surface it before validating the key against it
|
|
66
|
+
// so a key is never checked against an unexpected host without the user noticing.
|
|
67
|
+
if (!opts.endpointUrl &&
|
|
68
|
+
!envApiUrl &&
|
|
69
|
+
resolvedFromProfile &&
|
|
70
|
+
resolvedFromProfile !== DEFAULT_API_URL) {
|
|
71
|
+
stderr(`[advisory] Inheriting api_url from existing profile: ${resolvedFromProfile}`);
|
|
72
|
+
}
|
|
73
|
+
// Verify the key is accepted before persisting. Build an HttpClient
|
|
74
|
+
// directly (bypassing loadConfig) so we can test the candidate key+url
|
|
75
|
+
// before it is written to disk. This ensures we never overwrite a
|
|
76
|
+
// working profile with a bad key.
|
|
77
|
+
const pingClient = new HttpClient({
|
|
78
|
+
baseUrl: facadeBaseUrl(apiUrl),
|
|
79
|
+
apiKey,
|
|
80
|
+
fetchImpl: deps.fetchImpl,
|
|
81
|
+
});
|
|
82
|
+
try {
|
|
83
|
+
await pingClient.get('/me');
|
|
84
|
+
}
|
|
85
|
+
catch (err) {
|
|
86
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
87
|
+
stderr(`API key rejected by ${apiUrl}: ${message} — profile NOT updated`);
|
|
88
|
+
const exitCode = err instanceof ApiError ? err.exitCode : 3;
|
|
89
|
+
// Include the resolved endpoint in the thrown message so the user knows
|
|
90
|
+
// which host rejected the key. This prevents the "invalid or revoked"
|
|
91
|
+
// message from being ambiguous when the key is valid for a different env.
|
|
92
|
+
throw new CLIError(`API key rejected by ${apiUrl}: ${message} — did you mean to set TESTSPRITE_API_URL?`, exitCode);
|
|
93
|
+
}
|
|
94
|
+
writeProfile(opts.profile, { apiKey, apiUrl }, { path: credentialsPath });
|
|
95
|
+
out.print({ profile: opts.profile, apiUrl, status: 'configured' }, data => {
|
|
96
|
+
const d = data;
|
|
97
|
+
return `Profile "${d.profile}" configured. Endpoint: ${d.apiUrl}`;
|
|
98
|
+
});
|
|
99
|
+
// Self-bootstrap: nudge the user toward wiring their coding agent to TestSprite.
|
|
100
|
+
// stderr + text-only + real-run-only so JSON consumers and dry-run previews stay clean.
|
|
101
|
+
if (opts.output === 'text' && !opts.dryRun) {
|
|
102
|
+
stderr('Tip: run `testsprite agent install --target=claude` to let your coding ' +
|
|
103
|
+
'agent run TestSprite tests automatically (also: cursor, cline, antigravity).');
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
export async function runWhoami(opts, deps = {}) {
|
|
107
|
+
const out = makeOutput(opts.output, deps);
|
|
108
|
+
const env = deps.env ?? process.env;
|
|
109
|
+
// Resolve the endpoint URL so it can be surfaced in text output.
|
|
110
|
+
// Dry-run uses the flag/env/default chain without touching credentials.
|
|
111
|
+
// Real path uses the same loadConfig the HttpClient factory uses so the
|
|
112
|
+
// displayed URL always matches where requests actually go (dogfood L1788).
|
|
113
|
+
let resolvedEndpoint;
|
|
114
|
+
if (opts.dryRun) {
|
|
115
|
+
resolvedEndpoint = opts.endpointUrl ?? env.TESTSPRITE_API_URL ?? 'https://api.testsprite.com';
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
const credentialsPath = deps.credentialsPath ?? defaultCredentialsPath();
|
|
119
|
+
const config = loadConfig({
|
|
120
|
+
profile: opts.profile,
|
|
121
|
+
endpointUrl: opts.endpointUrl,
|
|
122
|
+
env,
|
|
123
|
+
credentialsPath,
|
|
124
|
+
});
|
|
125
|
+
resolvedEndpoint = config.apiUrl;
|
|
126
|
+
}
|
|
127
|
+
// Dry-run + real path both go through the shared factory.
|
|
128
|
+
const client = makeHttpClient(opts, {
|
|
129
|
+
env: deps.env,
|
|
130
|
+
credentialsPath: deps.credentialsPath,
|
|
131
|
+
fetchImpl: deps.fetchImpl,
|
|
132
|
+
stderr: deps.stderr,
|
|
133
|
+
});
|
|
134
|
+
const me = await client.get('/me');
|
|
135
|
+
out.print(me, data => {
|
|
136
|
+
const m = data;
|
|
137
|
+
const lines = [
|
|
138
|
+
`userId: ${m.userId}`,
|
|
139
|
+
// Human-readable identity, rendered only when the backend supplies it
|
|
140
|
+
// (dogfood L1866) — confirm the account at a glance before a billable run.
|
|
141
|
+
...(m.displayName ? [`name: ${m.displayName}`] : []),
|
|
142
|
+
...(m.email ? [`email: ${m.email}`] : []),
|
|
143
|
+
`keyId: ${m.keyId}`,
|
|
144
|
+
// Show the resolved endpoint so the user knows which env they are bound to
|
|
145
|
+
// without having to infer from the `env` field alone (dogfood L1788).
|
|
146
|
+
`endpoint: ${resolvedEndpoint}`,
|
|
147
|
+
`env: ${m.env}`,
|
|
148
|
+
`scopes: ${m.scopes.join(', ')}`,
|
|
149
|
+
];
|
|
150
|
+
// C2: warn in text mode when key cannot write/run
|
|
151
|
+
const missingScopes = ['write:tests', 'run:tests'].filter(s => !m.scopes.includes(s));
|
|
152
|
+
if (missingScopes.length > 0) {
|
|
153
|
+
lines.push(`note: this key cannot run write or test-trigger commands. Missing scopes: ${missingScopes.join(', ')}. Ask your account owner to extend it via the portal.`);
|
|
154
|
+
}
|
|
155
|
+
return lines.join('\n');
|
|
156
|
+
});
|
|
157
|
+
return me;
|
|
158
|
+
}
|
|
159
|
+
export async function runLogout(opts, deps = {}) {
|
|
160
|
+
const credentialsPath = deps.credentialsPath ?? defaultCredentialsPath();
|
|
161
|
+
const out = makeOutput(opts.output, deps);
|
|
162
|
+
const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
|
|
163
|
+
if (opts.dryRun) {
|
|
164
|
+
emitDryRunBanner(stderr);
|
|
165
|
+
stderr(`[dry-run] would remove credentials for profile="${opts.profile}" from ${credentialsPath}`);
|
|
166
|
+
out.print({ profile: opts.profile, status: 'logged_out' }, data => {
|
|
167
|
+
const d = data;
|
|
168
|
+
return `Removed credentials for profile "${d.profile}" (dry-run).`;
|
|
169
|
+
});
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
const removed = deleteProfile(opts.profile, { path: credentialsPath });
|
|
173
|
+
out.print({ profile: opts.profile, status: removed ? 'logged_out' : 'no_credentials' }, data => {
|
|
174
|
+
const d = data;
|
|
175
|
+
return d.status === 'logged_out'
|
|
176
|
+
? `Removed credentials for profile "${d.profile}".`
|
|
177
|
+
: `No credentials stored for profile "${d.profile}".`;
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
export function createAuthCommand(deps = {}) {
|
|
181
|
+
const auth = new Command('auth').description('Manage TestSprite credentials');
|
|
182
|
+
auth
|
|
183
|
+
.command('configure')
|
|
184
|
+
.description('Configure an API key for the active profile')
|
|
185
|
+
.option('--from-env', 'Read TESTSPRITE_API_KEY (and optionally TESTSPRITE_API_URL) from the environment instead of prompting', false)
|
|
186
|
+
.addHelpText('after', GLOBAL_OPTS_HINT)
|
|
187
|
+
.action(async (cmdOpts, command) => {
|
|
188
|
+
await runConfigure({ ...resolveCommonOptions(command), fromEnv: Boolean(cmdOpts.fromEnv) }, deps);
|
|
189
|
+
});
|
|
190
|
+
auth
|
|
191
|
+
.command('whoami')
|
|
192
|
+
.alias('status') // muscle-memory alias; `auth status` resolves to `auth whoami` (dogfood L1802)
|
|
193
|
+
.description('Show the user, API key, and scopes bound to the active profile')
|
|
194
|
+
.addHelpText('after', GLOBAL_OPTS_HINT)
|
|
195
|
+
.action(async (_cmdOpts, command) => {
|
|
196
|
+
await runWhoami(resolveCommonOptions(command), deps);
|
|
197
|
+
});
|
|
198
|
+
auth
|
|
199
|
+
.command('logout')
|
|
200
|
+
.description('Remove credentials for the active profile')
|
|
201
|
+
.addHelpText('after', GLOBAL_OPTS_HINT)
|
|
202
|
+
.action(async (_cmdOpts, command) => {
|
|
203
|
+
await runLogout(resolveCommonOptions(command), deps);
|
|
204
|
+
});
|
|
205
|
+
return auth;
|
|
206
|
+
}
|
|
207
|
+
function resolveCommonOptions(command) {
|
|
208
|
+
const globals = command.optsWithGlobals();
|
|
209
|
+
return {
|
|
210
|
+
profile: globals.profile ?? 'default',
|
|
211
|
+
output: globals.output ?? 'text',
|
|
212
|
+
endpointUrl: globals.endpointUrl,
|
|
213
|
+
debug: globals.debug ?? false,
|
|
214
|
+
verbose: globals.verbose ?? false,
|
|
215
|
+
dryRun: globals.dryRun ?? false,
|
|
216
|
+
requestTimeoutMs: parseRequestTimeoutFlag(globals.requestTimeout),
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Parse the `--request-timeout <seconds>` flag value into milliseconds.
|
|
221
|
+
* Returns `undefined` when the flag was not supplied (factory falls back to
|
|
222
|
+
* the env var / default). Silently clamps out-of-range values — the
|
|
223
|
+
* factory applies the same clamp so there is no double-clamp risk.
|
|
224
|
+
*/
|
|
225
|
+
function parseRequestTimeoutFlag(raw) {
|
|
226
|
+
if (raw === undefined)
|
|
227
|
+
return undefined;
|
|
228
|
+
const n = Number(raw);
|
|
229
|
+
if (!Number.isFinite(n) || n <= 0)
|
|
230
|
+
return undefined;
|
|
231
|
+
return Math.round(n * 1000); // seconds → milliseconds
|
|
232
|
+
}
|
|
233
|
+
function makeOutput(mode, deps) {
|
|
234
|
+
return new Output(mode, { stdout: deps.stdout, stderr: deps.stderr });
|
|
235
|
+
}
|
|
236
|
+
function validationError(field, message) {
|
|
237
|
+
return ApiError.fromEnvelope({
|
|
238
|
+
error: {
|
|
239
|
+
code: 'VALIDATION_ERROR',
|
|
240
|
+
message,
|
|
241
|
+
nextAction: `Set ${field} and re-run.`,
|
|
242
|
+
requestId: 'local',
|
|
243
|
+
details: { field, reason: 'missing' },
|
|
244
|
+
},
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
//# sourceMappingURL=auth.js.map
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `testsprite init` — one-shot onboarding orchestrator.
|
|
3
|
+
*
|
|
4
|
+
* Chains, in order:
|
|
5
|
+
* 1. runConfigure — writes the API-key profile (validates via GET /me first)
|
|
6
|
+
* 2. runWhoami — fetches identity for the post-configure banner
|
|
7
|
+
* 3. runInstall — installs the TestSprite verification-loop skill (unless --no-agent)
|
|
8
|
+
* 4. Summary print — JSON object or human text block
|
|
9
|
+
*
|
|
10
|
+
* Hard constraint: orchestrate existing exported primitives; never fork them.
|
|
11
|
+
*/
|
|
12
|
+
import { Command } from 'commander';
|
|
13
|
+
import type { CommonOptions as FactoryCommonOptions } from '../lib/client-factory.js';
|
|
14
|
+
import type { AuthDeps } from './auth.js';
|
|
15
|
+
import type { AgentFs } from './agent.js';
|
|
16
|
+
import type { FetchImpl } from '../lib/http.js';
|
|
17
|
+
type CommonOptions = FactoryCommonOptions;
|
|
18
|
+
/**
|
|
19
|
+
* InitDeps merges AuthDeps and AgentDeps. Because the `prompt` field differs
|
|
20
|
+
* between them (`{secret: fn}` in AuthDeps vs a plain function in AgentDeps),
|
|
21
|
+
* we compose manually and expose `agentPrompt` for the agent install step.
|
|
22
|
+
*/
|
|
23
|
+
export interface InitDeps {
|
|
24
|
+
env?: NodeJS.ProcessEnv;
|
|
25
|
+
stdout?: (line: string) => void;
|
|
26
|
+
stderr?: (line: string) => void;
|
|
27
|
+
credentialsPath?: string;
|
|
28
|
+
fetchImpl?: FetchImpl;
|
|
29
|
+
/** Injected for auth configure: { secret: (q) => Promise<string> } */
|
|
30
|
+
prompt?: AuthDeps['prompt'];
|
|
31
|
+
preludeWrite?: (chunk: string) => void;
|
|
32
|
+
cwd?: string;
|
|
33
|
+
fs?: AgentFs;
|
|
34
|
+
isTTY?: boolean;
|
|
35
|
+
/** Injected for agent install prompt (plain function, not {secret: fn}) */
|
|
36
|
+
agentPrompt?: (question: string) => Promise<string>;
|
|
37
|
+
}
|
|
38
|
+
interface InitOptions extends CommonOptions {
|
|
39
|
+
apiKey?: string;
|
|
40
|
+
fromEnv: boolean;
|
|
41
|
+
agent: string;
|
|
42
|
+
noAgent: boolean;
|
|
43
|
+
force: boolean;
|
|
44
|
+
dir?: string;
|
|
45
|
+
yes: boolean;
|
|
46
|
+
/** Set by the command action when both --agent and --no-agent appear in rawArgs. */
|
|
47
|
+
rawArgConflict?: boolean;
|
|
48
|
+
}
|
|
49
|
+
export interface InitSummary {
|
|
50
|
+
profile: string;
|
|
51
|
+
apiUrl: string;
|
|
52
|
+
env: string;
|
|
53
|
+
email?: string;
|
|
54
|
+
scopes: string[];
|
|
55
|
+
agent: {
|
|
56
|
+
target: string;
|
|
57
|
+
action: string;
|
|
58
|
+
} | null;
|
|
59
|
+
status: 'initialized';
|
|
60
|
+
}
|
|
61
|
+
export declare function runInit(opts: InitOptions, deps?: InitDeps): Promise<void>;
|
|
62
|
+
export declare function createInitCommand(deps?: InitDeps): Command;
|
|
63
|
+
export {};
|
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `testsprite init` — one-shot onboarding orchestrator.
|
|
3
|
+
*
|
|
4
|
+
* Chains, in order:
|
|
5
|
+
* 1. runConfigure — writes the API-key profile (validates via GET /me first)
|
|
6
|
+
* 2. runWhoami — fetches identity for the post-configure banner
|
|
7
|
+
* 3. runInstall — installs the TestSprite verification-loop skill (unless --no-agent)
|
|
8
|
+
* 4. Summary print — JSON object or human text block
|
|
9
|
+
*
|
|
10
|
+
* Hard constraint: orchestrate existing exported primitives; never fork them.
|
|
11
|
+
*/
|
|
12
|
+
import { Command } from 'commander';
|
|
13
|
+
import { CLIError } from '../lib/errors.js';
|
|
14
|
+
import { GLOBAL_OPTS_HINT, Output } from '../lib/output.js';
|
|
15
|
+
import { runConfigure, runWhoami } from './auth.js';
|
|
16
|
+
import { runInstall } from './agent.js';
|
|
17
|
+
import { TARGETS } from '../lib/agent-targets.js';
|
|
18
|
+
import { readProfile } from '../lib/credentials.js';
|
|
19
|
+
/** Mirrors auth.ts's DEFAULT_API_URL (kept in sync; auth.ts owns the canonical value). */
|
|
20
|
+
const DEFAULT_API_URL = 'https://api.testsprite.com';
|
|
21
|
+
/**
|
|
22
|
+
* Resolve the endpoint the summary should report, using the SAME precedence
|
|
23
|
+
* `runConfigure` uses to pick (and persist) the endpoint:
|
|
24
|
+
* --endpoint-url > TESTSPRITE_API_URL env > existing profile apiUrl > prod default.
|
|
25
|
+
* Reporting a flat prod default would falsely claim a prod target after
|
|
26
|
+
* configuring staging/dev (codex). On the real path this runs AFTER the profile
|
|
27
|
+
* is written, so the persisted apiUrl is reflected faithfully.
|
|
28
|
+
*/
|
|
29
|
+
function resolveReportedEndpoint(opts, deps) {
|
|
30
|
+
const env = deps.env ?? process.env;
|
|
31
|
+
const envApiUrl = env.TESTSPRITE_API_URL?.trim() || undefined;
|
|
32
|
+
let existing;
|
|
33
|
+
try {
|
|
34
|
+
existing = readProfile(opts.profile, { path: deps.credentialsPath })?.apiUrl;
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
existing = undefined;
|
|
38
|
+
}
|
|
39
|
+
return opts.endpointUrl ?? envApiUrl ?? existing ?? DEFAULT_API_URL;
|
|
40
|
+
}
|
|
41
|
+
// ---------------------------------------------------------------------------
|
|
42
|
+
// Helpers to split deps into the two primitive shapes
|
|
43
|
+
// ---------------------------------------------------------------------------
|
|
44
|
+
/**
|
|
45
|
+
* Build AuthDeps from InitDeps. `stdout` is intentionally suppressed here
|
|
46
|
+
* because runInit owns the final output — runConfigure's success message
|
|
47
|
+
* and runWhoami's identity block are replaced by the init summary.
|
|
48
|
+
* stderr (advisory messages, errors) flows through.
|
|
49
|
+
*/
|
|
50
|
+
function toAuthDeps(deps, apiKey) {
|
|
51
|
+
return {
|
|
52
|
+
env: deps.env,
|
|
53
|
+
credentialsPath: deps.credentialsPath,
|
|
54
|
+
fetchImpl: deps.fetchImpl,
|
|
55
|
+
stdout: _suppressedStdout,
|
|
56
|
+
stderr: deps.stderr,
|
|
57
|
+
// Forward the preludeWrite so injected tests can capture the "Configuring
|
|
58
|
+
// profile..." line, but default to a no-op so tests that don't care don't
|
|
59
|
+
// see it on real process.stdout.
|
|
60
|
+
preludeWrite: deps.preludeWrite ?? _suppressedStdout,
|
|
61
|
+
// If an explicit API key was provided, override the prompt so configure
|
|
62
|
+
// never actually prompts the user.
|
|
63
|
+
prompt: apiKey ? { secret: async (_q) => apiKey } : deps.prompt,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Build AgentDeps from InitDeps. `stdout` is suppressed for the same reason —
|
|
68
|
+
* runInit owns output. The result is parsed from the captured JSON in the
|
|
69
|
+
* caller, not forwarded to user stdout.
|
|
70
|
+
*/
|
|
71
|
+
function toAgentDeps(deps, captureStdout) {
|
|
72
|
+
return {
|
|
73
|
+
cwd: deps.cwd,
|
|
74
|
+
fs: deps.fs,
|
|
75
|
+
stdout: captureStdout ?? _suppressedStdout,
|
|
76
|
+
stderr: deps.stderr,
|
|
77
|
+
isTTY: deps.isTTY,
|
|
78
|
+
prompt: deps.agentPrompt,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
// Discards stdout lines from sub-commands so runInit owns the output surface.
|
|
82
|
+
function _suppressedStdout(_line) {
|
|
83
|
+
// intentionally empty
|
|
84
|
+
}
|
|
85
|
+
// ---------------------------------------------------------------------------
|
|
86
|
+
// runInit
|
|
87
|
+
// ---------------------------------------------------------------------------
|
|
88
|
+
export async function runInit(opts, deps = {}) {
|
|
89
|
+
const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
|
|
90
|
+
const out = new Output(opts.output, { stdout: deps.stdout, stderr: deps.stderr });
|
|
91
|
+
// -------------------------------------------------------------------------
|
|
92
|
+
// Fix 5: emit conflict warning when both --agent and --no-agent were given
|
|
93
|
+
// -------------------------------------------------------------------------
|
|
94
|
+
if (opts.rawArgConflict) {
|
|
95
|
+
const effectiveLabel = opts.noAgent ? '--no-agent' : `--agent ${opts.agent}`;
|
|
96
|
+
stderrFn(`[warn] both --no-agent and --agent supplied; using ${effectiveLabel} (last flag wins)`);
|
|
97
|
+
}
|
|
98
|
+
// -------------------------------------------------------------------------
|
|
99
|
+
// Non-interactive guard: no TTY + no key source → exit 5 immediately
|
|
100
|
+
// -------------------------------------------------------------------------
|
|
101
|
+
const isTTY = deps.isTTY ?? Boolean(process.stdin.isTTY);
|
|
102
|
+
const hasKeySource = Boolean(opts.apiKey) || opts.fromEnv;
|
|
103
|
+
// Non-interactive guard: no TTY + no key source → exit 5. Skipped under
|
|
104
|
+
// --dry-run, which is documented to work without credentials or network.
|
|
105
|
+
if (!isTTY && !hasKeySource && !opts.dryRun) {
|
|
106
|
+
throw new CLIError('No API key available in non-interactive mode. ' +
|
|
107
|
+
'Pass --api-key <key>, --from-env (reads TESTSPRITE_API_KEY), or run interactively.', 5);
|
|
108
|
+
}
|
|
109
|
+
// JSON-output guard: an interactive secret prompt writes to stdout and would
|
|
110
|
+
// corrupt init's single-JSON-object output contract. In --output json mode
|
|
111
|
+
// require a non-interactive key source. Skipped under --dry-run (never prompts).
|
|
112
|
+
if (opts.output === 'json' && !hasKeySource && !opts.dryRun) {
|
|
113
|
+
throw new CLIError('Interactive API-key prompt is unavailable in --output json mode (it would corrupt JSON stdout). ' +
|
|
114
|
+
'Pass --api-key <key> or --from-env.', 5);
|
|
115
|
+
}
|
|
116
|
+
// -------------------------------------------------------------------------
|
|
117
|
+
// Dry-run: zero network + zero FS writes; print preview only
|
|
118
|
+
// -------------------------------------------------------------------------
|
|
119
|
+
if (opts.dryRun) {
|
|
120
|
+
stderrFn('[dry-run] no writes or network calls — preview only');
|
|
121
|
+
stderrFn(`[dry-run] would configure profile="${opts.profile}" (key source: ${opts.apiKey ? 'flag' : opts.fromEnv ? 'env' : 'prompt'})`);
|
|
122
|
+
const agentTarget = opts.noAgent ? null : opts.agent;
|
|
123
|
+
if (!opts.noAgent) {
|
|
124
|
+
// Delegate to runInstall's own dry-run for the file-listing preview.
|
|
125
|
+
// runInstall prints the would-write lines itself under dryRun.
|
|
126
|
+
await runInstall({
|
|
127
|
+
...opts,
|
|
128
|
+
target: [agentTarget],
|
|
129
|
+
force: opts.force,
|
|
130
|
+
dir: opts.dir,
|
|
131
|
+
}, toAgentDeps(deps));
|
|
132
|
+
}
|
|
133
|
+
const summary = {
|
|
134
|
+
profile: opts.profile,
|
|
135
|
+
apiUrl: resolveReportedEndpoint(opts, deps),
|
|
136
|
+
env: 'development',
|
|
137
|
+
scopes: [],
|
|
138
|
+
agent: agentTarget ? { target: agentTarget, action: 'dry-run' } : null,
|
|
139
|
+
status: 'initialized',
|
|
140
|
+
};
|
|
141
|
+
out.print(summary, renderInitText);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
// -------------------------------------------------------------------------
|
|
145
|
+
// Step 1: Configure — validates key via GET /me before writing the profile
|
|
146
|
+
// -------------------------------------------------------------------------
|
|
147
|
+
// --api-key takes precedence over --from-env: when an explicit key is supplied,
|
|
148
|
+
// force fromEnv=false so runConfigure uses the injected key (toAuthDeps wires it
|
|
149
|
+
// as the prompt) instead of reading TESTSPRITE_API_KEY from the environment (codex).
|
|
150
|
+
await runConfigure({ ...opts, fromEnv: opts.apiKey ? false : opts.fromEnv }, toAuthDeps(deps, opts.apiKey));
|
|
151
|
+
// -------------------------------------------------------------------------
|
|
152
|
+
// Step 2: Whoami banner — for identity display only; not used for validation
|
|
153
|
+
// -------------------------------------------------------------------------
|
|
154
|
+
// runWhoami resolves its key via loadConfig (`env.TESTSPRITE_API_KEY ?? profile`).
|
|
155
|
+
// When the user passed an explicit --api-key, that key was just written to the
|
|
156
|
+
// profile above — but a STALE/different TESTSPRITE_API_KEY still in the environment
|
|
157
|
+
// would WIN in loadConfig and make the banner read the wrong identity (a bogus key →
|
|
158
|
+
// 401 → misleading `production`/no-email summary). Strip it for the whoami read so it
|
|
159
|
+
// uses the profile we just wrote (E2E finding 2026-06-09). Only when --api-key was
|
|
160
|
+
// given: a bare --from-env run legitimately relies on the env key.
|
|
161
|
+
const whoamiDeps = toAuthDeps(deps);
|
|
162
|
+
if (opts.apiKey) {
|
|
163
|
+
const sanitizedEnv = { ...(deps.env ?? process.env) };
|
|
164
|
+
delete sanitizedEnv.TESTSPRITE_API_KEY;
|
|
165
|
+
whoamiDeps.env = sanitizedEnv;
|
|
166
|
+
}
|
|
167
|
+
let me;
|
|
168
|
+
try {
|
|
169
|
+
me = await runWhoami(opts, whoamiDeps);
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
// Whoami is display-only. If it fails after a successful configure,
|
|
173
|
+
// continue with a minimal placeholder so the summary still prints.
|
|
174
|
+
me = { userId: '', keyId: '', scopes: [], env: 'production' };
|
|
175
|
+
}
|
|
176
|
+
// -------------------------------------------------------------------------
|
|
177
|
+
// Step 3: Agent skill install (unless --no-agent)
|
|
178
|
+
// -------------------------------------------------------------------------
|
|
179
|
+
let installedTarget = null;
|
|
180
|
+
let installedAction = null;
|
|
181
|
+
if (!opts.noAgent) {
|
|
182
|
+
// Run install in JSON mode internally so we can reliably parse the action
|
|
183
|
+
// regardless of the outer --output flag. The stdout is captured here and
|
|
184
|
+
// NOT forwarded — runInit owns the output surface.
|
|
185
|
+
let capturedInstallResult = null;
|
|
186
|
+
const captureStdout = (line) => {
|
|
187
|
+
try {
|
|
188
|
+
const parsed = JSON.parse(line);
|
|
189
|
+
if (Array.isArray(parsed) && parsed.length > 0 && parsed[0]) {
|
|
190
|
+
capturedInstallResult = parsed[0];
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
catch {
|
|
194
|
+
// ignore non-JSON lines (shouldn't happen in json mode, but be safe)
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
try {
|
|
198
|
+
await runInstall({
|
|
199
|
+
...opts,
|
|
200
|
+
output: 'json', // parse the result; final summary is ours to print
|
|
201
|
+
target: [opts.agent],
|
|
202
|
+
force: opts.force,
|
|
203
|
+
dir: opts.dir,
|
|
204
|
+
}, toAgentDeps(deps, captureStdout));
|
|
205
|
+
installedTarget = opts.agent;
|
|
206
|
+
installedAction = capturedInstallResult
|
|
207
|
+
? capturedInstallResult.action
|
|
208
|
+
: 'installed';
|
|
209
|
+
}
|
|
210
|
+
catch (installErr) {
|
|
211
|
+
// Fix 6: credentials were already saved (Step 1+2 above succeeded).
|
|
212
|
+
// Emit a clear summary line BEFORE re-throwing so the user knows their
|
|
213
|
+
// API key was persisted — only the agent skill step failed (Fix 6).
|
|
214
|
+
stderrFn(`[info] credentials saved for profile "${opts.profile}"; only the agent skill install failed — ` +
|
|
215
|
+
`re-run 'testsprite agent install --target ${opts.agent}' after fixing the path`);
|
|
216
|
+
throw installErr;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
// -------------------------------------------------------------------------
|
|
220
|
+
// Step 4: Summary
|
|
221
|
+
// -------------------------------------------------------------------------
|
|
222
|
+
const agentSummary = opts.noAgent || installedTarget === null
|
|
223
|
+
? null
|
|
224
|
+
: { target: installedTarget, action: installedAction ?? 'installed' };
|
|
225
|
+
const summary = {
|
|
226
|
+
profile: opts.profile,
|
|
227
|
+
// Resolved AFTER configure persists the profile → reflects the real endpoint
|
|
228
|
+
// (staging/dev/prod), not a flat prod default (codex).
|
|
229
|
+
apiUrl: resolveReportedEndpoint(opts, deps),
|
|
230
|
+
env: me.env,
|
|
231
|
+
email: me.email,
|
|
232
|
+
scopes: me.scopes,
|
|
233
|
+
agent: agentSummary,
|
|
234
|
+
status: 'initialized',
|
|
235
|
+
};
|
|
236
|
+
out.print(summary, renderInitText);
|
|
237
|
+
}
|
|
238
|
+
// ---------------------------------------------------------------------------
|
|
239
|
+
// Text renderer
|
|
240
|
+
// ---------------------------------------------------------------------------
|
|
241
|
+
function renderInitText(data) {
|
|
242
|
+
const s = data;
|
|
243
|
+
const lines = [];
|
|
244
|
+
lines.push('TestSprite initialized.');
|
|
245
|
+
lines.push('');
|
|
246
|
+
lines.push(` profile: ${s.profile}`);
|
|
247
|
+
lines.push(` endpoint: ${s.apiUrl}`);
|
|
248
|
+
lines.push(` env: ${s.env}`);
|
|
249
|
+
if (s.email)
|
|
250
|
+
lines.push(` email: ${s.email}`);
|
|
251
|
+
if (s.scopes.length > 0)
|
|
252
|
+
lines.push(` scopes: ${s.scopes.join(', ')}`);
|
|
253
|
+
lines.push('');
|
|
254
|
+
if (s.agent) {
|
|
255
|
+
lines.push(` agent: ${s.agent.target} (${s.agent.action})`);
|
|
256
|
+
}
|
|
257
|
+
else {
|
|
258
|
+
lines.push(' agent: skipped (--no-agent)');
|
|
259
|
+
}
|
|
260
|
+
lines.push('');
|
|
261
|
+
lines.push('Next steps:');
|
|
262
|
+
lines.push(' testsprite test list # list tests in the current project');
|
|
263
|
+
lines.push(' testsprite agent list # check installed agent targets');
|
|
264
|
+
if (s.agent) {
|
|
265
|
+
lines.push(' testsprite agent install --target=<t> # re-install or install additional targets');
|
|
266
|
+
}
|
|
267
|
+
return lines.join('\n');
|
|
268
|
+
}
|
|
269
|
+
// ---------------------------------------------------------------------------
|
|
270
|
+
// Command factory
|
|
271
|
+
// ---------------------------------------------------------------------------
|
|
272
|
+
function resolveCommonOptions(command) {
|
|
273
|
+
const globals = command.optsWithGlobals();
|
|
274
|
+
return {
|
|
275
|
+
profile: globals.profile ?? 'default',
|
|
276
|
+
output: globals.output ?? 'text',
|
|
277
|
+
endpointUrl: globals.endpointUrl,
|
|
278
|
+
debug: globals.debug ?? false,
|
|
279
|
+
verbose: globals.verbose ?? false,
|
|
280
|
+
dryRun: globals.dryRun ?? false,
|
|
281
|
+
requestTimeoutMs: parseRequestTimeoutFlag(globals.requestTimeout),
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
function parseRequestTimeoutFlag(raw) {
|
|
285
|
+
if (raw === undefined)
|
|
286
|
+
return undefined;
|
|
287
|
+
const n = Number(raw);
|
|
288
|
+
if (!Number.isFinite(n) || n <= 0)
|
|
289
|
+
return undefined;
|
|
290
|
+
return Math.round(n * 1000);
|
|
291
|
+
}
|
|
292
|
+
export function createInitCommand(deps = {}) {
|
|
293
|
+
const validTargets = Object.keys(TARGETS);
|
|
294
|
+
const defaultAgent = 'claude';
|
|
295
|
+
const cmd = new Command('init')
|
|
296
|
+
.description('One-shot onboarding: configure an API key and install the coding-agent skill')
|
|
297
|
+
.option('--api-key <key>', 'API key to configure (skips the interactive prompt)')
|
|
298
|
+
.option('--from-env', 'Read TESTSPRITE_API_KEY from the environment instead of prompting', false)
|
|
299
|
+
.option('--agent <target>', `Coding-agent target to install: ${validTargets.join(', ')} (default: ${defaultAgent})`, defaultAgent)
|
|
300
|
+
.option('--no-agent', 'Skip the agent skill install (configure credentials only)')
|
|
301
|
+
.option('--force', 'Overwrite an existing skill file (a .bak backup is kept)')
|
|
302
|
+
.option('--dir <path>', 'Project root for the skill install (default: current directory)')
|
|
303
|
+
.option('-y, --yes', 'Non-interactive: accept all defaults, never prompt')
|
|
304
|
+
.addHelpText('after', GLOBAL_OPTS_HINT)
|
|
305
|
+
.action(async (cmdOpts, command) => {
|
|
306
|
+
const common = resolveCommonOptions(command);
|
|
307
|
+
// Commander sets `agent: false` (boolean) when `--no-agent` is passed,
|
|
308
|
+
// because `--no-agent` is the negation of `--agent <target>`. Guard
|
|
309
|
+
// against this: if agent is falsy (false or empty string) default to
|
|
310
|
+
// the CLI default so runInstall never receives a non-string target.
|
|
311
|
+
const resolvedAgent = cmdOpts.agent && typeof cmdOpts.agent === 'string' ? cmdOpts.agent : defaultAgent;
|
|
312
|
+
const isNoAgent = cmdOpts.noAgent === true || cmdOpts.agent === false;
|
|
313
|
+
// Fix 5: detect conflict when both --no-agent and --agent <target> appear
|
|
314
|
+
// in the raw args. Thread the flag into runInit so it can emit the [warn]
|
|
315
|
+
// via deps.stderr (testable) instead of process.stderr directly.
|
|
316
|
+
//
|
|
317
|
+
// Commander only populates `rawArgs` on the ROOT command passed to
|
|
318
|
+
// parseAsync; subcommands have an empty array. Walk up to the root
|
|
319
|
+
// so we always inspect the full argv.
|
|
320
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
321
|
+
let root = command;
|
|
322
|
+
while (root.parent)
|
|
323
|
+
root = root.parent;
|
|
324
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
325
|
+
const rawArgs = root.rawArgs ?? process.argv;
|
|
326
|
+
const rawArgConflict = rawArgs.some((a) => a === '--no-agent') &&
|
|
327
|
+
rawArgs.some((a) => a === '--agent' || a.startsWith('--agent='));
|
|
328
|
+
const opts = {
|
|
329
|
+
...common,
|
|
330
|
+
apiKey: cmdOpts.apiKey,
|
|
331
|
+
fromEnv: Boolean(cmdOpts.fromEnv),
|
|
332
|
+
agent: resolvedAgent,
|
|
333
|
+
noAgent: isNoAgent,
|
|
334
|
+
force: Boolean(cmdOpts.force),
|
|
335
|
+
dir: cmdOpts.dir,
|
|
336
|
+
yes: Boolean(cmdOpts.yes),
|
|
337
|
+
rawArgConflict,
|
|
338
|
+
};
|
|
339
|
+
// When --yes is supplied without a key source, force isTTY=false so
|
|
340
|
+
// runInit emits exit 5 with a clear message rather than hanging on a
|
|
341
|
+
// prompt in a headless CI environment where a TTY fd happens to be open.
|
|
342
|
+
const effectiveDeps = {
|
|
343
|
+
...deps,
|
|
344
|
+
...(opts.yes && !opts.apiKey && !opts.fromEnv ? { isTTY: false } : {}),
|
|
345
|
+
};
|
|
346
|
+
await runInit(opts, effectiveDeps);
|
|
347
|
+
});
|
|
348
|
+
return cmd;
|
|
349
|
+
}
|
|
350
|
+
//# sourceMappingURL=init.js.map
|