@testsprite/testsprite-cli 0.2.0 → 0.3.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.
Files changed (55) hide show
  1. package/README.md +34 -26
  2. package/dist/commands/agent.d.ts +43 -0
  3. package/dist/commands/agent.js +200 -18
  4. package/dist/commands/auth.js +29 -27
  5. package/dist/commands/doctor.d.ts +49 -0
  6. package/dist/commands/doctor.js +211 -0
  7. package/dist/commands/init.d.ts +1 -1
  8. package/dist/commands/init.js +24 -14
  9. package/dist/commands/project.d.ts +50 -1
  10. package/dist/commands/project.js +252 -43
  11. package/dist/commands/test.d.ts +188 -1
  12. package/dist/commands/test.js +1088 -81
  13. package/dist/commands/usage.js +13 -12
  14. package/dist/index.js +33 -2
  15. package/dist/lib/agent-targets.d.ts +72 -6
  16. package/dist/lib/agent-targets.js +188 -6
  17. package/dist/lib/bundle.d.ts +34 -0
  18. package/dist/lib/bundle.js +44 -10
  19. package/dist/lib/client-factory.d.ts +25 -0
  20. package/dist/lib/client-factory.js +47 -0
  21. package/dist/lib/config.d.ts +2 -0
  22. package/dist/lib/config.js +11 -2
  23. package/dist/lib/credentials.js +10 -1
  24. package/dist/lib/dry-run/samples.d.ts +5 -0
  25. package/dist/lib/dry-run/samples.js +28 -0
  26. package/dist/lib/flaky.d.ts +80 -0
  27. package/dist/lib/flaky.js +76 -0
  28. package/dist/lib/http.d.ts +20 -0
  29. package/dist/lib/http.js +216 -132
  30. package/dist/lib/interrupt.d.ts +61 -0
  31. package/dist/lib/interrupt.js +97 -0
  32. package/dist/lib/junit-report.d.ts +58 -0
  33. package/dist/lib/junit-report.js +210 -0
  34. package/dist/lib/output.d.ts +16 -1
  35. package/dist/lib/output.js +24 -2
  36. package/dist/lib/pagination.d.ts +4 -3
  37. package/dist/lib/pagination.js +34 -6
  38. package/dist/lib/prompt.js +52 -8
  39. package/dist/lib/proxy.d.ts +29 -0
  40. package/dist/lib/proxy.js +30 -0
  41. package/dist/lib/render-error.js +3 -1
  42. package/dist/lib/skill-nudge.d.ts +2 -2
  43. package/dist/lib/skill-nudge.js +13 -4
  44. package/dist/lib/target-url.js +8 -1
  45. package/dist/lib/ticker.d.ts +11 -1
  46. package/dist/lib/ticker.js +33 -1
  47. package/dist/lib/update-check.d.ts +67 -0
  48. package/dist/lib/update-check.js +246 -0
  49. package/dist/version-guard.d.ts +33 -0
  50. package/dist/version-guard.js +39 -0
  51. package/dist/version.d.ts +1 -1
  52. package/dist/version.js +1 -1
  53. package/package.json +3 -2
  54. package/skills/testsprite-onboard.skill.md +21 -0
  55. package/skills/testsprite-verify.skill.md +33 -0
@@ -0,0 +1,211 @@
1
+ /**
2
+ * `testsprite doctor` — one-shot environment diagnostic.
3
+ *
4
+ * Runs a fixed checklist (CLI version, Node.js runtime, active profile, API
5
+ * endpoint, credentials, live connectivity + key validity, and whether the
6
+ * verify skill is installed in the current project) and prints an OK/WARN/FAIL
7
+ * report. Exits non-zero when any check FAILS so it can gate a CI step or an
8
+ * agent preflight (`testsprite doctor && testsprite test run ...`). Warnings
9
+ * (e.g. skill not installed) do not fail the process.
10
+ *
11
+ * Every check is reused from the same helpers the real commands use, so the
12
+ * report reflects exactly what a subsequent command would resolve: `loadConfig`
13
+ * for profile/endpoint/key, `assertValidEndpointUrl` for the endpoint gate,
14
+ * `makeHttpClient` + `GET /me` for connectivity, and `isVerifySkillInstalled`
15
+ * for the skill check.
16
+ */
17
+ import { Command } from 'commander';
18
+ import { assertValidEndpointUrl, makeHttpClient, } from '../lib/client-factory.js';
19
+ import { loadConfig } from '../lib/config.js';
20
+ import { ApiError, CLIError, localValidationError } from '../lib/errors.js';
21
+ import { GLOBAL_OPTS_HINT, Output } from '../lib/output.js';
22
+ import { isVerifySkillInstalled } from '../lib/skill-nudge.js';
23
+ import { VERSION } from '../version.js';
24
+ import { MIN_SUPPORTED_NODE_MAJOR, shouldRejectNodeVersion } from '../version-guard.js';
25
+ export async function runDoctor(opts, deps = {}) {
26
+ const out = makeOutput(opts.output, deps);
27
+ const env = deps.env ?? process.env;
28
+ const cwd = deps.cwd ?? process.cwd();
29
+ const nodeVersion = deps.nodeVersion ?? process.versions.node;
30
+ const config = loadConfig({
31
+ profile: opts.profile,
32
+ endpointUrl: opts.endpointUrl,
33
+ env,
34
+ credentialsPath: deps.credentialsPath,
35
+ });
36
+ const endpointCheck = checkEndpoint(config.apiUrl);
37
+ const hasKey = Boolean(config.apiKey);
38
+ const checks = [
39
+ { name: 'CLI version', status: 'ok', detail: VERSION },
40
+ checkNodeVersion(nodeVersion),
41
+ { name: 'Profile', status: 'ok', detail: config.profile },
42
+ endpointCheck,
43
+ checkCredentials(hasKey, config.profile, opts.dryRun ?? false),
44
+ await checkConnectivity(opts, deps, {
45
+ hasKey,
46
+ endpointOk: endpointCheck.status === 'ok',
47
+ }),
48
+ checkSkill(cwd, deps),
49
+ ];
50
+ const failures = checks.filter(check => check.status === 'fail').length;
51
+ const warnings = checks.filter(check => check.status === 'warn').length;
52
+ const report = { checks, failures, warnings };
53
+ out.print(report, () => renderDoctor(report));
54
+ if (failures > 0) {
55
+ // Non-zero exit so `testsprite doctor && ...` gates a CI step or an agent
56
+ // preflight. The full report already printed above; this line is the stderr
57
+ // summary index.ts renders before exiting 1.
58
+ throw new CLIError(`doctor: ${failures} check(s) failed, ${warnings} warning(s)`, 1);
59
+ }
60
+ return report;
61
+ }
62
+ function checkNodeVersion(nodeVersion) {
63
+ // Reuse the CLI's own runtime guard so the verdict matches exactly what the
64
+ // entrypoint enforces at startup, rather than a divergent hardcoded check.
65
+ // The precise engines floor (20.19+/22.13+/24+) is enforced by npm at install
66
+ // time via .npmrc engine-strict. sourceRef: src/version-guard.ts.
67
+ const rejected = shouldRejectNodeVersion(nodeVersion);
68
+ return {
69
+ name: 'Node.js',
70
+ status: rejected ? 'fail' : 'ok',
71
+ detail: rejected
72
+ ? `v${nodeVersion} is below the required Node ${MIN_SUPPORTED_NODE_MAJOR}; upgrade Node.js`
73
+ : `v${nodeVersion} (>=${MIN_SUPPORTED_NODE_MAJOR} required)`,
74
+ };
75
+ }
76
+ function checkEndpoint(apiUrl) {
77
+ try {
78
+ assertValidEndpointUrl(apiUrl);
79
+ return { name: 'API endpoint', status: 'ok', detail: apiUrl };
80
+ }
81
+ catch {
82
+ return {
83
+ name: 'API endpoint',
84
+ status: 'fail',
85
+ detail: `"${apiUrl}" is not a valid http(s) URL`,
86
+ };
87
+ }
88
+ }
89
+ function checkCredentials(hasKey, profile, dryRun) {
90
+ if (hasKey) {
91
+ // Never print any part of the key (security). Confirm presence only.
92
+ return {
93
+ name: 'Credentials',
94
+ status: 'ok',
95
+ detail: `API key configured (profile "${profile}")`,
96
+ };
97
+ }
98
+ // Under --dry-run no key is expected, so a missing key is not a failure.
99
+ return {
100
+ name: 'Credentials',
101
+ status: dryRun ? 'warn' : 'fail',
102
+ detail: dryRun
103
+ ? 'no API key (not needed under --dry-run)'
104
+ : 'no API key found; run `testsprite setup` (or set TESTSPRITE_API_KEY)',
105
+ };
106
+ }
107
+ function checkSkill(cwd, deps) {
108
+ const installed = isVerifySkillInstalled(cwd, {
109
+ existsSync: deps.existsSync,
110
+ readFileSync: deps.readFileSync,
111
+ });
112
+ return {
113
+ name: 'Verify skill',
114
+ status: installed ? 'ok' : 'warn',
115
+ detail: installed
116
+ ? 'installed in this project'
117
+ : 'not installed here; run `testsprite setup` so your agent verifies its changes',
118
+ };
119
+ }
120
+ async function checkConnectivity(opts, deps, ctx) {
121
+ const name = 'Connectivity';
122
+ if (opts.dryRun)
123
+ return { name, status: 'warn', detail: 'skipped under --dry-run' };
124
+ if (!ctx.hasKey)
125
+ return { name, status: 'warn', detail: 'skipped; no API key to test with' };
126
+ if (!ctx.endpointOk)
127
+ return { name, status: 'warn', detail: 'skipped; endpoint URL is invalid' };
128
+ try {
129
+ const client = makeHttpClient(opts, {
130
+ env: deps.env,
131
+ credentialsPath: deps.credentialsPath,
132
+ fetchImpl: deps.fetchImpl,
133
+ stderr: deps.stderr,
134
+ });
135
+ const me = await client.get('/me');
136
+ const who = me.userId ? ` (userId ${me.userId})` : '';
137
+ return { name, status: 'ok', detail: `reached GET /me, API key accepted${who}` };
138
+ }
139
+ catch (error) {
140
+ if (error instanceof ApiError) {
141
+ if (error.code === 'AUTH_REQUIRED' ||
142
+ error.code === 'AUTH_INVALID' ||
143
+ error.code === 'AUTH_FORBIDDEN') {
144
+ return { name, status: 'fail', detail: `API key rejected (${error.code})` };
145
+ }
146
+ return { name, status: 'fail', detail: `GET /me failed (${error.code})` };
147
+ }
148
+ return {
149
+ name,
150
+ status: 'fail',
151
+ detail: `GET /me failed (${error instanceof Error ? error.message : String(error)})`,
152
+ };
153
+ }
154
+ }
155
+ const STATUS_LABEL = {
156
+ ok: '[OK] ',
157
+ warn: '[WARN]',
158
+ fail: '[FAIL]',
159
+ };
160
+ function renderDoctor(report) {
161
+ const nameWidth = Math.max(...report.checks.map(check => check.name.length));
162
+ const lines = ['TestSprite doctor', ''];
163
+ for (const check of report.checks) {
164
+ lines.push(` ${STATUS_LABEL[check.status]} ${check.name.padEnd(nameWidth)} ${check.detail}`);
165
+ }
166
+ lines.push('');
167
+ lines.push(report.failures === 0 && report.warnings === 0
168
+ ? 'All checks passed.'
169
+ : `${report.failures} failure(s), ${report.warnings} warning(s).`);
170
+ return lines.join('\n');
171
+ }
172
+ export function createDoctorCommand(deps = {}) {
173
+ const cmd = new Command('doctor')
174
+ .description('Diagnose CLI setup: version, Node, profile, endpoint, credentials, connectivity, skill')
175
+ .addHelpText('after', GLOBAL_OPTS_HINT)
176
+ .addHelpText('after', '\nExamples:\n' +
177
+ ' testsprite doctor # run all checks (exit 1 if any fails)\n' +
178
+ ' testsprite doctor --output json # machine-readable report\n' +
179
+ ' testsprite doctor && testsprite test run <id> # gate a command on a healthy setup')
180
+ .action(async (_cmdOpts, command) => {
181
+ await runDoctor(resolveCommonOptions(command), deps);
182
+ });
183
+ return cmd;
184
+ }
185
+ function resolveCommonOptions(command) {
186
+ const globals = command.optsWithGlobals();
187
+ return {
188
+ profile: globals.profile ?? 'default',
189
+ output: globals.output ?? 'text',
190
+ endpointUrl: globals.endpointUrl,
191
+ debug: globals.debug ?? false,
192
+ verbose: globals.verbose ?? false,
193
+ dryRun: globals.dryRun ?? false,
194
+ requestTimeoutMs: parseRequestTimeoutFlag(globals.requestTimeout),
195
+ };
196
+ }
197
+ function parseRequestTimeoutFlag(raw) {
198
+ if (raw === undefined)
199
+ return undefined;
200
+ const seconds = Number(raw);
201
+ if (!Number.isFinite(seconds) || seconds <= 0) {
202
+ // Match the other commands: a malformed --request-timeout is a validation
203
+ // error, not a silently-ignored default.
204
+ throw localValidationError('request-timeout', `must be a positive number of seconds (got "${raw}")`);
205
+ }
206
+ return Math.round(seconds * 1000);
207
+ }
208
+ function makeOutput(mode, deps) {
209
+ return new Output(mode, { stdout: deps.stdout, stderr: deps.stderr });
210
+ }
211
+ //# sourceMappingURL=doctor.js.map
@@ -10,7 +10,7 @@
10
10
  * Hard constraint: orchestrate existing exported primitives; never fork them.
11
11
  */
12
12
  import { Command } from 'commander';
13
- import type { CommonOptions as FactoryCommonOptions } from '../lib/client-factory.js';
13
+ import { type CommonOptions as FactoryCommonOptions } from '../lib/client-factory.js';
14
14
  import type { AuthDeps } from './auth.js';
15
15
  import type { AgentFs } from './agent.js';
16
16
  import type { FetchImpl } from '../lib/http.js';
@@ -10,9 +10,11 @@
10
10
  * Hard constraint: orchestrate existing exported primitives; never fork them.
11
11
  */
12
12
  import { Command } from 'commander';
13
+ import { parseRequestTimeoutFlag, } from '../lib/client-factory.js';
14
+ import { normalizeEnvVar } from '../lib/config.js';
13
15
  import { emitDeprecationNotice } from '../lib/deprecate.js';
14
16
  import { CLIError } from '../lib/errors.js';
15
- import { GLOBAL_OPTS_HINT, Output } from '../lib/output.js';
17
+ import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
16
18
  import { runConfigure, runWhoami } from './auth.js';
17
19
  import { runInstall } from './agent.js';
18
20
  import { TARGETS, DEFAULT_SKILLS } from '../lib/agent-targets.js';
@@ -29,7 +31,7 @@ const DEFAULT_API_URL = 'https://api.testsprite.com';
29
31
  */
30
32
  function resolveReportedEndpoint(opts, deps) {
31
33
  const env = deps.env ?? process.env;
32
- const envApiUrl = env.TESTSPRITE_API_URL?.trim() || undefined;
34
+ const envApiUrl = normalizeEnvVar(env.TESTSPRITE_API_URL);
33
35
  let existing;
34
36
  try {
35
37
  existing = readProfile(opts.profile, { path: deps.credentialsPath })?.apiUrl;
@@ -298,10 +300,26 @@ function renderInitText(data) {
298
300
  }
299
301
  lines.push('');
300
302
  lines.push('Next steps:');
301
- lines.push(' testsprite test list # list tests in the current project');
302
- lines.push(' testsprite agent list # check installed agent targets');
303
+ lines.push(' # 1. Create your first project (frontend example) — prints a projectId');
304
+ lines.push(' testsprite project create --type frontend --name "My App" --url https://your-app.com');
305
+ lines.push('');
303
306
  if (s.agent) {
304
- lines.push(' testsprite agent install --target=<t> # re-install or install additional targets');
307
+ lines.push(' # 2. Generate tests: ask your coding agent (the testsprite-onboard skill is installed),');
308
+ lines.push(' # or create one yourself, then run them (use the projectId from step 1):');
309
+ lines.push(' testsprite test run --all --project <projectId>');
310
+ lines.push('');
311
+ lines.push(' # Manage installed agent skills');
312
+ lines.push(' testsprite agent list');
313
+ lines.push(' testsprite agent install --target=<t> # re-install or install additional targets');
314
+ }
315
+ else {
316
+ lines.push(' # 2. Create a test, then run it (use the projectId from step 1):');
317
+ lines.push(' testsprite test create --project <projectId> ...');
318
+ lines.push(' testsprite test run --all --project <projectId>');
319
+ lines.push(' # Tip: `testsprite agent install` sets up the onboarding skill for your coding agent');
320
+ lines.push('');
321
+ lines.push(' # Manage installed agent skills');
322
+ lines.push(' testsprite agent list');
305
323
  }
306
324
  return lines.join('\n');
307
325
  }
@@ -312,7 +330,7 @@ function resolveCommonOptions(command) {
312
330
  const globals = command.optsWithGlobals();
313
331
  return {
314
332
  profile: globals.profile ?? 'default',
315
- output: globals.output ?? 'text',
333
+ output: resolveOutputMode(globals.output),
316
334
  endpointUrl: globals.endpointUrl,
317
335
  debug: globals.debug ?? false,
318
336
  verbose: globals.verbose ?? false,
@@ -320,14 +338,6 @@ function resolveCommonOptions(command) {
320
338
  requestTimeoutMs: parseRequestTimeoutFlag(globals.requestTimeout),
321
339
  };
322
340
  }
323
- function parseRequestTimeoutFlag(raw) {
324
- if (raw === undefined)
325
- return undefined;
326
- const n = Number(raw);
327
- if (!Number.isFinite(n) || n <= 0)
328
- return undefined;
329
- return Math.round(n * 1000);
330
- }
331
341
  const SETUP_DESCRIPTION = 'Set up TestSprite: configure your API key and install the TestSprite agent skills for your coding agent';
332
342
  /** Attach the onboarding flags shared by `setup` and the `init` alias. */
333
343
  function addSetupOptions(cmd, validTargets, defaultAgent) {
@@ -63,10 +63,59 @@ interface UpdateOptions extends CommonOptions {
63
63
  username?: string;
64
64
  password?: string;
65
65
  passwordFile?: string;
66
- description?: string;
67
66
  instruction?: string;
68
67
  idempotencyKey?: string;
69
68
  }
70
69
  export declare function runUpdate(opts: UpdateOptions, deps?: ProjectDeps): Promise<CliUpdateProjectResponse>;
70
+ export interface CliProjectCredentialResponse {
71
+ projectId: string;
72
+ authType: string;
73
+ rewroteCount: number;
74
+ }
75
+ interface CredentialOptions extends CommonOptions {
76
+ projectId: string;
77
+ authType: string;
78
+ credential?: string;
79
+ credentialFile?: string;
80
+ idempotencyKey?: string;
81
+ }
82
+ export declare function runCredential(opts: CredentialOptions, deps?: ProjectDeps): Promise<CliProjectCredentialResponse>;
83
+ export interface CliProjectAutoAuthResponse {
84
+ projectId: string;
85
+ enabled: boolean;
86
+ method: string;
87
+ inject: string;
88
+ /**
89
+ * Present when the server's trial refresh failed: `enabled` is then `false`
90
+ * and this carries the reason (e.g. a bad refresh token). The config is still
91
+ * stored, but auto-auth won't run until the login succeeds.
92
+ */
93
+ lastRefreshError?: string;
94
+ }
95
+ interface AutoAuthOptions extends CommonOptions {
96
+ projectId: string;
97
+ disable?: boolean;
98
+ method: string;
99
+ inject: string;
100
+ injectKey?: string;
101
+ loginUrl?: string;
102
+ loginMethod?: string;
103
+ loginContentType?: string;
104
+ loginBodyTemplate?: string;
105
+ username?: string;
106
+ password?: string;
107
+ passwordFile?: string;
108
+ tokenPath?: string;
109
+ tokenEndpoint?: string;
110
+ clientId?: string;
111
+ clientSecret?: string;
112
+ clientSecretFile?: string;
113
+ refreshToken?: string;
114
+ refreshTokenFile?: string;
115
+ scope?: string;
116
+ region?: string;
117
+ idempotencyKey?: string;
118
+ }
119
+ export declare function runAutoAuth(opts: AutoAuthOptions, deps?: ProjectDeps): Promise<CliProjectAutoAuthResponse>;
71
120
  export declare function createProjectCommand(deps?: ProjectDeps): Command;
72
121
  export {};