@testsprite/testsprite-cli 0.15.0 → 0.17.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 (207) hide show
  1. package/README.md +53 -141
  2. package/dist/commands/agent.d.ts +12 -4
  3. package/dist/commands/agent.js +55 -65
  4. package/dist/commands/auth.d.ts +6 -10
  5. package/dist/commands/auth.js +44 -56
  6. package/dist/commands/ci.d.ts +23 -100
  7. package/dist/commands/ci.js +297 -489
  8. package/dist/commands/completion.js +2 -1
  9. package/dist/commands/conversation.d.ts +27 -0
  10. package/dist/commands/conversation.js +702 -0
  11. package/dist/commands/doctor.d.ts +5 -1
  12. package/dist/commands/doctor.js +130 -34
  13. package/dist/commands/init.d.ts +4 -45
  14. package/dist/commands/init.js +116 -68
  15. package/dist/commands/project-env.d.ts +62 -2
  16. package/dist/commands/project-env.js +426 -53
  17. package/dist/commands/project-sign-in.d.ts +0 -48
  18. package/dist/commands/project-sign-in.js +1 -224
  19. package/dist/commands/project.d.ts +15 -186
  20. package/dist/commands/project.js +93 -921
  21. package/dist/commands/result.d.ts +10 -0
  22. package/dist/commands/result.js +215 -0
  23. package/dist/commands/schedule.d.ts +0 -29
  24. package/dist/commands/schedule.js +47 -97
  25. package/dist/commands/test.d.ts +315 -1824
  26. package/dist/commands/test.js +1962 -13733
  27. package/dist/commands/testlist.d.ts +128 -5
  28. package/dist/commands/testlist.js +269 -329
  29. package/dist/commands/tunnel.d.ts +2 -2
  30. package/dist/commands/tunnel.js +43 -41
  31. package/dist/commands/usage.d.ts +12 -45
  32. package/dist/commands/usage.js +51 -131
  33. package/dist/index.js +189 -108
  34. package/dist/lib/agent-detect.js +9 -5
  35. package/dist/lib/agent-targets.d.ts +21 -2
  36. package/dist/lib/agent-targets.js +88 -11
  37. package/dist/lib/args.d.ts +13 -0
  38. package/dist/lib/args.js +49 -0
  39. package/dist/lib/basic-auth.d.ts +3 -0
  40. package/dist/lib/basic-auth.js +15 -0
  41. package/dist/lib/billing-refusal.js +4 -3
  42. package/dist/lib/ci-linkage.d.ts +4 -82
  43. package/dist/lib/ci-linkage.js +4 -157
  44. package/dist/lib/ci-run.js +1 -1
  45. package/dist/lib/client-factory.d.ts +10 -2
  46. package/dist/lib/client-factory.js +38 -26
  47. package/dist/lib/commit-signal.d.ts +65 -0
  48. package/dist/lib/commit-signal.js +305 -0
  49. package/dist/lib/concurrency-limiter.d.ts +6 -0
  50. package/dist/lib/concurrency-limiter.js +29 -0
  51. package/dist/lib/config.js +10 -5
  52. package/dist/lib/conflict-reason.d.ts +31 -4
  53. package/dist/lib/conflict-reason.js +38 -4
  54. package/dist/lib/conversation/answers.d.ts +9 -0
  55. package/dist/lib/conversation/answers.js +49 -0
  56. package/dist/lib/conversation/api.d.ts +71 -0
  57. package/dist/lib/conversation/api.js +150 -0
  58. package/dist/lib/conversation/change.d.ts +31 -0
  59. package/dist/lib/conversation/change.js +124 -0
  60. package/dist/lib/conversation/context.d.ts +19 -0
  61. package/dist/lib/conversation/context.js +70 -0
  62. package/dist/lib/conversation/environment.d.ts +15 -0
  63. package/dist/lib/conversation/environment.js +33 -0
  64. package/dist/lib/conversation/follow.d.ts +24 -0
  65. package/dist/lib/conversation/follow.js +42 -0
  66. package/dist/lib/conversation/render.d.ts +33 -0
  67. package/dist/lib/conversation/render.js +315 -0
  68. package/dist/lib/conversation/title.d.ts +2 -0
  69. package/dist/lib/conversation/title.js +18 -0
  70. package/dist/lib/conversation/types.d.ts +156 -0
  71. package/dist/lib/conversation/types.js +6 -0
  72. package/dist/lib/credentials.js +67 -11
  73. package/dist/lib/cron.d.ts +1 -1
  74. package/dist/lib/cron.js +2 -2
  75. package/dist/lib/dispatch-stop.d.ts +20 -0
  76. package/dist/lib/dispatch-stop.js +30 -0
  77. package/dist/lib/download.d.ts +71 -0
  78. package/dist/lib/download.js +274 -0
  79. package/dist/lib/dry-run/fetch.d.ts +10 -0
  80. package/dist/lib/dry-run/fetch.js +20 -0
  81. package/dist/lib/dry-run/samples.d.ts +6 -34
  82. package/dist/lib/dry-run/samples.js +389 -751
  83. package/dist/lib/environment-tunnel.d.ts +16 -26
  84. package/dist/lib/environment-tunnel.js +161 -157
  85. package/dist/lib/errors.d.ts +20 -4
  86. package/dist/lib/errors.js +36 -16
  87. package/dist/lib/facade.d.ts +7 -29
  88. package/dist/lib/facade.js +7 -36
  89. package/dist/lib/failing-fe-resolver.d.ts +13 -58
  90. package/dist/lib/failing-fe-resolver.js +47 -132
  91. package/dist/lib/first-suite-hint.d.ts +16 -22
  92. package/dist/lib/first-suite-hint.js +38 -47
  93. package/dist/lib/gh-output.d.ts +76 -21
  94. package/dist/lib/gh-output.js +171 -90
  95. package/dist/lib/git-utils.d.ts +56 -0
  96. package/dist/lib/git-utils.js +212 -0
  97. package/dist/lib/github-context.d.ts +2 -0
  98. package/dist/lib/github-context.js +40 -8
  99. package/dist/lib/history-retention.d.ts +6 -2
  100. package/dist/lib/history-retention.js +10 -7
  101. package/dist/lib/http.d.ts +58 -134
  102. package/dist/lib/http.js +352 -271
  103. package/dist/lib/interrupt.d.ts +14 -8
  104. package/dist/lib/interrupt.js +28 -10
  105. package/dist/lib/junit-report.d.ts +60 -4
  106. package/dist/lib/junit-report.js +209 -32
  107. package/dist/lib/local-target.d.ts +3 -3
  108. package/dist/lib/local-target.js +3 -3
  109. package/dist/lib/output.d.ts +0 -29
  110. package/dist/lib/output.js +10 -33
  111. package/dist/lib/pagination.d.ts +2 -5
  112. package/dist/lib/pagination.js +2 -5
  113. package/dist/lib/presigned-url.d.ts +22 -0
  114. package/dist/lib/presigned-url.js +90 -0
  115. package/dist/lib/prompt.js +36 -2
  116. package/dist/lib/proxy.js +2 -1
  117. package/dist/lib/redact.d.ts +2 -2
  118. package/dist/lib/redact.js +3 -4
  119. package/dist/lib/removed-commands.d.ts +18 -0
  120. package/dist/lib/removed-commands.js +154 -0
  121. package/dist/lib/render-error.d.ts +31 -6
  122. package/dist/lib/render-error.js +88 -25
  123. package/dist/lib/response-schemas.d.ts +38 -30
  124. package/dist/lib/response-schemas.js +210 -207
  125. package/dist/lib/result/api.d.ts +24 -0
  126. package/dist/lib/result/api.js +28 -0
  127. package/dist/lib/result/evidence.d.ts +71 -0
  128. package/dist/lib/result/evidence.js +420 -0
  129. package/dist/lib/result/render.d.ts +20 -0
  130. package/dist/lib/result/render.js +194 -0
  131. package/dist/lib/result/types.d.ts +122 -0
  132. package/dist/lib/result/types.js +19 -0
  133. package/dist/lib/run-output.d.ts +275 -0
  134. package/dist/lib/run-output.js +227 -0
  135. package/dist/lib/run-render.d.ts +101 -0
  136. package/dist/lib/run-render.js +183 -0
  137. package/dist/lib/run-wait.d.ts +192 -0
  138. package/dist/lib/run-wait.js +452 -0
  139. package/dist/lib/runs.types.d.ts +134 -367
  140. package/dist/lib/runs.types.js +0 -14
  141. package/dist/lib/secret-file.d.ts +1 -1
  142. package/dist/lib/secret-file.js +11 -2
  143. package/dist/lib/skill-nudge.d.ts +7 -27
  144. package/dist/lib/skill-nudge.js +9 -37
  145. package/dist/lib/target-path.d.ts +15 -0
  146. package/dist/lib/target-path.js +35 -0
  147. package/dist/lib/target-url-advisory.d.ts +19 -0
  148. package/dist/lib/target-url-advisory.js +31 -0
  149. package/dist/lib/target-url-preflight.d.ts +9 -0
  150. package/dist/lib/target-url-preflight.js +214 -106
  151. package/dist/lib/target-url.d.ts +1 -1
  152. package/dist/lib/target-url.js +6 -16
  153. package/dist/lib/telemetry.d.ts +32 -12
  154. package/dist/lib/telemetry.js +39 -8
  155. package/dist/lib/terminal-text.d.ts +41 -0
  156. package/dist/lib/terminal-text.js +127 -0
  157. package/dist/lib/testlist.types.d.ts +16 -8
  158. package/dist/lib/testlist.types.js +1 -1
  159. package/dist/lib/text-equality.d.ts +2 -0
  160. package/dist/lib/text-equality.js +5 -0
  161. package/dist/lib/text-file.d.ts +16 -0
  162. package/dist/lib/text-file.js +41 -0
  163. package/dist/lib/text-table.d.ts +46 -0
  164. package/dist/lib/text-table.js +72 -4
  165. package/dist/lib/ticker.d.ts +9 -2
  166. package/dist/lib/ticker.js +16 -3
  167. package/dist/lib/transport-failure.d.ts +22 -0
  168. package/dist/lib/transport-failure.js +126 -0
  169. package/dist/lib/tunnel-session.d.ts +7 -1
  170. package/dist/lib/tunnel-session.js +22 -9
  171. package/dist/lib/update-check.js +3 -2
  172. package/dist/lib/url-template.d.ts +43 -0
  173. package/dist/lib/url-template.js +151 -0
  174. package/dist/lib/validate.d.ts +0 -64
  175. package/dist/lib/validate.js +2 -131
  176. package/dist/lib/version-notice.js +4 -3
  177. package/dist/lib/wait-exit.d.ts +37 -2
  178. package/dist/lib/wait-exit.js +88 -30
  179. package/dist/lib/workspace-status.js +10 -2
  180. package/dist/version.d.ts +1 -1
  181. package/dist/version.js +1 -1
  182. package/package.json +3 -4
  183. package/skills/testsprite-ci.skill.md +48 -18
  184. package/skills/testsprite-onboard.skill.md +66 -151
  185. package/skills/testsprite-verify.codex.md +54 -56
  186. package/skills/testsprite-verify.skill.md +194 -358
  187. package/dist/lib/browser.d.ts +0 -6
  188. package/dist/lib/browser.js +0 -54
  189. package/dist/lib/bundle.d.ts +0 -234
  190. package/dist/lib/bundle.js +0 -781
  191. package/dist/lib/deprecate.d.ts +0 -10
  192. package/dist/lib/deprecate.js +0 -13
  193. package/dist/lib/flaky.d.ts +0 -91
  194. package/dist/lib/flaky.js +0 -71
  195. package/dist/lib/plan-poll.d.ts +0 -171
  196. package/dist/lib/plan-poll.js +0 -441
  197. package/dist/lib/plans.types.d.ts +0 -130
  198. package/dist/lib/plans.types.js +0 -31
  199. package/dist/lib/poll.d.ts +0 -100
  200. package/dist/lib/poll.js +0 -290
  201. package/dist/lib/rate-throttle.d.ts +0 -49
  202. package/dist/lib/rate-throttle.js +0 -75
  203. package/dist/lib/run-progress.d.ts +0 -41
  204. package/dist/lib/run-progress.js +0 -56
  205. package/dist/lib/v3-advisory.d.ts +0 -55
  206. package/dist/lib/v3-advisory.js +0 -74
  207. package/schemas/plan.schema.json +0 -61
@@ -1,22 +1,17 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { createReadStream, readFileSync, statSync } from 'node:fs';
3
- import { basename, extname } from 'node:path';
4
- import { Readable } from 'node:stream';
5
- import { Command, Option } from 'commander';
6
- import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, resolveRequestTimeoutMs, } from '../lib/client-factory.js';
2
+ import { Command } from 'commander';
3
+ import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, } from '../lib/client-factory.js';
7
4
  import { resolveProfileName } from '../lib/config.js';
8
- import { ApiError, InterruptError, RequestTimeoutError } from '../lib/errors.js';
5
+ import { ApiError } from '../lib/errors.js';
9
6
  import { firstSuiteNextSteps } from '../lib/first-suite-hint.js';
10
- import { globalShutdown } from '../lib/interrupt.js';
11
- import { assertStoredLocalTargetListening, buildLocalTargetUrl, parseStoredLocalTarget, } from '../lib/local-target.js';
12
7
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
13
- import { readSecretFileGuarded } from '../lib/secret-file.js';
14
- import { assertNotLocal } from '../lib/target-url.js';
8
+ import { CLI_PROJECT_LIST_SCHEMA, CLI_PROJECT_SCHEMA } from '../lib/response-schemas.js';
9
+ import { terminalWidth } from '../lib/ticker.js';
15
10
  import { renderTextTable, resolveTextColumns } from '../lib/text-table.js';
16
11
  import { assertIdempotencyKey } from '../lib/validate.js';
17
12
  import { fetchSinglePage, paginate, validatePaginationFlags, } from '../lib/pagination.js';
18
13
  import { createProjectEnvCommand } from './project-env.js';
19
- import { createProjectSignInCommand } from './project-sign-in.js';
14
+ import { terminalSafe, terminalSafeLine, terminalSafeWriter } from '../lib/terminal-text.js';
20
15
  /** Attribute names are interpolated into CSS selectors by the engine — keep them plain. */
21
16
  const TEST_ID_ATTRIBUTE_NAME = /^[A-Za-z_][\w.:-]*$/;
22
17
  const TEST_ID_ATTRIBUTES_MAX = 10;
@@ -63,14 +58,16 @@ export async function runList(opts, deps = {}) {
63
58
  // for --max-items, treat that as a "give me one page and the cursor"
64
59
  // request — same shape AWS CLI ships. Otherwise auto-page.
65
60
  const useSinglePage = opts.pageSize !== undefined && opts.maxItems === undefined;
61
+ const fetchPage = async ({ pageSize, cursor }) => client.get('/projects', {
62
+ query: { pageSize, cursor },
63
+ schema: CLI_PROJECT_LIST_SCHEMA,
64
+ });
66
65
  let page;
67
66
  if (useSinglePage) {
68
- page = await fetchSinglePage(client, '/projects', paginationFlags.pageSize, opts.startingToken);
67
+ page = await fetchSinglePage(client, '/projects', paginationFlags.pageSize, opts.startingToken, {}, CLI_PROJECT_LIST_SCHEMA);
69
68
  }
70
69
  else {
71
- page = await paginate(async ({ pageSize, cursor }) => client.get('/projects', {
72
- query: { pageSize, cursor },
73
- }), paginationFlags);
70
+ page = await paginate(fetchPage, paginationFlags);
74
71
  }
75
72
  out.print(page, data => {
76
73
  const p = data;
@@ -81,7 +78,9 @@ export async function runList(opts, deps = {}) {
81
78
  export async function runGet(opts, deps = {}) {
82
79
  const out = makeOutput(opts.output, deps);
83
80
  const client = makeClient(opts, deps);
84
- const project = await client.get(`/projects/${encodeURIComponent(opts.projectId)}`);
81
+ const project = await client.get(`/projects/${encodeURIComponent(opts.projectId)}`, {
82
+ schema: CLI_PROJECT_SCHEMA,
83
+ });
85
84
  out.print(project, data => renderProjectText(data));
86
85
  return project;
87
86
  }
@@ -91,66 +90,29 @@ export function resolveCreatedProjectId(r) {
91
90
  }
92
91
  export async function runCreate(opts, deps = {}) {
93
92
  const out = makeOutput(opts.output, deps);
94
- const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
93
+ const stderr = terminalSafeWriter(deps.stderr);
95
94
  // P1-2: validate idempotency key before sending as an HTTP header.
96
95
  // Non-ASCII chars cause a ByteString TypeError at the transport layer
97
96
  // (exit 10 UNAVAILABLE) — fail fast with a clear exit 5 instead.
98
97
  assertIdempotencyKey(opts.idempotencyKey);
99
98
  // P1-3: client-side length checks matching server limits.
100
- // Whitespace-only / empty rejection (parity with `test create`'s requireString;
101
- // a truthy `--name " "` otherwise creates a blank-named project on the backend).
99
+ // Whitespace-only / empty rejection: a truthy `--name " "` otherwise
100
+ // creates a blank-named project on the backend.
102
101
  if (opts.name === undefined || opts.name.trim().length === 0) {
103
102
  throw localValidationError('--name is required and must not be empty or whitespace-only');
104
103
  }
105
- if (opts.password !== undefined && opts.password.trim().length === 0) {
106
- throw localValidationError('--password must not be empty or whitespace-only');
107
- }
108
- if (opts.password !== undefined && opts.passwordFile !== undefined) {
109
- stderr('Warning: --password takes precedence; --password-file was ignored.');
110
- }
111
104
  if (opts.name.length > 200) {
112
105
  throw localValidationError('--name must be at most 200 characters');
113
106
  }
114
- // `--description` is not supported on projects — no project entity stores a
115
- // description, and the backend rejects it with a 422. Fail fast client-side
116
- // with an actionable message instead of a wasted round trip.
117
- if (opts.description !== undefined) {
118
- throw localValidationError('--description is not supported for projects; omit it (test-level descriptions are set on `test create`)');
119
- }
120
- if (opts.local !== undefined && opts.type !== 'frontend') {
121
- throw localValidationError('--local projects are frontend-only');
122
- }
123
- const localTarget = parseStoredLocalTarget({
124
- local: opts.local,
125
- localHost: opts.localHost,
126
- url: opts.targetUrl,
127
- });
128
- // A loopback --url is the same stored target as --local, so it gets the same
129
- // refusal before anything is sent.
130
- if (localTarget && opts.type !== 'frontend') {
131
- throw localValidationError('a --url on this machine (localhost, 127.0.0.1, [::1]) is frontend-only; give a backend project a public URL');
132
- }
133
- const targetUrl = opts.targetUrl ??
134
- (localTarget ? buildLocalTargetUrl(localTarget.host, localTarget.port) : undefined);
135
- // Keep the existing public-address guard for targets a loopback tunnel cannot reach.
136
- if (opts.targetUrl !== undefined && !localTarget) {
137
- assertNotLocal(opts.targetUrl, {
138
- field: 'url',
139
- helpCommand: 'testsprite project create',
140
- hintContext: 'local-project-create',
141
- });
142
- }
143
- if (opts.type === 'frontend' && !targetUrl) {
144
- throw localValidationError('--url is required for --type frontend');
145
- }
146
107
  if (opts.dryRun) {
147
- // This path returns before makeClient() fires the banner, so emit it here
148
- // — otherwise the canned sample can be mistaken for a live response.
108
+ // This path returns without making any dry-run request, so emit the
109
+ // banner here — otherwise the canned sample can be mistaken for a live
110
+ // response.
149
111
  emitDryRunBanner(stderr);
150
112
  const idempotencyKey = opts.idempotencyKey ?? `cli-proj-create-${randomUUID()}`;
151
- // P2-6: gate idempotency-key output behind --verbose/--debug/json (matches
152
- // test create convention). Suppress in plain text interactive mode to reduce
153
- // noise; still available for automation and retry flows.
113
+ // P2-6: gate idempotency-key output behind --verbose/--debug/json. Suppress
114
+ // in plain text interactive mode to reduce noise; still available for
115
+ // automation and retry flows.
154
116
  if (opts.idempotencyKey === undefined &&
155
117
  (opts.output === 'json' || opts.verbose || opts.debug)) {
156
118
  stderr(`idempotency-key: ${idempotencyKey}`);
@@ -163,8 +125,6 @@ export async function runCreate(opts, deps = {}) {
163
125
  id: 'p_dryrun_2026',
164
126
  type: opts.type,
165
127
  name: opts.name,
166
- targetUrl: targetUrl ?? '',
167
- ...(localTarget ? { originMode: 'local' } : {}),
168
128
  createdFrom: 'cli',
169
129
  createdAt: '2026-05-16T00:00:00.000Z',
170
130
  updatedAt: '2026-05-16T00:00:00.000Z',
@@ -172,14 +132,6 @@ export async function runCreate(opts, deps = {}) {
172
132
  out.print(sample, data => renderCreateProjectText(data));
173
133
  return sample;
174
134
  }
175
- if (localTarget) {
176
- await assertStoredLocalTargetListening(localTarget, opts, deps.localPortProbeDeps);
177
- }
178
- // Resolve password: flag > file > none
179
- let password = opts.password;
180
- if (password === undefined && opts.passwordFile !== undefined) {
181
- password = readSecretFileGuarded('password-file', opts.passwordFile);
182
- }
183
135
  const idempotencyKey = opts.idempotencyKey ?? `cli-proj-create-${randomUUID()}`;
184
136
  if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
185
137
  stderr(`idempotency-key: ${idempotencyKey}`);
@@ -187,10 +139,6 @@ export async function runCreate(opts, deps = {}) {
187
139
  const body = {
188
140
  type: opts.type,
189
141
  name: opts.name,
190
- ...(targetUrl !== undefined ? { targetUrl } : {}),
191
- ...(localTarget ? { originMode: 'local' } : {}),
192
- ...(opts.username !== undefined ? { username: opts.username } : {}),
193
- ...(password !== undefined ? { password } : {}),
194
142
  ...(opts.instruction !== undefined ? { instruction: opts.instruction } : {}),
195
143
  ...(opts.testIdAttributes !== undefined ? { testIdAttributes: opts.testIdAttributes } : {}),
196
144
  };
@@ -213,53 +161,11 @@ export async function runCreate(opts, deps = {}) {
213
161
  ...rawCreated,
214
162
  ...(resolvedId !== undefined ? { projectId: resolvedId, id: resolvedId } : {}),
215
163
  };
216
- out.print(created, data => renderCreateProjectText(data, localTarget));
217
- // A backend project created without --url has no default environment URL.
218
- // On the V3 execution path, the shared admission guard (`runProjectGuarded`
219
- // -> `assertProjectEnvNotLocal`, called by every V3 run/rerun/batch entry
220
- // point, including `backendRun`) rejects the FIRST run of any test in the
221
- // project with 400 no-target-resolvable. On the V2 path (`cli-run.service.ts`
222
- // -> `resolveRunPrereqsFE`), this URL resolution is frontend-only and is
223
- // never applied to a backend run, so a V2-routed backend project without a
224
- // URL runs fine — V2 is the only execution path live in production today
225
- // (V3 is dev-only pending its own GA release), so the wording below is
226
- // conditioned on V3 rather than stated as a universal consequence.
227
- // `--url` is intentionally NOT made mandatory here (that would break the
228
- // published --help contract: npm 0.4.0 already ships text saying the URL
229
- // is frontend-only), so this stays advisory-only. The CLI does not call
230
- // GET /me here to check the caller's actual v3Enabled routing before
231
- // deciding whether to print this — an extra round-trip on every create is
232
- // not worth it just to gate a hint — so it points the reader at `auth
233
- // status` (which already renders the routing: v2|v3 line) instead.
234
- // Emitted in EVERY output mode, including --output json: this goes to
235
- // stderr, which never touches JSON stdout, so there is nothing to protect
236
- // by suppressing it (unlike `emitV3RoutingAdvisory`, which withholds
237
- // account-context advisory in JSON mode because a JSON caller can read
238
- // `v3Enabled` directly instead — there is no equivalent structured signal
239
- // for this one). And --output json is precisely the case that needs it
240
- // most: a script or agent creating a project non-interactively has no one
241
- // watching a terminal, so a silent dead-on-arrival project only surfaces
242
- // later as an unexplained 400 on the first run. Same family as the C1
243
- // `--target-url` advisory above (a flag/setup the caller just made has a
244
- // structural consequence) rather than the routing-advisory family.
245
- // Real path only — NOT duplicated into the dry-run branch above, because
246
- // the remedy command below embeds the created project id, and under
247
- // --dry-run that id is the canned `p_dryrun_2026` sample: emitting a
248
- // live-looking fix-it command against a fake resource is exactly what the
249
- // `dashboardUrl` convention (see CLAUDE.md) already decided to suppress.
250
- if (opts.type === 'backend' && !opts.targetUrl) {
251
- stderr(`[advisory] this backend project has no default environment URL. On the V3 execution ` +
252
- `path (check with \`testsprite auth status\`), test runs are rejected with ` +
253
- `no-target-resolvable until one is set. Fix: testsprite project update ` +
254
- `${resolvedId ?? '<project-id>'} --url <url>`);
255
- }
256
- // A new project with no tests is where activation stalls. Point at
257
- // the generate -> accept path (text mode only: a JSON caller already holds
258
- // the id; --dry-run returned above, its id is the canned sample). Printed
259
- // after the URL advisory so a fix-first warning is never buried below it.
260
- // A --local project is skipped: its record above already ends with the
261
- // hand-written-plan next steps.
262
- if (opts.output !== 'json' && resolvedId !== undefined && !localTarget) {
164
+ out.print(created, data => renderCreateProjectText(data));
165
+ // A new project has no environment and no tests yet; one hint names both
166
+ // steps. Text mode only: a JSON caller already holds the id, and --dry-run
167
+ // returned above with a canned one.
168
+ if (opts.output !== 'json' && resolvedId !== undefined) {
263
169
  stderr(firstSuiteNextSteps(resolvedId, opts.type));
264
170
  }
265
171
  return created;
@@ -270,7 +176,7 @@ export function resolveUpdatedProjectId(r) {
270
176
  }
271
177
  export async function runUpdate(opts, deps = {}) {
272
178
  const out = makeOutput(opts.output, deps);
273
- const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
179
+ const stderr = terminalSafeWriter(deps.stderr);
274
180
  // P1-2: validate idempotency key before sending as an HTTP header.
275
181
  assertIdempotencyKey(opts.idempotencyKey);
276
182
  // P1-3: client-side length checks matching server limits.
@@ -279,40 +185,14 @@ export async function runUpdate(opts, deps = {}) {
279
185
  if (opts.name !== undefined && opts.name.trim().length === 0) {
280
186
  throw localValidationError('--name must not be empty or whitespace-only');
281
187
  }
282
- if (opts.password !== undefined && opts.password.trim().length === 0) {
283
- throw localValidationError('--password must not be empty or whitespace-only');
284
- }
285
- if (opts.password !== undefined && opts.passwordFile !== undefined) {
286
- stderr('Warning: --password takes precedence; --password-file was ignored.');
287
- }
288
188
  if (opts.name !== undefined && opts.name.length > 200) {
289
189
  throw localValidationError('--name must be at most 200 characters');
290
190
  }
291
- // A loopback URL and --local shorthand use the same stored-target wire shape.
292
- // The server owns project-type validation on update.
293
- const localTarget = parseStoredLocalTarget({
294
- local: opts.local,
295
- localHost: opts.localHost,
296
- url: opts.targetUrl,
297
- });
298
- const targetUrl = opts.targetUrl ??
299
- (localTarget ? buildLocalTargetUrl(localTarget.host, localTarget.port) : undefined);
300
- if (opts.targetUrl !== undefined && !localTarget) {
301
- assertNotLocal(opts.targetUrl, {
302
- field: 'url',
303
- helpCommand: 'testsprite project update',
304
- hintContext: 'local-project-create',
305
- });
306
- }
307
191
  if (opts.testIdAttributes !== undefined && opts.clearTestIdAttributes) {
308
192
  throw localValidationError('--test-id-attributes and --clear-test-id-attributes are mutually exclusive.');
309
193
  }
310
- const passwordSupplied = opts.password !== undefined || opts.passwordFile !== undefined;
311
194
  const mutableFields = {
312
195
  name: opts.name !== undefined,
313
- targetUrl: targetUrl !== undefined,
314
- username: opts.username !== undefined,
315
- password: passwordSupplied,
316
196
  instruction: opts.instruction !== undefined,
317
197
  testIdAttributes: opts.testIdAttributes !== undefined || opts.clearTestIdAttributes === true,
318
198
  };
@@ -320,8 +200,8 @@ export async function runUpdate(opts, deps = {}) {
320
200
  .filter(([, present]) => present)
321
201
  .map(([field]) => field);
322
202
  if (presentFieldNames.length === 0) {
323
- throw localValidationError('At least one mutable flag is required: --name, --url, --username, --password/--password-file, ' +
324
- '--instruction, --test-id-attributes, or --clear-test-id-attributes.');
203
+ throw localValidationError('At least one mutable flag is required: --name, --instruction, --test-id-attributes, or ' +
204
+ '--clear-test-id-attributes.');
325
205
  }
326
206
  if (opts.dryRun) {
327
207
  // Emit the banner here (this path returns before makeClient() does).
@@ -340,28 +220,15 @@ export async function runUpdate(opts, deps = {}) {
340
220
  updatedFields: presentFieldNames,
341
221
  updatedAt: '2026-05-16T00:00:00.000Z',
342
222
  };
343
- out.print(sample, data => renderUpdateText(data, localTarget));
223
+ out.print(sample, data => renderUpdateText(data));
344
224
  return sample;
345
225
  }
346
- if (localTarget) {
347
- await assertStoredLocalTargetListening(localTarget, opts, deps.localPortProbeDeps);
348
- }
349
- // Resolve password only on the real path. Dry-run must not touch the
350
- // filesystem, even when --password-file is present.
351
- let password = opts.password;
352
- if (password === undefined && opts.passwordFile !== undefined) {
353
- password = readSecretFileGuarded('password-file', opts.passwordFile);
354
- }
355
226
  const idempotencyKey = opts.idempotencyKey ?? `cli-proj-update-${randomUUID()}`;
356
227
  if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
357
228
  stderr(`idempotency-key: ${idempotencyKey}`);
358
229
  }
359
230
  const bodyFields = {
360
231
  name: opts.name,
361
- targetUrl,
362
- originMode: localTarget ? 'local' : undefined,
363
- username: opts.username,
364
- password,
365
232
  instruction: opts.instruction,
366
233
  // `null` clears the list server-side (same convention as `test update --clear-step-timeout`).
367
234
  testIdAttributes: opts.clearTestIdAttributes ? null : opts.testIdAttributes,
@@ -388,7 +255,7 @@ export async function runUpdate(opts, deps = {}) {
388
255
  ? { projectId: resolvedUpdatedId, id: resolvedUpdatedId }
389
256
  : {}),
390
257
  };
391
- out.print(updated, data => renderUpdateText(data, localTarget));
258
+ out.print(updated, data => renderUpdateText(data));
392
259
  return updated;
393
260
  }
394
261
  /**
@@ -406,9 +273,6 @@ export async function runUpdate(opts, deps = {}) {
406
273
  */
407
274
  export async function runDelete(opts, deps = {}) {
408
275
  assertIdempotencyKey(opts.idempotencyKey);
409
- if (opts.projectId === undefined || opts.projectId.trim().length === 0) {
410
- throw localValidationError('<project-id> is required');
411
- }
412
276
  if (!opts.confirm && !opts.dryRun) {
413
277
  throw ApiError.fromEnvelope({
414
278
  error: {
@@ -425,7 +289,7 @@ export async function runDelete(opts, deps = {}) {
425
289
  }
426
290
  const idempotencyKey = opts.idempotencyKey ?? `cli-delete-${randomUUID()}`;
427
291
  if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
428
- const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
292
+ const stderr = terminalSafeWriter(deps.stderr);
429
293
  stderr(`idempotency-key: ${idempotencyKey}`);
430
294
  }
431
295
  const client = makeClient(opts, deps);
@@ -436,528 +300,21 @@ export async function runDelete(opts, deps = {}) {
436
300
  out.print(response, data => renderDeleteText(data));
437
301
  return response;
438
302
  }
439
- // ---------------------------------------------------------------------------
440
- // project credential — set the static backend credential
441
- // ---------------------------------------------------------------------------
442
- const CLI_AUTH_TYPES = ['public', 'Bearer token', 'API key', 'basic token'];
443
- export async function runCredential(opts, deps = {}) {
444
- const out = makeOutput(opts.output, deps);
445
- const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
446
- assertIdempotencyKey(opts.idempotencyKey);
447
- if (!CLI_AUTH_TYPES.includes(opts.authType)) {
448
- throw localValidationError(`--type must be one of: ${CLI_AUTH_TYPES.join(', ')}`);
449
- }
450
- // Resolve the credential value (flag or file). Required for every type
451
- // except `public` (which clears it).
452
- let credential = opts.credential;
453
- if (credential === undefined && opts.credentialFile !== undefined) {
454
- credential = readFileSync(opts.credentialFile, 'utf8').trim();
455
- }
456
- if (opts.authType !== 'public' && (credential === undefined || credential === '')) {
457
- throw localValidationError('--credential (or --credential-file) is required unless --type is "public"');
458
- }
459
- const body = { authType: opts.authType };
460
- if (opts.authType !== 'public' && credential !== undefined)
461
- body.credential = credential;
462
- const idempotencyKey = opts.idempotencyKey ?? `cli-proj-cred-${randomUUID()}`;
463
- if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
464
- stderr(`idempotency-key: ${idempotencyKey}`);
465
- }
466
- if (opts.dryRun) {
467
- const sample = {
468
- projectId: opts.projectId,
469
- authType: opts.authType,
470
- rewroteCount: 0,
471
- };
472
- out.print(sample, data => renderCredentialText(data));
473
- return sample;
474
- }
475
- const client = makeClient(opts, deps);
476
- const res = await client.put(`/projects/${encodeURIComponent(opts.projectId)}/credential`, { body, headers: { 'idempotency-key': idempotencyKey } });
477
- out.print(res, data => renderCredentialText(data));
478
- return res;
479
- }
480
- function renderCredentialText(r) {
481
- return [
482
- `projectId ${r.projectId}`,
483
- `authType ${r.authType}`,
484
- `rewroteCount ${r.rewroteCount}`,
485
- ].join('\n');
486
- }
487
- // ---------------------------------------------------------------------------
488
- // project auto-auth — configure the recurring-token (auto-refresh) login
489
- // ---------------------------------------------------------------------------
490
- const AUTO_AUTH_METHODS = ['password', 'refresh_token', 'aws_cognito_refresh'];
491
- const AUTO_AUTH_INJECTS = ['bearer', 'header', 'cookie'];
492
- export async function runAutoAuth(opts, deps = {}) {
493
- const out = makeOutput(opts.output, deps);
494
- const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
495
- assertIdempotencyKey(opts.idempotencyKey);
496
- if (!AUTO_AUTH_METHODS.includes(opts.method)) {
497
- throw localValidationError(`--method must be one of: ${AUTO_AUTH_METHODS.join(', ')}`);
498
- }
499
- if (!AUTO_AUTH_INJECTS.includes(opts.inject)) {
500
- throw localValidationError(`--inject must be one of: ${AUTO_AUTH_INJECTS.join(', ')}`);
501
- }
502
- // Resolve secrets from --*-file variants so they stay out of shell history.
503
- const password = opts.password ??
504
- (opts.passwordFile !== undefined ? readFileSync(opts.passwordFile, 'utf8').trim() : undefined);
505
- const clientSecret = opts.clientSecret ??
506
- (opts.clientSecretFile !== undefined
507
- ? readFileSync(opts.clientSecretFile, 'utf8').trim()
508
- : undefined);
509
- const refreshToken = opts.refreshToken ??
510
- (opts.refreshTokenFile !== undefined
511
- ? readFileSync(opts.refreshTokenFile, 'utf8').trim()
512
- : undefined);
513
- const enabled = opts.disable !== true;
514
- const body = { enabled, method: opts.method, inject: opts.inject };
515
- const maybe = (k, v) => {
516
- if (v !== undefined)
517
- body[k] = v;
518
- };
519
- maybe('injectKey', opts.injectKey);
520
- maybe('loginUrl', opts.loginUrl);
521
- maybe('loginMethod', opts.loginMethod);
522
- maybe('loginContentType', opts.loginContentType);
523
- maybe('loginBodyTemplate', opts.loginBodyTemplate);
524
- maybe('username', opts.username);
525
- maybe('password', password);
526
- maybe('tokenPath', opts.tokenPath);
527
- maybe('tokenEndpoint', opts.tokenEndpoint);
528
- maybe('clientId', opts.clientId);
529
- maybe('clientSecret', clientSecret);
530
- maybe('refreshToken', refreshToken);
531
- maybe('scope', opts.scope);
532
- maybe('region', opts.region);
533
- const idempotencyKey = opts.idempotencyKey ?? `cli-proj-autoauth-${randomUUID()}`;
534
- if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
535
- stderr(`idempotency-key: ${idempotencyKey}`);
536
- }
537
- if (opts.dryRun) {
538
- const sample = {
539
- projectId: opts.projectId,
540
- enabled,
541
- method: opts.method,
542
- inject: opts.inject,
543
- };
544
- out.print(sample, data => renderAutoAuthText(data));
545
- return sample;
546
- }
547
- const client = makeClient(opts, deps);
548
- const res = await client.put(`/projects/${encodeURIComponent(opts.projectId)}/auto-auth`, { body, headers: { 'idempotency-key': idempotencyKey } });
549
- out.print(res, data => renderAutoAuthText(data));
550
- return res;
551
- }
552
- function renderAutoAuthText(r) {
553
- const lines = [
554
- `projectId ${r.projectId}`,
555
- `enabled ${r.enabled}`,
556
- `method ${r.method}`,
557
- `inject ${r.inject}`,
558
- ];
559
- if (r.lastRefreshError) {
560
- lines.push(`lastRefreshError ${r.lastRefreshError}`);
561
- }
562
- // A disabled result after a write means the trial login failed — call it out
563
- // so the user doesn't assume auto-auth is live.
564
- if (!r.enabled) {
565
- lines.push('note auto-auth was stored but is DISABLED — the trial login failed. Fix the credentials (e.g. a valid refresh token) and re-run.');
566
- }
567
- return lines.join('\n');
568
- }
569
- // ---------------------------------------------------------------------------
570
- // project docs upload
571
- // ---------------------------------------------------------------------------
572
- /**
573
- * CLI-facing role flags → wire enum. Default is `api-doc` (stated in help);
574
- * no inference from project type in v1 (design §3.4).
575
- */
576
- const DOC_ROLES = { 'api-doc': 'API_DOC', prd: 'PRD' };
577
- /**
578
- * MIME type sent in step 1 and echoed on the step-2 PUT. The backend signs
579
- * `ContentType` into the presigned URL when supplied, so the PUT's
580
- * `Content-Type` header must be byte-identical to what step 1 declared —
581
- * both come from this one lookup, so they cannot drift.
582
- */
583
- const DOC_CONTENT_TYPES = {
584
- '.json': 'application/json',
585
- '.yaml': 'application/yaml',
586
- '.yml': 'application/yaml',
587
- '.md': 'text/markdown',
588
- '.markdown': 'text/markdown',
589
- '.txt': 'text/plain',
590
- '.pdf': 'application/pdf',
591
- };
592
- const DEFAULT_DOC_CONTENT_TYPE = 'application/octet-stream';
593
- /**
594
- * `project docs upload <file>` — upload an API spec or PRD as a project
595
- * source so plan generation has inputs to feed on (closes the API-project
596
- * cold start at `no_processed_inputs`).
597
- *
598
- * Three-step flow against the docs facade routes:
599
- *
600
- * 1. `POST /projects/{id}/docs/upload-url` — mints a one-hour presigned
601
- * S3 PUT URL plus the S3 key to register afterwards.
602
- * 2. HTTP PUT of the file bytes to the presigned URL — **streamed**
603
- * (`createReadStream` → web stream), never buffering the whole file.
604
- * This request goes straight to S3: no facade base URL, no API key.
605
- * 3. `POST /projects/{id}/docs` — registers the S3 object with its role
606
- * and display name, which starts processing + embedding.
607
- *
608
- * Reading the local file as INPUT is allowed by DR-21 (the no-local-OUTPUTS
609
- * rule); nothing is ever written back to disk.
610
- *
611
- * Failure modes are deliberately distinguished (design non-negotiable): a
612
- * step-2 failure names the presigned PUT and the fix (re-running mints a
613
- * fresh URL — they expire); a step-3 failure preserves the server envelope
614
- * and says the upload already succeeded (re-running is safe: the server
615
- * upserts the document by S3 key, so no duplicate is created).
616
- */
617
- export async function runDocsUpload(opts, deps = {}) {
618
- const out = makeOutput(opts.output, deps);
619
- const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
620
- assertIdempotencyKey(opts.idempotencyKey);
621
- const projectId = requireDocsProjectId(opts.projectId, deps);
622
- const roleFlag = opts.role ?? 'api-doc';
623
- if (!(roleFlag in DOC_ROLES)) {
624
- throw localValidationError('--role must be api-doc (API spec, the default) or prd (product requirements document)');
625
- }
626
- const role = DOC_ROLES[roleFlag];
627
- if (opts.name !== undefined && opts.name.trim().length === 0) {
628
- throw localValidationError('--name must not be empty or whitespace-only');
629
- }
630
- if (opts.name !== undefined && opts.name.length > 255) {
631
- throw localValidationError('--name must be at most 255 characters');
632
- }
633
- if (opts.file === undefined || opts.file.trim().length === 0) {
634
- throw localValidationError('<file> is required');
635
- }
636
- // Size + existence sanity via stat only — the dry-run contract is "nothing
637
- // read beyond a stat", and the real path opens the file exactly once, in
638
- // the streamed PUT below.
639
- let stat;
640
- try {
641
- stat = statSync(opts.file);
642
- }
643
- catch (cause) {
644
- const code = cause.code;
645
- if (code === 'ENOENT') {
646
- throw localValidationError(`file does not exist: ${opts.file}`);
647
- }
648
- throw localValidationError(`cannot stat file ${opts.file}: ${cause.message ?? String(cause)}`);
649
- }
650
- if (!stat.isFile()) {
651
- throw localValidationError(`${opts.file} is not a regular file (is it a directory?)`);
652
- }
653
- if (stat.size === 0) {
654
- throw localValidationError(`file is empty (0 bytes), nothing to upload: ${opts.file}`);
655
- }
656
- const fileName = basename(opts.file);
657
- if (fileName.length > 255) {
658
- throw localValidationError('the file name (basename) must be at most 255 characters — rename the file ' +
659
- '(--name only changes the display name, not the stored file name)');
660
- }
661
- const displayName = opts.name ?? fileName;
662
- const contentType = DOC_CONTENT_TYPES[extname(fileName).toLowerCase()] ?? DEFAULT_DOC_CONTENT_TYPE;
663
- const projectPath = encodeURIComponent(projectId);
664
- if (opts.dryRun) {
665
- // Same inline early-exit family as `test delete-batch --dry-run`: the
666
- // command's dry-run contract (zero network, stat only, print the plan)
667
- // cannot be expressed through canned fetch samples — step 2 would have
668
- // to PUT somewhere. The `docsUploadUrl`/`docsRegister` entries in
669
- // `samples.ts` are shape-guards/documentation, not consumed here.
670
- emitDryRunBanner(stderr);
671
- const plan = {
672
- dryRun: true,
673
- projectId,
674
- file: opts.file,
675
- fileName,
676
- displayName,
677
- role,
678
- contentType,
679
- size: stat.size,
680
- steps: [
681
- `POST /projects/${projectId}/docs/upload-url — mint a presigned S3 PUT URL for ${fileName} (${contentType})`,
682
- `PUT ${stat.size} bytes to the presigned URL (streamed from disk, never buffered)`,
683
- `POST /projects/${projectId}/docs — register ${displayName} as ${role}; starts processing + embedding`,
684
- ],
685
- };
686
- out.print(plan, data => renderDocsUploadPlanText(data));
687
- return plan;
688
- }
689
- const idempotencyKey = opts.idempotencyKey ?? `cli-docs-upload-${randomUUID()}`;
690
- if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
691
- stderr(`idempotency-key: ${idempotencyKey}`);
692
- }
693
- const client = makeClient(opts, deps);
694
- // ── Step 1 of 3: mint the presigned upload URL ────────────────────────────
695
- const minted = await client.post(`/projects/${projectPath}/docs/upload-url`, { body: { fileName, contentType } });
696
- // ── Step 2 of 3: stream the file bytes to S3 ──────────────────────────────
697
- // Straight to the presigned host with the raw fetch impl — NOT through
698
- // HttpClient, which would attach the facade base URL and leak the API key
699
- // to S3. Content-Length comes from the stat: S3 rejects chunked
700
- // transfer-encoding on presigned PUTs, and Node's fetch uses the explicit
701
- // header to keep identity framing with a streamed body.
702
- const fetchImpl = deps.fetchImpl ?? globalThis.fetch.bind(globalThis);
703
- // A remote facade must mint a non-local https URL.
704
- assertSafePresignedUploadUrl(minted.uploadUrl, client.resolvedBaseUrl);
705
- // Same flag > TESTSPRITE_REQUEST_TIMEOUT_MS > default resolution (and 1-600s
706
- // clamp) as makeHttpClient — this leg bypasses HttpClient, so resolve here.
707
- const requestTimeoutMs = resolveRequestTimeoutMs(opts, deps.env ?? process.env);
708
- const controller = new AbortController();
709
- const timer = setTimeout(() => controller.abort(), requestTimeoutMs);
710
- // Compose the shutdown signal into the PUT abort (manual listeners, house
711
- // style — no AbortSignal.any) and arm the graceful scope for the upload's
712
- // duration, so Ctrl-C during a long PUT takes the honest detach path
713
- // instead of being unabortable.
714
- const shutdown = deps.shutdown ?? globalShutdown;
715
- const shutdownSignal = shutdown.signal;
716
- const onShutdownAbort = () => controller.abort(shutdownSignal.reason);
717
- const disarm = shutdown.arm();
718
- if (shutdownSignal.aborted)
719
- onShutdownAbort();
720
- else
721
- shutdownSignal.addEventListener('abort', onShutdownAbort, { once: true });
722
- let putResponse;
723
- try {
724
- putResponse = await fetchImpl(minted.uploadUrl, {
725
- method: 'PUT',
726
- headers: { 'content-type': contentType, 'content-length': String(stat.size) },
727
- body: Readable.toWeb(createReadStream(opts.file)),
728
- duplex: 'half',
729
- // assertSafePresignedUploadUrl vets the MINTED url, but a
730
- // default `redirect: 'follow'` would let a 3xx from that host resend
731
- // the request to an unvetted Location (e.g. a 303 → 169.254.169.254) —
732
- // an SSRF-shaped hop the guard never sees. A real S3 presigned PUT never
733
- // redirects, so refuse: the thrown TypeError falls through to the catch
734
- // below as a normal `presigned_put_failed` (no new error reason).
735
- redirect: 'error',
736
- signal: controller.signal,
737
- });
738
- }
739
- catch (cause) {
740
- // Interrupt outranks the timeout mapping: a Ctrl-C-aborted fetch must
741
- // surface as InterruptError (exit 130/143), never as a timeout.
742
- if (cause instanceof InterruptError)
743
- throw cause;
744
- if (shutdownSignal.aborted)
745
- throw shutdownSignal.reason;
746
- // Any other abort here is ours (the per-request timer): map to the CLI's
747
- // typed exit-7 timeout, same contract as HttpClient's per-request timeout.
748
- if (isAbortError(cause)) {
749
- throw new RequestTimeoutError(requestTimeoutMs);
750
- }
751
- throw presignedPutError(`network error before S3 responded: ${describeCause(cause)}`, minted.expiresInSeconds);
752
- }
753
- finally {
754
- clearTimeout(timer);
755
- shutdownSignal.removeEventListener('abort', onShutdownAbort);
756
- disarm();
757
- }
758
- if (!putResponse.ok) {
759
- const snippet = (await putResponse.text().catch(() => '')).slice(0, 300);
760
- throw presignedPutError(`S3 returned HTTP ${putResponse.status}${snippet ? ` — ${snippet}` : ''}`, minted.expiresInSeconds);
761
- }
762
- // ── Step 3 of 3: register the uploaded object ─────────────────────────────
763
- let registered;
764
- try {
765
- registered = await client.post(`/projects/${projectPath}/docs`, {
766
- body: { s3Key: minted.s3Key, displayName, docRole: role },
767
- headers: { 'idempotency-key': idempotencyKey },
768
- });
769
- }
770
- catch (cause) {
771
- if (cause instanceof ApiError)
772
- throw registerStepError(cause);
773
- // A register timeout needs the same step-3 context — it is precisely the
774
- // case where the caller can't tell whether the register landed. Class and
775
- // exit 7 are preserved; only the text gains the upload-succeeded /
776
- // safe-to-re-run explanation.
777
- if (cause instanceof RequestTimeoutError) {
778
- cause.message =
779
- `Document register timed out (step 3 of 3) — the S3 upload succeeded, and the ` +
780
- `register may or may not have landed. ${cause.message} Re-running the whole command ` +
781
- `is safe: the server upserts the document by its S3 key (no duplicate is created; a PRD re-register re-runs the embedding compute, but the embedding charge is idempotent per document — never billed twice).`;
782
- throw cause;
783
- }
784
- throw cause;
785
- }
786
- const result = {
787
- resourceId: registered.resourceId,
788
- displayName: registered.displayName ?? displayName,
789
- role: registered.docRole ?? role,
790
- size: stat.size,
791
- processStatus: registered.processStatus,
792
- };
793
- out.print(result, data => renderDocsUploadText(data));
794
- return result;
795
- }
796
- function isAbortError(cause) {
797
- return cause instanceof Error && cause.name === 'AbortError';
798
- }
799
- function describeCause(cause) {
800
- if (!(cause instanceof Error))
801
- return String(cause);
802
- // undici wraps network failures as `TypeError: fetch failed` with the
803
- // useful detail on `.cause` — surface both.
804
- const nested = cause.cause;
805
- const nestedMsg = nested instanceof Error ? ` (${nested.message})` : '';
806
- return `${cause.message}${nestedMsg}`;
807
- }
808
- /**
809
- * Defense-in-depth on the server-minted presigned URL.
810
- *
811
- * A REMOTE facade must mint a non-local `https:` URL; a localhost/private or
812
- * plain-http mint from a remote facade is exactly the anomaly to reject
813
- * (compromised/misconfigured facade or an active MITM) — the PUT would
814
- * otherwise send the user's file wherever that URL points, before any bytes
815
- * leave the machine. A facade that is ITSELF loopback (dev rig, localhost
816
- * e2e) is a deliberate operator configuration and is trusted to mint local
817
- * URLs — and ONLY loopback qualifies: the gate is a positive, fail-closed
818
- * check, because gating on "anything `assertNotLocal` dislikes" would
819
- * silently disable the guard for an unparsable base URL or a user-settable
820
- * private-range endpoint (`--endpoint-url https://10.1.2.3`). Literal checks
821
- * only (same scope as `assertNotLocal`); no host allow-listing by design.
822
- *
823
- * Known residual: a loopback facade that is really a TUNNEL to a remote
824
- * backend (`ssh -L`, a localhost corporate proxy) is trusted here even though
825
- * the real conversation is remote and MITM-able upstream. This is inherent to
826
- * "loopback facade = trusted dev rig" and accepted — the CLI cannot tell a
827
- * dev rig from a tunnel by the base URL alone.
828
- */
829
- function assertSafePresignedUploadUrl(uploadUrl, facadeBaseUrl) {
830
- if (isLoopbackFacade(facadeBaseUrl))
831
- return;
832
- const reject = (reason) => {
833
- throw ApiError.fromEnvelope({
834
- error: {
835
- code: 'VALIDATION_ERROR',
836
- message: `Refusing the presigned upload URL the server returned: ${reason}.`,
837
- nextAction: 'No bytes were uploaded. This can indicate a misconfigured or intercepted API ' +
838
- 'endpoint — verify --endpoint-url / TESTSPRITE_API_URL and retry.',
839
- requestId: 'local',
840
- details: { field: 'uploadUrl', reason: 'unsafe_presigned_url' },
841
- },
842
- });
843
- };
844
- let parsed;
845
- try {
846
- parsed = new URL(uploadUrl);
847
- }
848
- catch {
849
- return reject('it is not a valid URL');
850
- }
851
- if (parsed.protocol !== 'https:')
852
- return reject('it is not https');
853
- if (isLocalUrl(uploadUrl))
854
- return reject('it points at a local/private address');
855
- }
856
- /** True when `assertNotLocal` rejects the URL (localhost, RFC1918, link-local,
857
- * metadata, non-http(s), unparsable). Fail-closed in the REJECTION direction
858
- * only — used to refuse a suspicious mint, never to grant trust (that side
859
- * is `isLoopbackFacade`). */
860
- function isLocalUrl(url) {
861
- try {
862
- assertNotLocal(url, {
863
- field: 'upload-url',
864
- helpCommand: 'testsprite project docs upload',
865
- });
866
- return false;
867
- }
868
- catch {
869
- return true;
870
- }
871
- }
872
- /**
873
- * The facade-trust gate for `assertSafePresignedUploadUrl`.
874
- * Positive and narrow — only an explicitly-loopback facade (`localhost`,
875
- * a `127.0.0.0/8` literal, or `[::1]`) is trusted to mint local upload URLs.
876
- * Anything else — including an unparsable base URL or a private-range
877
- * endpoint — leaves the guard ON.
878
- */
879
- function isLoopbackFacade(url) {
880
- let parsed;
881
- try {
882
- parsed = new URL(url);
883
- }
884
- catch {
885
- return false;
886
- }
887
- // `localhost.` is the fully-qualified form of `localhost` (RFC 6761).
888
- const host = parsed.hostname.toLowerCase().replace(/\.$/, '');
889
- if (host === 'localhost')
890
- return true;
891
- if (/^127\.\d+\.\d+\.\d+$/.test(host))
892
- return true;
893
- return host === '[::1]';
894
- }
895
- /**
896
- * Step-2 failure: the presigned PUT to S3. Distinguished from a register
897
- * failure per the design non-negotiable — the fix is different (re-running
898
- * re-mints the URL; nothing was registered, so nothing is half-done).
899
- */
900
- function presignedPutError(detail, expiresInSeconds) {
901
- return new ApiError({
902
- code: 'UNAVAILABLE',
903
- message: `Presigned S3 upload failed (step 2 of 3): ${detail}`,
904
- nextAction: 'The document was NOT registered. Re-run the command — each run mints a fresh ' +
905
- `upload URL (presigned URLs expire, this one after ${Math.round(expiresInSeconds / 60)} minutes).`,
906
- requestId: 'local',
907
- details: { reason: 'presigned_put_failed' },
908
- });
909
- }
910
- /**
911
- * Step-3 failure: register. The server envelope (code, exit, requestId,
912
- * details) passes through unchanged; only the text gains step context so
913
- * the caller knows the upload itself already landed and a re-run is safe
914
- * (the server upserts the document by S3 key — no duplicate).
915
- */
916
- function registerStepError(cause) {
917
- return new ApiError({
918
- code: cause.code,
919
- message: `Document register failed (step 3 of 3) — the S3 upload succeeded, but the document is not registered yet. ${cause.message}`,
920
- nextAction: `${cause.nextAction ? `${cause.nextAction} ` : ''}` +
921
- 'Re-running the whole command is safe: the same file re-uploads and the server ' +
922
- 'upserts the document by its S3 key (no duplicate is created; a PRD re-register re-runs the embedding compute, but the embedding charge is idempotent per document — never billed twice).',
923
- requestId: cause.requestId,
924
- details: cause.details,
925
- }, cause.httpStatus, cause.retryAfterMs);
926
- }
927
- function formatDocSize(bytes) {
928
- if (bytes < 1024)
929
- return `${bytes} B`;
930
- if (bytes < 1024 * 1024)
931
- return `${Math.round(bytes / 1024)} KB`;
932
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
933
- }
934
- function renderDocsUploadText(r) {
935
- return [
936
- `uploaded ${r.displayName} (${formatDocSize(r.size)}) — processing started`,
937
- 'note: generation can use this source once processing and embedding finish',
938
- ' (check with `testsprite test plan generate` — it says if inputs are still processing)',
939
- ].join('\n');
940
- }
941
- function renderDocsUploadPlanText(p) {
942
- return [
943
- `would upload ${p.file} (${formatDocSize(p.size)}) to project ${p.projectId} as ${p.role}:`,
944
- ...p.steps.map((step, i) => ` ${i + 1}. ${step}`),
945
- ].join('\n');
946
- }
947
303
  export function createProjectCommand(deps = {}) {
948
304
  const project = new Command('project').description('Manage TestSprite projects');
949
305
  project
950
306
  .command('list')
307
+ .summary('List projects visible to the API key')
951
308
  .description('List projects visible to the API key\n' +
952
309
  '\nExit codes:\n' +
953
310
  ' 0 success\n' +
954
311
  ' 3 auth error\n' +
955
312
  ' 5 validation error (e.g., bad --page-size)\n' +
956
313
  ' 10 transport/network failure (UNAVAILABLE) — retry the command')
957
- .option('--page-size <n>', 'service page-size hint (1-100, default 25)')
314
+ .option('--page-size <n>', 'page size (1-100, default 25); alone it returns one page plus a next --starting-token (add --max-items to auto-page)')
958
315
  .option('--starting-token <token>', 'opaque cursor from a previous list response')
959
316
  .option('--max-items <n>', 'stop after this many items across auto-paged pages')
960
- .option('--columns <list>', 'select/reorder text table columns (comma-separated keys)')
317
+ .option('--columns <list>', 'select/reorder text table columns (comma-separated keys: id, name, type, from, org, url, created, defaultenv, envs)')
961
318
  .option('--no-header', 'suppress the text table header row')
962
319
  .addHelpText('after', GLOBAL_OPTS_HINT)
963
320
  .action(async (cmdOpts, command) => {
@@ -984,19 +341,10 @@ export function createProjectCommand(deps = {}) {
984
341
  });
985
342
  project
986
343
  .command('create')
987
- .description('Create a new project')
344
+ .description('Create a project; add where it runs with `project env create`')
988
345
  .option('--type <frontend|backend>', 'project type (required)')
989
346
  .option('--name <name>', 'project name (required)')
990
- .option('--url <url>', 'target URL (public http/https or a loopback http origin with an explicit port; required for frontend unless --local is used; also required for backend on the V3 execution ' +
991
- 'path — see `auth status` for your routing)')
992
- .option('--local <port>', 'shorthand for --url http://localhost:<port> (1-65535; excludes --url; runs open a tunnel automatically)')
993
- .addOption(new Option('--local-host <host>', 'deprecated loopback host override; requires --local').hideHelp())
994
- .option('--skip-preflight', 'skip the local TCP listener check before project creation')
995
- .option('--description <text>', 'not supported — projects have no description (test-level descriptions are set on `test create`)')
996
- .option('--username <user>', 'optional auth username')
997
- .option('--password <pw>', 'optional auth password (use --password-file for non-interactive)')
998
- .option('--password-file <path>', 'read password from file instead of inline flag')
999
- .option('--instruction <text>', 'optional FE plan-gen instruction hint')
347
+ .option('--instruction <text>', 'extra instructions: facts and rules the agent keeps in mind when it explores the app, writes tests or runs them')
1000
348
  .option('--test-id-attributes <list>', 'comma-separated DOM attributes the engine should prefer as locators, highest priority first ' +
1001
349
  '(e.g. data-element,data-testid). Unique values are exported as page.locator(\'[attr="…"]\').')
1002
350
  .option('--idempotency-key <token>', 'opaque idempotency token. Defaults to a UUIDv4 minted per invocation.')
@@ -1014,14 +362,6 @@ export function createProjectCommand(deps = {}) {
1014
362
  ...resolveCommonOptions(command, deps.env),
1015
363
  type,
1016
364
  name: cmdOpts.name,
1017
- targetUrl: cmdOpts.url,
1018
- local: cmdOpts.local,
1019
- localHost: cmdOpts.localHost,
1020
- skipPreflight: cmdOpts.skipPreflight,
1021
- description: cmdOpts.description,
1022
- username: cmdOpts.username,
1023
- password: cmdOpts.password,
1024
- passwordFile: cmdOpts.passwordFile,
1025
365
  instruction: cmdOpts.instruction,
1026
366
  testIdAttributes: cmdOpts.testIdAttributes !== undefined
1027
367
  ? parseTestIdAttributesFlag(cmdOpts.testIdAttributes, 'test-id-attributes')
@@ -1031,16 +371,9 @@ export function createProjectCommand(deps = {}) {
1031
371
  });
1032
372
  project
1033
373
  .command('update <project-id>')
1034
- .description('Update project metadata')
374
+ .description("Update a project's name, extra instructions or test-id attributes")
1035
375
  .option('--name <name>', 'new project name')
1036
- .option('--url <url>', 'new target URL (public http/https, or a loopback http origin with an explicit port)')
1037
- .option('--local <port>', 'shorthand for --url http://localhost:<port> (1-65535; excludes --url; frontend only)')
1038
- .addOption(new Option('--local-host <host>', 'deprecated loopback host override; requires --local').hideHelp())
1039
- .option('--skip-preflight', 'skip the local TCP listener check before the update')
1040
- .option('--username <user>', 'new auth username')
1041
- .option('--password <pw>', 'new auth password')
1042
- .option('--password-file <path>', 'read new password from file')
1043
- .option('--instruction <text>', 'new FE plan-gen instruction hint')
376
+ .option('--instruction <text>', 'replace the current instructions (read them with project get)')
1044
377
  .option('--test-id-attributes <list>', 'comma-separated DOM attributes the engine should prefer as locators, highest priority first ' +
1045
378
  '(e.g. data-element,data-testid); replaces the current list')
1046
379
  .option('--clear-test-id-attributes', 'remove the test-id attribute list (engine falls back to data-testid)', false)
@@ -1051,13 +384,6 @@ export function createProjectCommand(deps = {}) {
1051
384
  ...resolveCommonOptions(command, deps.env),
1052
385
  projectId,
1053
386
  name: cmdOpts.name,
1054
- targetUrl: cmdOpts.url,
1055
- local: cmdOpts.local,
1056
- localHost: cmdOpts.localHost,
1057
- skipPreflight: cmdOpts.skipPreflight,
1058
- username: cmdOpts.username,
1059
- password: cmdOpts.password,
1060
- passwordFile: cmdOpts.passwordFile,
1061
387
  instruction: cmdOpts.instruction,
1062
388
  testIdAttributes: cmdOpts.testIdAttributes !== undefined
1063
389
  ? parseTestIdAttributesFlag(cmdOpts.testIdAttributes, 'test-id-attributes')
@@ -1068,6 +394,7 @@ export function createProjectCommand(deps = {}) {
1068
394
  });
1069
395
  project
1070
396
  .command('delete <project-id>')
397
+ .summary('Permanently delete a project (requires --confirm)')
1071
398
  .description('Permanently delete a project and everything under it (sub-projects,\n' +
1072
399
  'their tests, and backend fixtures). Requires --confirm.\n' +
1073
400
  '\nExit codes:\n' +
@@ -1086,115 +413,9 @@ export function createProjectCommand(deps = {}) {
1086
413
  idempotencyKey: cmdOpts.idempotencyKey,
1087
414
  }, deps);
1088
415
  });
1089
- project
1090
- .command('credential <project-id>')
1091
- .description('Set the static backend credential injected into every backend test\n' +
1092
- '(Bearer token / API key / Basic token / public). Free tier.')
1093
- .requiredOption('--type <type>', 'public | "Bearer token" | "API key" | "basic token"')
1094
- .option('--credential <value>', 'credential value (required unless --type public)')
1095
- .option('--credential-file <path>', 'read the credential value from a file')
1096
- .option('--idempotency-key <token>', 'opaque idempotency token. Defaults to a UUIDv4 minted per invocation.')
1097
- .addHelpText('after', GLOBAL_OPTS_HINT)
1098
- .action(async (projectId, cmdOpts, command) => {
1099
- await runCredential({
1100
- ...resolveCommonOptions(command, deps.env),
1101
- projectId,
1102
- authType: cmdOpts.type,
1103
- credential: cmdOpts.credential,
1104
- credentialFile: cmdOpts.credentialFile,
1105
- idempotencyKey: cmdOpts.idempotencyKey,
1106
- }, deps);
1107
- });
1108
- project
1109
- .command('auto-auth <project-id>')
1110
- .description('Configure the recurring-token (auto-refresh login) for backend tests (Pro).\n' +
1111
- 'A fresh token is fetched on each run and injected into every backend test.')
1112
- .requiredOption('--method <method>', 'password | refresh_token | aws_cognito_refresh')
1113
- .requiredOption('--inject <where>', 'bearer | header | cookie')
1114
- .option('--disable', 'turn auto-auth off (keeps stored config)')
1115
- .option('--inject-key <name>', 'header/cookie name when --inject is header/cookie')
1116
- // password method
1117
- .option('--login-url <url>', 'login endpoint (method=password)')
1118
- .option('--login-method <verb>', 'POST | PUT (method=password)')
1119
- .option('--login-content-type <ct>', 'application/json | application/x-www-form-urlencoded')
1120
- .option('--login-body-template <tpl>', 'login body template with {{username}}/{{password}}')
1121
- .option('--username <user>', 'login username (method=password)')
1122
- .option('--password <pw>', 'login password (method=password)')
1123
- .option('--password-file <path>', 'read login password from a file')
1124
- .option('--token-path <jsonpath>', 'JSONPath to the token in the login response')
1125
- // refresh_token method
1126
- .option('--token-endpoint <url>', 'OAuth token endpoint (method=refresh_token)')
1127
- .option('--client-id <id>', 'OAuth client id')
1128
- .option('--client-secret <secret>', 'OAuth client secret')
1129
- .option('--client-secret-file <path>', 'read OAuth client secret from a file')
1130
- .option('--refresh-token <token>', 'OAuth/Cognito refresh token')
1131
- .option('--refresh-token-file <path>', 'read the refresh token from a file')
1132
- .option('--scope <scope>', 'OAuth scope')
1133
- // aws_cognito_refresh method
1134
- .option('--region <region>', "AWS region (method=aws_cognito_refresh, e.g. 'us-east-1')")
1135
- .option('--idempotency-key <token>', 'opaque idempotency token. Defaults to a UUIDv4 minted per invocation.')
1136
- .addHelpText('after', GLOBAL_OPTS_HINT)
1137
- .action(async (projectId, cmdOpts, command) => {
1138
- await runAutoAuth({
1139
- ...resolveCommonOptions(command, deps.env),
1140
- projectId,
1141
- disable: cmdOpts.disable,
1142
- method: cmdOpts.method,
1143
- inject: cmdOpts.inject,
1144
- injectKey: cmdOpts.injectKey,
1145
- loginUrl: cmdOpts.loginUrl,
1146
- loginMethod: cmdOpts.loginMethod,
1147
- loginContentType: cmdOpts.loginContentType,
1148
- loginBodyTemplate: cmdOpts.loginBodyTemplate,
1149
- username: cmdOpts.username,
1150
- password: cmdOpts.password,
1151
- passwordFile: cmdOpts.passwordFile,
1152
- tokenPath: cmdOpts.tokenPath,
1153
- tokenEndpoint: cmdOpts.tokenEndpoint,
1154
- clientId: cmdOpts.clientId,
1155
- clientSecret: cmdOpts.clientSecret,
1156
- clientSecretFile: cmdOpts.clientSecretFile,
1157
- refreshToken: cmdOpts.refreshToken,
1158
- refreshTokenFile: cmdOpts.refreshTokenFile,
1159
- scope: cmdOpts.scope,
1160
- region: cmdOpts.region,
1161
- idempotencyKey: cmdOpts.idempotencyKey,
1162
- }, deps);
1163
- });
1164
- const docs = new Command('docs').description('Manage project documents — the sources plan generation feeds on');
1165
- docs
1166
- .command('upload <file>')
1167
- .description('Upload an API spec or PRD as a project source. Three steps:\n' +
1168
- 'mint a presigned S3 URL, stream the file bytes to it, register the\n' +
1169
- 'document — which starts processing + embedding. The local file is\n' +
1170
- 'only read; nothing is written back to disk.\n' +
1171
- '\nExit codes:\n' +
1172
- ' 0 upload registered (processing started)\n' +
1173
- ' 3 auth error\n' +
1174
- ' 4 project not found (or not accessible in this workspace)\n' +
1175
- ' 5 validation error (missing/empty file, bad --role)\n' +
1176
- ' 7 request timeout (also: backend predates the docs routes)\n' +
1177
- ' 10 presigned S3 PUT failed — re-run to mint a fresh URL')
1178
- .option('--project <id>', 'project id the document belongs to (required)')
1179
- .option('--role <role>', 'document role: api-doc (API spec, default) | prd')
1180
- .option('--name <display-name>', 'display name for the document (default: file basename)')
1181
- .option('--idempotency-key <token>', 'opaque idempotency token. Defaults to a UUIDv4 minted per invocation.')
1182
- .addHelpText('after', GLOBAL_OPTS_HINT)
1183
- .action(async (file, cmdOpts, command) => {
1184
- await runDocsUpload({
1185
- ...resolveCommonOptions(command, deps.env),
1186
- file,
1187
- projectId: cmdOpts.project,
1188
- role: cmdOpts.role,
1189
- name: cmdOpts.name,
1190
- idempotencyKey: cmdOpts.idempotencyKey,
1191
- }, deps);
1192
- });
1193
- project.addCommand(docs);
1194
- // `project env <verb>` — the per-project environment surface (credentials,
1195
- // URL, default). Own module; `deps` threaded so tests inject.
416
+ // `project env <verb>` — the per-project environment surface (URL, sign-in,
417
+ // backend credentials, default). Own module; `deps` threaded so tests inject.
1196
418
  project.addCommand(createProjectEnvCommand(deps));
1197
- project.addCommand(createProjectSignInCommand(deps));
1198
419
  return project;
1199
420
  }
1200
421
  function parseFlag(raw, flagName) {
@@ -1249,34 +470,29 @@ function makeOutput(mode, deps) {
1249
470
  const PROJECT_LIST_COLUMNS = [
1250
471
  {
1251
472
  header: 'ID',
1252
- width: rows => Math.max(2, ...rows.map(project => project.id.length)),
473
+ width: rows => Math.max(2, ...rows.map(project => terminalWidth(project.id))),
1253
474
  render: project => project.id,
1254
475
  },
1255
476
  {
1256
477
  header: 'NAME',
1257
- width: rows => Math.max(4, ...rows.map(project => project.name.length)),
478
+ width: rows => Math.max(4, ...rows.map(project => terminalWidth(project.name))),
1258
479
  render: project => project.name,
1259
480
  },
1260
481
  { header: 'TYPE', width: 8, render: project => project.type },
1261
482
  { header: 'FROM', width: 6, render: project => project.createdFrom },
1262
483
  {
1263
484
  header: 'ORG',
1264
- width: rows => Math.max(3, ...rows.map(project => (project.orgName ?? project.orgId ?? '').length)),
485
+ width: rows => Math.max(3, ...rows.map(project => terminalWidth(project.orgName ?? project.orgId ?? ''))),
1265
486
  render: project => project.orgName ?? project.orgId ?? '',
1266
487
  },
1267
- {
1268
- header: 'URL',
1269
- width: rows => Math.max(3, ...rows.map(project => renderProjectUrl(project).length)),
1270
- render: renderProjectUrl,
1271
- },
1272
488
  {
1273
489
  header: 'CREATED',
1274
- width: rows => Math.max(7, ...rows.map(project => project.createdAt.length)),
490
+ width: rows => Math.max(7, ...rows.map(project => terminalWidth(project.createdAt))),
1275
491
  render: project => project.createdAt,
1276
492
  },
1277
493
  {
1278
494
  header: 'DEFAULT ENV',
1279
- width: rows => Math.max(11, ...rows.map(project => (project.defaultEnvironment ?? '-').length)),
495
+ width: rows => Math.max(11, ...rows.map(project => terminalWidth(project.defaultEnvironment ?? '-'))),
1280
496
  render: project => project.defaultEnvironment ?? '-',
1281
497
  },
1282
498
  {
@@ -1285,24 +501,24 @@ const PROJECT_LIST_COLUMNS = [
1285
501
  render: project => project.environmentCount?.toString() ?? '-',
1286
502
  },
1287
503
  ];
1288
- function renderProjectUrl(project) {
1289
- const url = project.targetUrl ?? '';
1290
- return project.originMode === 'local' ? `${url ? `${url} ` : ''}(Local)` : url;
1291
- }
1292
504
  /**
1293
505
  * Default (no explicit `--columns`) column set. ORG is included only when
1294
- * at least one row carries `orgId`; URL is included when a row is local.
1295
- * Older responses retain the existing default table columns.
506
+ * at least one row carries `orgId`.
1296
507
  */
1297
508
  function defaultProjectListColumns(rows) {
1298
509
  const hasOrgInfo = rows.some(project => project.orgId !== undefined);
1299
- const hasLocalProject = rows.some(project => project.originMode === 'local');
1300
- return PROJECT_LIST_COLUMNS.filter(column => (column.header !== 'ORG' || hasOrgInfo) && (column.header !== 'URL' || hasLocalProject));
510
+ return PROJECT_LIST_COLUMNS.filter(column => column.header !== 'ORG' || hasOrgInfo);
1301
511
  }
1302
- function renderProjectListText(page, options = {}) {
512
+ /**
513
+ * Render `project list`'s text table over a fetched page. Falls back to the
514
+ * default column set (ORG/URL included only when the data carries them).
515
+ * Exported for direct unit coverage of the CJK display-width regression
516
+ * (#369): later columns must not shift when a project name is full-width.
517
+ */
518
+ export function renderProjectListText(page, options = {}) {
1303
519
  if (page.items.length === 0) {
1304
520
  return page.nextToken
1305
- ? `No projects on this page.\nnextToken: ${page.nextToken}`
521
+ ? `No projects on this page.\nnextToken: ${terminalSafeLine(page.nextToken)}`
1306
522
  : 'No projects.';
1307
523
  }
1308
524
  // Explicit --columns: resolve against the FULL master set (so `org` can be
@@ -1316,44 +532,38 @@ function renderProjectListText(page, options = {}) {
1316
532
  }),
1317
533
  ];
1318
534
  if (page.nextToken)
1319
- lines.push('', `nextToken: ${page.nextToken}`);
535
+ lines.push('', `nextToken: ${terminalSafeLine(page.nextToken)}`);
1320
536
  return lines.join('\n');
1321
537
  }
1322
538
  function renderProjectText(p) {
1323
539
  const lines = [
1324
- `id: ${p.id}`,
1325
- `name: ${p.name}`,
1326
- `type: ${p.type}`,
1327
- `createdFrom: ${p.createdFrom}`,
1328
- `createdAt: ${p.createdAt}`,
1329
- `updatedAt: ${p.updatedAt}`,
540
+ `id: ${terminalSafeLine(p.id)}`,
541
+ `name: ${terminalSafeLine(p.name)}`,
542
+ `type: ${terminalSafeLine(p.type)}`,
543
+ `createdFrom: ${terminalSafeLine(p.createdFrom)}`,
544
+ `createdAt: ${terminalSafeLine(p.createdAt)}`,
545
+ `updatedAt: ${terminalSafeLine(p.updatedAt)}`,
1330
546
  ];
1331
547
  if (p.orgId !== undefined) {
1332
- lines.push(`org: ${p.orgName ?? '(name unknown)'} (${p.orgId})`);
548
+ lines.push(`org: ${terminalSafeLine(p.orgName ?? '(name unknown)')} (${terminalSafeLine(p.orgId)})`);
549
+ }
550
+ if (p.instruction !== undefined) {
551
+ lines.push(p.instruction
552
+ ? `instruction:\n ${terminalSafe(p.instruction).replaceAll('\n', '\n ')}`
553
+ : 'instruction: (not set)');
1333
554
  }
1334
555
  if ('defaultEnvironment' in p) {
1335
- lines.push(`defaultEnv: ${p.defaultEnvironment ?? '-'}`);
556
+ lines.push(`defaultEnv: ${terminalSafeLine(p.defaultEnvironment ?? '-')}`);
1336
557
  }
1337
558
  if ('environmentCount' in p) {
1338
559
  const count = p.environmentCount;
1339
- lines.push(`envs: ${count}${count !== undefined && count > 0 ? ` (list with: testsprite project env list ${p.id})` : ''}`);
560
+ lines.push(`envs: ${count}${count !== undefined && count > 0 ? ` (list with: testsprite project env list ${terminalSafeLine(p.id)})` : ''}`);
1340
561
  }
1341
- // Presence, not truthiness — see the `targetUrl` docstring on `CliProject`.
1342
- // `'targetUrl' in p` distinguishes "the backend answered 'no URL'" (render the
1343
- // hint) from "this endpoint doesn't report it" (say nothing).
1344
- if ('targetUrl' in p) {
1345
- lines.push(p.targetUrl
1346
- ? `targetUrl: ${renderProjectUrl(p)}`
1347
- : `targetUrl: (not set — set one with: testsprite project update ${p.id} --url <url>)`);
1348
- }
1349
- if (p.originMode === 'local' && !p.targetUrl) {
1350
- lines.push('originMode: local (Local)');
1351
- }
1352
- // Presence-keyed like targetUrl: older backends don't report the field at all.
562
+ // Presence-keyed: older backends don't report the field at all.
1353
563
  if ('testIdAttributes' in p) {
1354
564
  lines.push(p.testIdAttributes && p.testIdAttributes.length > 0
1355
- ? `testIdAttrs: ${p.testIdAttributes.join(', ')} (locator priority, highest first)`
1356
- : `testIdAttrs: (not set — engine default data-testid; set with: testsprite project update ${p.id} --test-id-attributes <list>)`);
565
+ ? `testIdAttrs: ${terminalSafeLine(p.testIdAttributes.join(', '))} (locator priority, highest first)`
566
+ : `testIdAttrs: (not set — engine default data-testid; set with: testsprite project update ${terminalSafeLine(p.id)} --test-id-attributes <list>)`);
1357
567
  }
1358
568
  return lines.join('\n');
1359
569
  }
@@ -1363,70 +573,32 @@ function renderProjectText(p) {
1363
573
  * field is proven reliable) because the create response's id field name and
1364
574
  * `updatedAt` presence are not guaranteed — see `CliCreateProjectResponse`.
1365
575
  */
1366
- function renderCreateProjectText(p, localTarget) {
576
+ function renderCreateProjectText(p) {
1367
577
  const lines = [
1368
- `id: ${resolveCreatedProjectId(p) ?? '(unknown)'}`,
1369
- `name: ${p.name}`,
1370
- `type: ${p.type}`,
1371
- `createdFrom: ${p.createdFrom}`,
1372
- `createdAt: ${p.createdAt}`,
578
+ `id: ${terminalSafeLine(resolveCreatedProjectId(p) ?? '(unknown)')}`,
579
+ `name: ${terminalSafeLine(p.name)}`,
580
+ `type: ${terminalSafeLine(p.type)}`,
581
+ `createdFrom: ${terminalSafeLine(p.createdFrom)}`,
582
+ `createdAt: ${terminalSafeLine(p.createdAt)}`,
1373
583
  ];
1374
584
  if (p.updatedAt !== undefined)
1375
- lines.push(`updatedAt: ${p.updatedAt}`);
1376
- if (localTarget) {
1377
- const projectId = resolveCreatedProjectId(p) ?? '<project-id>';
1378
- const url = buildLocalTargetUrl(localTarget.host, localTarget.port);
1379
- lines.push(`Local project: TestSprite will reach ${url} only through a tunnel from this machine.`, 'Next: write a plan and run it locally:',
1380
- // The only next step a --local project gets (it has no first-suite hint),
1381
- // so it names how to get a plan file. `--plan-from` takes the project from
1382
- // the file and ignores `--project`, hence "set projectId" and no flag.
1383
- ' testsprite test create --plan-template > plan.json', ` In plan.json, set projectId to ${projectId} and edit the steps.`, ' testsprite test create --plan-from plan.json', ' testsprite test run <test-id>', `Portal runs of this project stay blocked (free) until you set a public URL with: testsprite project update ${projectId} --url https://...`);
1384
- }
585
+ lines.push(`updatedAt: ${terminalSafeLine(p.updatedAt)}`);
1385
586
  return lines.join('\n');
1386
587
  }
1387
- function renderUpdateText(r, localTarget) {
588
+ function renderUpdateText(r) {
1388
589
  const lines = [
1389
- `id: ${resolveUpdatedProjectId(r) ?? '(unknown)'}`,
1390
- `updatedFields: ${r.updatedFields?.join(', ') ?? '(none)'}`,
590
+ `id: ${terminalSafeLine(resolveUpdatedProjectId(r) ?? '(unknown)')}`,
591
+ `updatedFields: ${terminalSafeLine(r.updatedFields?.join(', ') ?? '(none)')}`,
1391
592
  ];
1392
593
  if (r.updatedAt !== undefined)
1393
- lines.push(`updatedAt: ${r.updatedAt}`);
1394
- if (r.environment !== undefined) {
1395
- lines.push(`environment: ${r.environment.name} (default)`);
1396
- const labels = {
1397
- 'environment.url': 'Environment URL updated',
1398
- 'environment.credentials': 'Environment credentials updated',
1399
- 'project.name': 'Project name updated',
1400
- 'project.instruction': 'Project instruction updated',
1401
- 'project.testIdAttributes': 'Project test ID attributes updated',
1402
- };
1403
- for (const effect of r.effects ?? []) {
1404
- if (labels[effect])
1405
- lines.push(`effect: ${labels[effect]}`);
1406
- }
1407
- }
1408
- if (localTarget) {
1409
- const url = buildLocalTargetUrl(localTarget.host, localTarget.port);
1410
- lines.push(`Local project: TestSprite will reach ${url} only through a tunnel from this machine.`, 'Run its tests with: testsprite test run <test-id> (the CLI opens a tunnel automatically).');
1411
- }
594
+ lines.push(`updatedAt: ${terminalSafeLine(r.updatedAt)}`);
1412
595
  return lines.join('\n');
1413
596
  }
1414
597
  function renderDeleteText(r) {
1415
- return [`projectId ${r.projectId}`, `deletedAt ${r.deletedAt}`].join('\n');
1416
- }
1417
- /**
1418
- * `--project` resolution for `project docs upload` — mirrors test.ts's
1419
- * resolveProjectId/requireProjectId so `TESTSPRITE_PROJECT_ID` works here the
1420
- * same as on every other command. Flag wins over env.
1421
- */
1422
- function requireDocsProjectId(projectId, deps) {
1423
- const explicit = projectId?.trim();
1424
- if (explicit && explicit.length > 0)
1425
- return explicit;
1426
- const envValue = (deps.env ?? process.env).TESTSPRITE_PROJECT_ID?.trim();
1427
- if (envValue && envValue.length > 0)
1428
- return envValue;
1429
- throw localValidationError('--project <id> is required; pass --project <id> or set TESTSPRITE_PROJECT_ID');
598
+ return [
599
+ `projectId ${terminalSafeLine(r.projectId)}`,
600
+ `deletedAt ${terminalSafeLine(r.deletedAt)}`,
601
+ ].join('\n');
1430
602
  }
1431
603
  /**
1432
604
  * A backend that predates the testIdAttributes field answers a PATCH/POST that