@testsprite/testsprite-cli 0.12.0 → 0.14.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 (113) hide show
  1. package/README.md +59 -49
  2. package/dist/commands/agent.js +16 -13
  3. package/dist/commands/auth.d.ts +19 -0
  4. package/dist/commands/auth.js +60 -24
  5. package/dist/commands/ci.d.ts +86 -1
  6. package/dist/commands/ci.js +436 -5
  7. package/dist/commands/doctor.d.ts +2 -0
  8. package/dist/commands/doctor.js +34 -20
  9. package/dist/commands/init.js +14 -11
  10. package/dist/commands/project-env.d.ts +11 -1
  11. package/dist/commands/project-env.js +408 -70
  12. package/dist/commands/project-sign-in.d.ts +60 -0
  13. package/dist/commands/project-sign-in.js +289 -0
  14. package/dist/commands/project.d.ts +14 -5
  15. package/dist/commands/project.js +110 -70
  16. package/dist/commands/schedule.d.ts +14 -0
  17. package/dist/commands/schedule.js +193 -15
  18. package/dist/commands/test.d.ts +123 -44
  19. package/dist/commands/test.js +2993 -636
  20. package/dist/commands/testlist.d.ts +10 -5
  21. package/dist/commands/testlist.js +217 -47
  22. package/dist/commands/tunnel.d.ts +26 -3
  23. package/dist/commands/tunnel.js +221 -18
  24. package/dist/commands/usage.d.ts +3 -0
  25. package/dist/commands/usage.js +12 -5
  26. package/dist/index.js +39 -50
  27. package/dist/lib/agent-targets.d.ts +3 -3
  28. package/dist/lib/agent-targets.js +2 -2
  29. package/dist/lib/billing-refusal.d.ts +43 -0
  30. package/dist/lib/billing-refusal.js +171 -0
  31. package/dist/lib/bundle.d.ts +5 -0
  32. package/dist/lib/bundle.js +43 -13
  33. package/dist/lib/ci-linkage.d.ts +90 -0
  34. package/dist/lib/ci-linkage.js +181 -0
  35. package/dist/lib/client-factory.d.ts +16 -2
  36. package/dist/lib/client-factory.js +37 -6
  37. package/dist/lib/config.d.ts +17 -0
  38. package/dist/lib/config.js +20 -1
  39. package/dist/lib/conflict-reason.d.ts +27 -3
  40. package/dist/lib/conflict-reason.js +53 -4
  41. package/dist/lib/credentials.js +56 -14
  42. package/dist/lib/dry-run/samples.d.ts +13 -1
  43. package/dist/lib/dry-run/samples.js +104 -7
  44. package/dist/lib/environment-tunnel.d.ts +109 -0
  45. package/dist/lib/environment-tunnel.js +465 -0
  46. package/dist/lib/errors.d.ts +18 -11
  47. package/dist/lib/errors.js +123 -14
  48. package/dist/lib/failing-fe-resolver.d.ts +1 -1
  49. package/dist/lib/failing-fe-resolver.js +3 -3
  50. package/dist/lib/gh-output.d.ts +1 -0
  51. package/dist/lib/gh-output.js +16 -4
  52. package/dist/lib/history-retention.d.ts +8 -0
  53. package/dist/lib/history-retention.js +24 -0
  54. package/dist/lib/http.d.ts +39 -19
  55. package/dist/lib/http.js +46 -24
  56. package/dist/lib/interrupt.d.ts +21 -13
  57. package/dist/lib/interrupt.js +32 -21
  58. package/dist/lib/junit-report.d.ts +18 -4
  59. package/dist/lib/junit-report.js +23 -5
  60. package/dist/lib/local-target.d.ts +14 -4
  61. package/dist/lib/local-target.js +48 -13
  62. package/dist/lib/output.js +15 -1
  63. package/dist/lib/plan-poll.d.ts +11 -11
  64. package/dist/lib/plan-poll.js +15 -16
  65. package/dist/lib/plans.types.d.ts +9 -9
  66. package/dist/lib/plans.types.js +3 -3
  67. package/dist/lib/poll.d.ts +2 -2
  68. package/dist/lib/poll.js +9 -3
  69. package/dist/lib/redact.d.ts +38 -0
  70. package/dist/lib/redact.js +140 -0
  71. package/dist/lib/render-error.d.ts +21 -5
  72. package/dist/lib/render-error.js +44 -0
  73. package/dist/lib/response-schemas.d.ts +54 -12
  74. package/dist/lib/response-schemas.js +88 -7
  75. package/dist/lib/runs.types.d.ts +68 -11
  76. package/dist/lib/secret-file.js +72 -14
  77. package/dist/lib/skill-nudge.d.ts +6 -1
  78. package/dist/lib/skill-nudge.js +32 -5
  79. package/dist/lib/target-url-preflight.d.ts +6 -4
  80. package/dist/lib/target-url-preflight.js +64 -51
  81. package/dist/lib/target-url.js +11 -11
  82. package/dist/lib/telemetry.d.ts +10 -8
  83. package/dist/lib/telemetry.js +24 -17
  84. package/dist/lib/testlist.types.d.ts +1 -0
  85. package/dist/lib/ticker.d.ts +9 -0
  86. package/dist/lib/ticker.js +111 -4
  87. package/dist/lib/tunnel-session.d.ts +16 -4
  88. package/dist/lib/tunnel-session.js +7 -5
  89. package/dist/lib/tunnel.types.d.ts +12 -2
  90. package/dist/lib/tunnel.types.js +2 -2
  91. package/dist/lib/v3-advisory.js +0 -1
  92. package/dist/lib/wait-exit.d.ts +8 -0
  93. package/dist/lib/wait-exit.js +76 -4
  94. package/dist/lib/workspace-status.d.ts +23 -0
  95. package/dist/lib/workspace-status.js +15 -0
  96. package/dist/vendor/tunnel-client/client.d.ts +15 -8
  97. package/dist/vendor/tunnel-client/client.js +477 -407
  98. package/dist/vendor/tunnel-client/config.d.ts +5 -5
  99. package/dist/vendor/tunnel-client/config.js +5 -5
  100. package/dist/vendor/tunnel-client/index.d.ts +4 -4
  101. package/dist/vendor/tunnel-client/index.js +4 -4
  102. package/dist/vendor/tunnel-client/types.d.ts +19 -34
  103. package/dist/vendor/tunnel-client/types.js +1 -0
  104. package/dist/vendor/tunnel-client/ws-compat.d.ts +13 -3
  105. package/dist/vendor/tunnel-client/ws-compat.js +70 -12
  106. package/dist/version-guard.d.ts +7 -1
  107. package/dist/version-guard.js +19 -1
  108. package/dist/version.d.ts +1 -1
  109. package/dist/version.js +1 -1
  110. package/package.json +4 -4
  111. package/skills/testsprite-onboard.skill.md +8 -8
  112. package/skills/testsprite-verify.codex.md +59 -57
  113. package/skills/testsprite-verify.skill.md +53 -38
@@ -0,0 +1,43 @@
1
+ import type { ApiError } from './errors.js';
2
+ /**
3
+ * The workspace gate's three refusals, named as the backend's `GateRefusal`
4
+ * names them — the one set the CLI, MCP, portal and agent all share.
5
+ */
6
+ export type GateRefusal = 'paused' | 'not_entitled' | 'limit_exceeded';
7
+ export interface BillingRefusal {
8
+ /** A gate refusal, or a credit shortfall (reported separately as INSUFFICIENT_CREDITS). */
9
+ reason: GateRefusal | 'insufficient_credits';
10
+ links: {
11
+ pricing: string;
12
+ billing: string;
13
+ };
14
+ nextAction: string;
15
+ lines: string[];
16
+ }
17
+ type BillingInput = Pick<ApiError, 'code' | 'message' | 'nextAction' | 'details'> & {
18
+ apiUrl?: string;
19
+ serverNextAction?: string;
20
+ };
21
+ /** Shared pricing/billing destinations for refusals and history-window notes. */
22
+ export declare function resolveBillingLinks(input: {
23
+ apiUrl?: string;
24
+ billingUrl?: string;
25
+ orgId?: unknown;
26
+ nextAction?: string;
27
+ message?: string;
28
+ }): {
29
+ pricing: string;
30
+ billing: string;
31
+ };
32
+ /**
33
+ * Which gate refusal a FEATURE_GATED `details.reason` is. An absent or empty
34
+ * reason is an older backend that never sent one (historically a plan
35
+ * exclusion). Any other value — `rollout`, the MCP view-only mirror's
36
+ * `mcp_origin`, or one this CLI doesn't know yet — is not a billing refusal:
37
+ * upgrading does nothing for it, so it gets no links and no fallback advice.
38
+ */
39
+ export declare function gateRefusalOf(reason: unknown): GateRefusal | undefined;
40
+ /** True for a paused-workspace reason, including the deprecated `billing_hold`. */
41
+ export declare function isPausedReason(reason: unknown): boolean;
42
+ export declare function classifyBillingRefusal(input: BillingInput): BillingRefusal | undefined;
43
+ export {};
@@ -0,0 +1,171 @@
1
+ import { resolvePortalBase } from './facade.js';
2
+ function hasPlaceholder(url) {
3
+ return (/^(undefined|null)$/i.test(url.hostname) || /\/(?:undefined|null)(?:\/|$)/i.test(url.pathname));
4
+ }
5
+ function portalUrlIn(text, billingOnly = false) {
6
+ for (const match of text.matchAll(/https?:\/\/[^\s<>"'`]+/g)) {
7
+ const candidate = match[0].replace(/[),.;!?]+$/, '');
8
+ try {
9
+ const url = new URL(candidate);
10
+ if (hasPlaceholder(url))
11
+ continue;
12
+ if (url.pathname.endsWith('/settings/billing') ||
13
+ (!billingOnly && url.pathname === '/pricing')) {
14
+ return candidate;
15
+ }
16
+ }
17
+ catch {
18
+ // Ignore malformed server text and use the next available source.
19
+ }
20
+ }
21
+ return undefined;
22
+ }
23
+ /**
24
+ * The `TESTSPRITE_PORTAL_URL` origin, when the override is set and valid.
25
+ * `resolvePortalBase` checks this same env var first and ignores its `apiUrl`
26
+ * argument once it finds it set, so any argument resolves it — `''` keeps the
27
+ * intent explicit at each call site (there is no API URL to fall back to).
28
+ */
29
+ function overridePortalBase() {
30
+ if (!process.env.TESTSPRITE_PORTAL_URL?.trim())
31
+ return undefined;
32
+ const resolved = resolvePortalBase('');
33
+ return resolved && !hasPlaceholder(new URL(resolved)) ? resolved : undefined;
34
+ }
35
+ function portalBase(input) {
36
+ const override = overridePortalBase();
37
+ if (override)
38
+ return override;
39
+ const billingUrl = typeof input.details.billingUrl === 'string' ? input.details.billingUrl : '';
40
+ const serverUrl = portalUrlIn([billingUrl, input.serverNextAction ?? input.nextAction, input.message].join(' '));
41
+ if (serverUrl)
42
+ return new URL(serverUrl).origin;
43
+ return input.apiUrl ? resolvePortalBase(input.apiUrl) : undefined;
44
+ }
45
+ /**
46
+ * Rebase an absolute server-supplied billing URL onto the operator's
47
+ * `TESTSPRITE_PORTAL_URL` override, keeping the path (and query, if any) —
48
+ * the server knows its own routes, but the override says where the CLI's
49
+ * links should actually point. Without this, an override set for `pricing`
50
+ * (always synthesized from `portalBase`) silently didn't apply to a
51
+ * server-found `billing` URL, sending the two links to different hosts.
52
+ */
53
+ function rebaseOntoOverride(url) {
54
+ const override = overridePortalBase();
55
+ if (!override)
56
+ return url;
57
+ const parsed = new URL(url);
58
+ return `${override}${parsed.pathname}${parsed.search}`;
59
+ }
60
+ /** Shared pricing/billing destinations for refusals and history-window notes. */
61
+ export function resolveBillingLinks(input) {
62
+ const base = portalBase({
63
+ apiUrl: input.apiUrl,
64
+ details: { billingUrl: input.billingUrl },
65
+ nextAction: input.nextAction ?? '',
66
+ message: input.message ?? '',
67
+ code: 'FEATURE_GATED',
68
+ });
69
+ const pricing = base ? `${base}/pricing` : '/pricing';
70
+ const foundBilling = portalUrlIn(input.billingUrl ?? '', true) ??
71
+ portalUrlIn([input.nextAction, input.message].join(' '), true);
72
+ const orgId = safeOrgId(input.orgId);
73
+ const billing = (foundBilling !== undefined ? rebaseOntoOverride(foundBilling) : undefined) ??
74
+ (base
75
+ ? `${base}${orgId ? `/dashboard-v3/o/${orgId}` : '/dashboard'}/settings/billing`
76
+ : orgId
77
+ ? `/dashboard-v3/o/${orgId}/settings/billing`
78
+ : '/dashboard/settings/billing');
79
+ return { pricing, billing };
80
+ }
81
+ /** One ` label: value` line, aligned like the CLI's other key/value output. */
82
+ function fact(label, value) {
83
+ return ` ${`${label}:`.padEnd(11)}${value}`;
84
+ }
85
+ function safeOrgId(value) {
86
+ return typeof value === 'string' &&
87
+ value.trim() !== '' &&
88
+ !/^(undefined|null)$/i.test(value.trim()) &&
89
+ !/[/?#]/.test(value)
90
+ ? encodeURIComponent(value)
91
+ : undefined;
92
+ }
93
+ /**
94
+ * `details.reason` spellings of the three gate refusals: the gate's own names,
95
+ * plus the deprecated `billing_hold` / `plan` / `plan_limit` that older
96
+ * backends' CLI envelope and gate body still send. The CLI reads both and
97
+ * only ever writes the gate's names.
98
+ */
99
+ const GATE_REFUSAL_BY_REASON = new Map([
100
+ ['paused', 'paused'],
101
+ ['billing_hold', 'paused'],
102
+ ['not_entitled', 'not_entitled'],
103
+ ['plan', 'not_entitled'],
104
+ ['limit_exceeded', 'limit_exceeded'],
105
+ ['plan_limit', 'limit_exceeded'],
106
+ ]);
107
+ /**
108
+ * Which gate refusal a FEATURE_GATED `details.reason` is. An absent or empty
109
+ * reason is an older backend that never sent one (historically a plan
110
+ * exclusion). Any other value — `rollout`, the MCP view-only mirror's
111
+ * `mcp_origin`, or one this CLI doesn't know yet — is not a billing refusal:
112
+ * upgrading does nothing for it, so it gets no links and no fallback advice.
113
+ */
114
+ export function gateRefusalOf(reason) {
115
+ if (reason === undefined || reason === '')
116
+ return 'not_entitled';
117
+ return typeof reason === 'string' ? GATE_REFUSAL_BY_REASON.get(reason) : undefined;
118
+ }
119
+ /** True for a paused-workspace reason, including the deprecated `billing_hold`. */
120
+ export function isPausedReason(reason) {
121
+ return reason === 'paused' || reason === 'billing_hold';
122
+ }
123
+ export function classifyBillingRefusal(input) {
124
+ let reason;
125
+ if (input.code === 'INSUFFICIENT_CREDITS') {
126
+ reason = 'insufficient_credits';
127
+ }
128
+ else if (input.code === 'FEATURE_GATED') {
129
+ const refusal = gateRefusalOf(input.details.reason);
130
+ if (!refusal)
131
+ return undefined;
132
+ reason = refusal;
133
+ }
134
+ else {
135
+ return undefined;
136
+ }
137
+ const { pricing, billing } = resolveBillingLinks({
138
+ apiUrl: input.apiUrl,
139
+ billingUrl: typeof input.details.billingUrl === 'string' ? input.details.billingUrl : undefined,
140
+ orgId: input.details.orgId,
141
+ nextAction: input.serverNextAction ?? input.nextAction,
142
+ message: input.message,
143
+ });
144
+ // The server's message says why (which feature, which limit, why the
145
+ // workspace is paused) and its nextAction says what to do. These fallbacks
146
+ // only cover a response that arrived without a nextAction, and follow the
147
+ // backend's own CLI wording rather than guessing a cause.
148
+ let nextAction = input.nextAction;
149
+ if (!nextAction) {
150
+ switch (reason) {
151
+ case 'not_entitled':
152
+ nextAction = `Upgrade at ${billing} (plans: ${pricing}), then retry.`;
153
+ break;
154
+ case 'limit_exceeded':
155
+ nextAction = `Delete one and retry, or upgrade at ${billing} for a higher limit.`;
156
+ break;
157
+ case 'paused':
158
+ nextAction = `See ${billing} to resume this workspace, then retry.`;
159
+ break;
160
+ }
161
+ }
162
+ // Add only the links the printed message and nextAction don't already carry.
163
+ const printed = `${input.message}\n${nextAction}`;
164
+ const lines = [];
165
+ if (!printed.includes(pricing))
166
+ lines.push(fact('upgrade', pricing));
167
+ if (!printed.includes(billing))
168
+ lines.push(fact('billing', billing));
169
+ return { reason, links: { pricing, billing }, nextAction, lines };
170
+ }
171
+ //# sourceMappingURL=billing-refusal.js.map
@@ -33,6 +33,7 @@
33
33
  * when the agent re-runs. M3 may add resume.
34
34
  */
35
35
  import type { CliFailureContext } from '../commands/test.js';
36
+ import { type ShutdownHandle } from './interrupt.js';
36
37
  import type { FetchImpl } from './http.js';
37
38
  /** Schema version stamped into `meta.json`. Bumps with the contract. */
38
39
  export declare const BUNDLE_SCHEMA_VERSION: "cli-v1";
@@ -90,6 +91,8 @@ export interface WriteBundleOptions {
90
91
  failedOnly: boolean;
91
92
  /** Custom fetch impl for tests. Defaults to global `fetch`. */
92
93
  fetchImpl?: FetchImpl;
94
+ shutdownSignal?: AbortSignal;
95
+ shutdown?: Pick<ShutdownHandle, 'runCriticalOperation'>;
93
96
  /** Server requestId to embed in `.partial` on failure. */
94
97
  requestId?: string;
95
98
  }
@@ -226,4 +229,6 @@ export declare function commitBundle(tmpDir: string, dir: string, files: Readonl
226
229
  */
227
230
  export declare function streamUrlToFile(url: string, filePath: string, fetchImpl: FetchImpl, deps?: {
228
231
  sleep?: (ms: number) => Promise<void>;
232
+ shutdownSignal?: AbortSignal;
233
+ shutdown?: Pick<ShutdownHandle, 'runCriticalOperation'>;
229
234
  }): Promise<void>;
@@ -37,7 +37,9 @@ import { mkdir, mkdtemp, readdir, rename, rm, stat, unlink, writeFile } from 'no
37
37
  import { pipeline } from 'node:stream/promises';
38
38
  import { createWriteStream } from 'node:fs';
39
39
  import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
40
- import { ApiError, TransportError, localValidationError } from './errors.js';
40
+ import { ApiError, InterruptError, TransportError, localValidationError } from './errors.js';
41
+ import { globalShutdown } from './interrupt.js';
42
+ import { defaultSleep, sleepUnlessInterrupted } from './poll-support.js';
41
43
  import { requireEnum } from './validate.js';
42
44
  /** Schema version stamped into `meta.json`. Bumps with the contract. */
43
45
  export const BUNDLE_SCHEMA_VERSION = 'cli-v1';
@@ -321,6 +323,10 @@ export async function writeBundle(ctx, options) {
321
323
  assertContextIntegrity(filtered, requestId);
322
324
  const dir = resolveBundleDir(options.dir);
323
325
  const fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);
326
+ const downloadDeps = {
327
+ shutdownSignal: options.shutdownSignal,
328
+ shutdown: options.shutdown,
329
+ };
324
330
  const meta = buildMeta(filtered);
325
331
  const codeExt = pickCodeExtension(filtered.code.language, filtered.code.framework);
326
332
  await mkdir(dir, { recursive: true });
@@ -343,7 +349,7 @@ export async function writeBundle(ctx, options) {
343
349
  // bodies), stream the URL into the file rather than embedding
344
350
  // the URL in code.<ext>. M2's backend hasn't shipped the
345
351
  // >=100KB branch yet, but the contract supports it.
346
- await streamUrlToFile(filtered.code.code, join(tmpDir, codeFile), fetchImpl);
352
+ await streamUrlToFile(filtered.code.code, join(tmpDir, codeFile), fetchImpl, downloadDeps);
347
353
  }
348
354
  else {
349
355
  await writeFile(join(tmpDir, codeFile), filtered.code.code, 'utf8');
@@ -356,11 +362,11 @@ export async function writeBundle(ctx, options) {
356
362
  // (some runs ship `.webm`, not `.mp4`).
357
363
  if (filtered.result.videoUrl) {
358
364
  const videoFile = `video.${pickVideoExtension(filtered.result.videoUrl)}`;
359
- await streamUrlToFile(filtered.result.videoUrl, join(tmpDir, videoFile), fetchImpl);
365
+ await streamUrlToFile(filtered.result.videoUrl, join(tmpDir, videoFile), fetchImpl, downloadDeps);
360
366
  filesWritten.push(videoFile);
361
367
  }
362
368
  for (const step of filtered.steps) {
363
- await writeStepArtifacts(step, filtered.failure.evidence, stepsTmpDir, fetchImpl, filesWritten);
369
+ await writeStepArtifacts(step, filtered.failure.evidence, stepsTmpDir, fetchImpl, filesWritten, downloadDeps);
364
370
  }
365
371
  // meta.json LAST. Its presence is the sentinel that the bundle
366
372
  // is complete. An agent that opens <dir> and finds meta.json can
@@ -521,7 +527,7 @@ async function dirExists(path) {
521
527
  * console — for that step). The evidence-json file is omitted when
522
528
  * there's nothing to put in it; it's NOT a placeholder.
523
529
  */
524
- async function writeStepArtifacts(step, allEvidence, stepsTmpDir, fetchImpl, filesWritten) {
530
+ async function writeStepArtifacts(step, allEvidence, stepsTmpDir, fetchImpl, filesWritten, downloadDeps) {
525
531
  // stepIndex comes straight from the response and is used to build the
526
532
  // filename — reject anything that isn't a real index before composing a path.
527
533
  if (!Number.isInteger(step.stepIndex) || step.stepIndex < 0) {
@@ -530,12 +536,12 @@ async function writeStepArtifacts(step, allEvidence, stepsTmpDir, fetchImpl, fil
530
536
  const prefix = stepFilenamePrefix(step.stepIndex);
531
537
  if (step.screenshotUrl) {
532
538
  const file = `${prefix}-screenshot.png`;
533
- await streamUrlToFile(step.screenshotUrl, assertNoEscape(stepsTmpDir, file), fetchImpl);
539
+ await streamUrlToFile(step.screenshotUrl, assertNoEscape(stepsTmpDir, file), fetchImpl, downloadDeps);
534
540
  filesWritten.push(`steps/${file}`);
535
541
  }
536
542
  if (step.htmlSnapshotUrl) {
537
543
  const file = `${prefix}-snapshot.html`;
538
- await streamUrlToFile(step.htmlSnapshotUrl, assertNoEscape(stepsTmpDir, file), fetchImpl);
544
+ await streamUrlToFile(step.htmlSnapshotUrl, assertNoEscape(stepsTmpDir, file), fetchImpl, downloadDeps);
539
545
  filesWritten.push(`steps/${file}`);
540
546
  }
541
547
  // Evidence sidecar artifacts. Per codex round-1 P2: the bundle must
@@ -583,7 +589,7 @@ async function writeStepArtifacts(step, allEvidence, stepsTmpDir, fetchImpl, fil
583
589
  }
584
590
  const ext = sidecarExtension(entry.kind);
585
591
  const filename = `${prefix}-${entry.kind}-${i}.${ext}`;
586
- await streamUrlToFile(entry.url, assertNoEscape(stepsTmpDir, filename), fetchImpl);
592
+ await streamUrlToFile(entry.url, assertNoEscape(stepsTmpDir, filename), fetchImpl, downloadDeps);
587
593
  filesWritten.push(`steps/${filename}`);
588
594
  return {
589
595
  kind: entry.kind,
@@ -628,21 +634,31 @@ function sidecarExtension(kind) {
628
634
  * Presigned URLs are valid for 15 minutes, so retries are safe.
629
635
  */
630
636
  export async function streamUrlToFile(url, filePath, fetchImpl, deps) {
631
- const sleepFn = deps?.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
637
+ const shutdownSignal = deps?.shutdownSignal ?? globalShutdown.signal;
638
+ const shutdown = deps?.shutdown ?? globalShutdown;
639
+ return shutdown.runCriticalOperation(() => streamUrlToFileTracked(url, filePath, fetchImpl, deps?.sleep ?? defaultSleep, shutdownSignal));
640
+ }
641
+ async function streamUrlToFileTracked(url, filePath, fetchImpl, sleepFn, shutdownSignal) {
632
642
  const artifactUrl = redactArtifactUrlForDetails(url);
633
643
  for (let attempt = 1; attempt <= STREAM_URL_MAX_RETRIES; attempt++) {
644
+ if (shutdownSignal.aborted)
645
+ throw shutdownSignal.reason;
634
646
  let response;
635
647
  try {
636
- response = await fetchImpl(url, { redirect: 'error' });
648
+ response = await fetchImpl(url, { redirect: 'error', signal: shutdownSignal });
637
649
  }
638
650
  catch (err) {
651
+ if (err instanceof InterruptError || shutdownSignal.aborted)
652
+ throw shutdownSignal.reason ?? err;
639
653
  const message = err instanceof Error ? err.message : String(err);
640
654
  if (attempt < STREAM_URL_MAX_RETRIES) {
641
- await sleepFn(STREAM_URL_RETRY_DELAY_MS);
655
+ await sleepUnlessInterrupted(sleepFn, STREAM_URL_RETRY_DELAY_MS, shutdownSignal);
642
656
  continue;
643
657
  }
644
658
  throw new TransportError(`Failed to download presigned URL ${artifactUrl}: ${message}`);
645
659
  }
660
+ if (shutdownSignal.aborted)
661
+ throw shutdownSignal.reason;
646
662
  if (!response.ok) {
647
663
  // Non-2xx: the URL itself is bad (expired, unauthorized, not found).
648
664
  // Retrying the same URL won't help — surface immediately.
@@ -665,12 +681,20 @@ export async function streamUrlToFile(url, filePath, fetchImpl, deps) {
665
681
  try {
666
682
  const buffer = Buffer.from(await response.arrayBuffer());
667
683
  await writeFile(filePath, buffer);
684
+ if (shutdownSignal.aborted) {
685
+ await rm(filePath, { force: true }).catch(() => undefined);
686
+ throw shutdownSignal.reason;
687
+ }
668
688
  return;
669
689
  }
670
690
  catch (err) {
691
+ if (err instanceof InterruptError || shutdownSignal.aborted) {
692
+ await rm(filePath, { force: true }).catch(() => undefined);
693
+ throw shutdownSignal.reason ?? err;
694
+ }
671
695
  const message = err instanceof Error ? err.message : String(err);
672
696
  if (attempt < STREAM_URL_MAX_RETRIES) {
673
- await sleepFn(STREAM_URL_RETRY_DELAY_MS);
697
+ await sleepUnlessInterrupted(sleepFn, STREAM_URL_RETRY_DELAY_MS, shutdownSignal);
674
698
  continue;
675
699
  }
676
700
  throw new TransportError(`Failed to download presigned URL ${artifactUrl}: ${message}`);
@@ -688,12 +712,18 @@ export async function streamUrlToFile(url, filePath, fetchImpl, deps) {
688
712
  const { Readable } = await import('node:stream');
689
713
  const nodeStream = Readable.fromWeb(webBody);
690
714
  await pipeline(nodeStream, fileSink);
715
+ if (shutdownSignal.aborted)
716
+ throw shutdownSignal.reason;
691
717
  return;
692
718
  }
693
719
  catch (err) {
720
+ if (err instanceof InterruptError || shutdownSignal.aborted) {
721
+ await rm(filePath, { force: true }).catch(() => undefined);
722
+ throw shutdownSignal.reason ?? err;
723
+ }
694
724
  const message = err instanceof Error ? err.message : String(err);
695
725
  if (attempt < STREAM_URL_MAX_RETRIES) {
696
- await sleepFn(STREAM_URL_RETRY_DELAY_MS);
726
+ await sleepUnlessInterrupted(sleepFn, STREAM_URL_RETRY_DELAY_MS, shutdownSignal);
697
727
  continue;
698
728
  }
699
729
  throw new TransportError(`Failed mid-download of ${artifactUrl}: ${message}`);
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Deployment-linkage diagnosis for `ci doctor`.
3
+ *
4
+ * A deployment-gated workflow (`on: deployment_status`) only ever fires if the
5
+ * repo actually RECEIVES GitHub Deployment events. Those records are written by
6
+ * whatever deploys the app — Vercel's own GitHub App writes a `deployment` plus
7
+ * a `deployment_status`, GitHub broadcasts the event, and every subscriber
8
+ * (our workflow, the TestSprite GitHub App) sees the same one.
9
+ *
10
+ * When the deploy platform is not git-linked to the repo, nothing is ever
11
+ * written, so nothing ever fires — with no error anywhere. Measured on a real
12
+ * repo: the app deploys fine on Vercel while the repo's Deployments list is
13
+ * empty, which would leave a scaffolded gate permanently silent. This module
14
+ * turns that invisible state into a verdict.
15
+ *
16
+ * Pure functions only: the `gh`/`git` subprocess calls live in `commands/ci.ts`
17
+ * so this stays trivially testable.
18
+ */
19
+ /** One GitHub Deployment record, reduced to what the verdict needs. */
20
+ export interface DeploymentRecord {
21
+ /** GitHub's environment label — "Preview", "Production", "preview", … */
22
+ environment: string;
23
+ /** ISO timestamp the record was created. */
24
+ createdAt: string;
25
+ /** Login that wrote the record (`vercel[bot]`, a user, a CI app). */
26
+ creator: string | null;
27
+ }
28
+ export type LinkageStatus =
29
+ /** Recent records exist — events reach this repo, a gate will fire. */
30
+ 'linked'
31
+ /** Records exist but all are old — the link may have been removed since. */
32
+ | 'stale'
33
+ /** Records exist but none for a preview environment — a PR gate never fires. */
34
+ | 'production-only'
35
+ /** No records at all — either not linked, or linked and never deployed. */
36
+ | 'none';
37
+ export interface LinkageVerdict {
38
+ status: LinkageStatus;
39
+ /**
40
+ * Whether a deployment-gated workflow is safe to scaffold. Only `linked`
41
+ * qualifies: every other status means the gate would be silent or partial,
42
+ * which is the failure this check exists to prevent.
43
+ */
44
+ ok: boolean;
45
+ /** One-line human explanation, ready to print. */
46
+ detail: string;
47
+ /**
48
+ * Timestamp of the record the verdict is ABOUT — the newest preview record
49
+ * for `linked`/`stale`, the newest record overall for `production-only` —
50
+ * or null when there are none.
51
+ */
52
+ lastDeployAt: string | null;
53
+ /** Distinct creators seen, newest first — names who is writing the events. */
54
+ creators: string[];
55
+ /** Whether any record targets a preview environment. */
56
+ hasPreview: boolean;
57
+ }
58
+ /** "3 days ago" / "5 months ago", for the human line. */
59
+ export declare function describeAge(iso: string, now: Date): string;
60
+ /**
61
+ * Turn a repo's deployment history into a verdict.
62
+ *
63
+ * Deliberately NOT Vercel-specific on the success path: the event is the same
64
+ * whoever writes it, so a repo fed by Netlify, a self-hosted pipeline, or a
65
+ * hand-rolled `gh api` call reads as linked just the same. The creator is
66
+ * reported, not required.
67
+ *
68
+ * `records` may be in any order; the newest is picked here.
69
+ */
70
+ export declare function classifyLinkage(records: readonly DeploymentRecord[], now: Date): LinkageVerdict;
71
+ /**
72
+ * Whether a string is safe to use as an `owner/repo` slug in a `gh api` path.
73
+ * The character class matches what GitHub itself allows in owner/repo names,
74
+ * but admits `.`/`..` — which as path SEGMENTS would make `repos/../../…`
75
+ * resolve to a different endpoint — so those are refused explicitly.
76
+ */
77
+ export declare function isValidRepoSlug(slug: string): boolean;
78
+ /**
79
+ * `owner/repo` from a git remote URL. Handles the three shapes a cloned repo
80
+ * actually carries — SSH (`git@github.com:o/r.git`), HTTPS, and the `ssh://`
81
+ * form — and returns null for anything not on github.com, since a GitLab or
82
+ * Bitbucket remote has no GitHub Deployments to read.
83
+ */
84
+ export declare function parseRepoSlug(remoteUrl: string): string | null;
85
+ /**
86
+ * Reduce `gh api .../deployments` output to `DeploymentRecord`s. Tolerates the
87
+ * field being absent or oddly typed: a diagnosis must not crash on a payload
88
+ * shape change, it should just report what it could read.
89
+ */
90
+ export declare function parseDeploymentsPayload(raw: string): DeploymentRecord[];
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Deployment-linkage diagnosis for `ci doctor`.
3
+ *
4
+ * A deployment-gated workflow (`on: deployment_status`) only ever fires if the
5
+ * repo actually RECEIVES GitHub Deployment events. Those records are written by
6
+ * whatever deploys the app — Vercel's own GitHub App writes a `deployment` plus
7
+ * a `deployment_status`, GitHub broadcasts the event, and every subscriber
8
+ * (our workflow, the TestSprite GitHub App) sees the same one.
9
+ *
10
+ * When the deploy platform is not git-linked to the repo, nothing is ever
11
+ * written, so nothing ever fires — with no error anywhere. Measured on a real
12
+ * repo: the app deploys fine on Vercel while the repo's Deployments list is
13
+ * empty, which would leave a scaffolded gate permanently silent. This module
14
+ * turns that invisible state into a verdict.
15
+ *
16
+ * Pure functions only: the `gh`/`git` subprocess calls live in `commands/ci.ts`
17
+ * so this stays trivially testable.
18
+ */
19
+ /** How old the newest deployment may be before the link looks abandoned. */
20
+ const STALE_AFTER_DAYS = 90;
21
+ /** GitHub labels Vercel previews "Preview"; other platforms vary in case. */
22
+ function isPreviewEnvironment(environment) {
23
+ const env = environment.toLowerCase();
24
+ return env.includes('preview') || env.includes('staging');
25
+ }
26
+ function daysBetween(fromIso, now) {
27
+ const then = new Date(fromIso).getTime();
28
+ if (Number.isNaN(then))
29
+ return Number.POSITIVE_INFINITY;
30
+ return (now.getTime() - then) / 86_400_000;
31
+ }
32
+ /** "3 days ago" / "5 months ago", for the human line. */
33
+ export function describeAge(iso, now) {
34
+ const days = daysBetween(iso, now);
35
+ if (!Number.isFinite(days))
36
+ return 'at an unknown time';
37
+ if (days < 1)
38
+ return 'today';
39
+ if (days < 2)
40
+ return 'yesterday';
41
+ if (days < 45)
42
+ return `${Math.round(days)} days ago`;
43
+ return `${Math.round(days / 30)} months ago`;
44
+ }
45
+ /**
46
+ * Turn a repo's deployment history into a verdict.
47
+ *
48
+ * Deliberately NOT Vercel-specific on the success path: the event is the same
49
+ * whoever writes it, so a repo fed by Netlify, a self-hosted pipeline, or a
50
+ * hand-rolled `gh api` call reads as linked just the same. The creator is
51
+ * reported, not required.
52
+ *
53
+ * `records` may be in any order; the newest is picked here.
54
+ */
55
+ export function classifyLinkage(records, now) {
56
+ if (records.length === 0) {
57
+ return {
58
+ status: 'none',
59
+ ok: false,
60
+ // The two causes are indistinguishable from GitHub's side — we cannot
61
+ // query another App's installations — so the verdict names both rather
62
+ // than guessing. `ci connect` resolves either one the same way.
63
+ detail: 'No deployment events on this repo. Either the deploy platform is not linked to it, ' +
64
+ 'or it is linked and has not deployed yet — a deployment-gated workflow would never fire.',
65
+ lastDeployAt: null,
66
+ creators: [],
67
+ hasPreview: false,
68
+ };
69
+ }
70
+ const sorted = [...records].sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
71
+ const creators = [...new Set(sorted.map(r => r.creator).filter((c) => !!c))];
72
+ // Classify per environment, never off the newest record overall. A repo that
73
+ // deploys production daily but whose last preview is months old would
74
+ // otherwise read as freshly `linked` — and a gate scaffolded on that verdict
75
+ // never fires, which is the exact silent failure this classifier exists to
76
+ // catch. (Boundary this accepts: a repo whose whole fetched page is
77
+ // production deploys newer than its last preview reads `production-only`
78
+ // rather than `stale` — both mean "no PR gate", not worth paging for.)
79
+ const previews = sorted.filter(r => isPreviewEnvironment(r.environment));
80
+ if (previews.length === 0) {
81
+ const newest = sorted[0];
82
+ const age = describeAge(newest.createdAt, now);
83
+ const by = newest.creator ? ` by ${newest.creator}` : '';
84
+ return {
85
+ status: 'production-only',
86
+ ok: false,
87
+ // A PR gate keys on preview deployments; production-only records mean the
88
+ // workflow would fire on releases and never on a pull request.
89
+ detail: `Only production deployment events on this repo (newest ${age}${by}), none for a preview environment. ` +
90
+ 'A PR gate keys on preview deployments — enable preview deployments on your deploy platform.',
91
+ lastDeployAt: newest.createdAt,
92
+ creators,
93
+ hasPreview: false,
94
+ };
95
+ }
96
+ const newestPreview = previews[0];
97
+ const age = describeAge(newestPreview.createdAt, now);
98
+ const by = newestPreview.creator ? ` by ${newestPreview.creator}` : '';
99
+ if (daysBetween(newestPreview.createdAt, now) > STALE_AFTER_DAYS) {
100
+ return {
101
+ status: 'stale',
102
+ ok: false,
103
+ detail: `Preview deployment events exist, but the newest is from ${age}${by}. ` +
104
+ 'The link may have been removed since — push a commit and re-check before relying on a gate.',
105
+ lastDeployAt: newestPreview.createdAt,
106
+ creators,
107
+ hasPreview: true,
108
+ };
109
+ }
110
+ return {
111
+ status: 'linked',
112
+ ok: true,
113
+ detail: `Preview deployment events reach this repo (newest preview ${age}${by}).`,
114
+ lastDeployAt: newestPreview.createdAt,
115
+ creators,
116
+ hasPreview: true,
117
+ };
118
+ }
119
+ /**
120
+ * Whether a string is safe to use as an `owner/repo` slug in a `gh api` path.
121
+ * The character class matches what GitHub itself allows in owner/repo names,
122
+ * but admits `.`/`..` — which as path SEGMENTS would make `repos/../../…`
123
+ * resolve to a different endpoint — so those are refused explicitly.
124
+ */
125
+ export function isValidRepoSlug(slug) {
126
+ if (!/^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/.test(slug))
127
+ return false;
128
+ return slug.split('/').every(segment => segment !== '.' && segment !== '..');
129
+ }
130
+ /**
131
+ * `owner/repo` from a git remote URL. Handles the three shapes a cloned repo
132
+ * actually carries — SSH (`git@github.com:o/r.git`), HTTPS, and the `ssh://`
133
+ * form — and returns null for anything not on github.com, since a GitLab or
134
+ * Bitbucket remote has no GitHub Deployments to read.
135
+ */
136
+ export function parseRepoSlug(remoteUrl) {
137
+ const url = remoteUrl.trim();
138
+ if (!url)
139
+ return null;
140
+ const match = /^git@github\.com:(?<slug>[^/]+\/[^/]+?)(?:\.git)?$/.exec(url) ??
141
+ /^ssh:\/\/git@github\.com\/(?<slug>[^/]+\/[^/]+?)(?:\.git)?$/.exec(url) ??
142
+ /^https?:\/\/(?:[^@]+@)?github\.com\/(?<slug>[^/]+\/[^/]+?)(?:\.git)?\/?$/.exec(url);
143
+ const slug = match?.groups?.slug;
144
+ if (!slug)
145
+ return null;
146
+ return isValidRepoSlug(slug) ? slug : null;
147
+ }
148
+ /**
149
+ * Reduce `gh api .../deployments` output to `DeploymentRecord`s. Tolerates the
150
+ * field being absent or oddly typed: a diagnosis must not crash on a payload
151
+ * shape change, it should just report what it could read.
152
+ */
153
+ export function parseDeploymentsPayload(raw) {
154
+ let parsed;
155
+ try {
156
+ parsed = JSON.parse(raw);
157
+ }
158
+ catch {
159
+ return [];
160
+ }
161
+ if (!Array.isArray(parsed))
162
+ return [];
163
+ return (parsed
164
+ .filter((row) => row !== null && typeof row === 'object')
165
+ .map(row => {
166
+ const creator = row.creator;
167
+ const login = creator !== null && typeof creator === 'object'
168
+ ? creator.login
169
+ : undefined;
170
+ return {
171
+ environment: typeof row.environment === 'string' ? row.environment : '',
172
+ createdAt: typeof row.created_at === 'string' ? row.created_at : '',
173
+ creator: typeof login === 'string' ? login : null,
174
+ };
175
+ })
176
+ // A row without a PARSEABLE timestamp can't be aged or ordered — one NaN
177
+ // in the sort comparator would make the whole ordering implementation-
178
+ // defined — so it is dropped rather than silently treated as epoch.
179
+ .filter(r => Number.isFinite(new Date(r.createdAt).getTime())));
180
+ }
181
+ //# sourceMappingURL=ci-linkage.js.map