diff --git a/.changeset/submit-records-submission.md b/.changeset/submit-records-submission.md new file mode 100644 index 0000000..c57e21a --- /dev/null +++ b/.changeset/submit-records-submission.md @@ -0,0 +1,9 @@ +--- +'@reactivapp/cli': minor +--- + +`reactiv app submit` now records the published version with Reactiv and shows where to follow it. + +After the publish, the CLI sends the version to Reactiv, which records it as a submission. The receipt keeps its seven lines and adds two: `submission ` and `dashboard `, the submission's page in the Reactiv Dashboard; the link is printed once more on a line of its own so it can be opened in one piece. A network or server error is tried three times in all; a refusal is not retried. + +If the version cannot be recorded, it stays published and the CLI does not publish it again: it prints why, the version and `reactiv app submit --record ` on a line of its own, and exits with an error. The new `--record ` flag checks that it was given a draft version and then sends only that record call, with no checks, pack or publish, so it can be run once the cause is fixed. diff --git a/docs/commands.md b/docs/commands.md index 2e6ba28..a6ebf54 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -103,15 +103,19 @@ Validates and packs the library at the project root and publishes it as a draft ``` reactiv app submit [--dry-run] [--max-size-mb ] +reactiv app submit --record ``` | Flag | Effect | | --- | --- | | `--dry-run` | Run every check and pack the library, but publish nothing. The token service and the registry are still contacted, and the project's `.npmrc` token may be refreshed. | | `--max-size-mb` | Maximum unpacked size in MB. Default 5. | +| `--record ` | Record a version that is already published as a submission, and do nothing else: no checks, no pack, no publish. Use the version and command a failed submit printed; a value that is not a draft version (`-draft.`) is refused before anything is sent. Cannot be combined with `--dry-run`; `--max-size-mb` has no effect with it. | The checks are listed in [Project layout](project-layout.md#what-reactiv-app-submit-checks). The local ones run first; the CLI then contacts Reactiv's token service for a registry token and the submissions registry for the next draft version, scans the staged copy for credentials, packs `src/` and a generated `package.json` into a tarball, verifies the tarball's contents, and publishes it as `@reactiv-submissions/@-draft.` with the dist-tag `draft`. The receipt shows the version, the review-cycle base version, the app UUID, the declared dependencies, the registry and the tarball's sha256. +After the publish the CLI records the version with Reactiv as a submission, sending only the version; Reactiv works out the store from your API key. The receipt then ends with two more lines: `submission ` and `dashboard `, the submission's page in the Reactiv Dashboard. The link is printed once more on a line of its own below the receipt, so it can be opened or copied in one piece. A network error or a server error is tried three times in all, one and then two seconds apart; a refusal, including "too many submissions", is not retried. If recording still fails, the published version is kept and the CLI does not publish it again: it prints why, the version, and `reactiv app submit --record ` on a line of its own, and exits with an error. Run that command once the cause is fixed. Recording the same version twice is harmless, because Reactiv records each version of a store only once. When `--record` itself fails, it offers to run the same command again only if the failure can pass (Reactiv unreachable, too many submissions, or Reactiv not finding or not answering the record request); a refusal such as a revoked key needs its cause fixed first. + ## Environment variables | Variable | Effect | diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 4f21424..a987626 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -70,6 +70,10 @@ Another Metro is running on this machine. Stop it, then run `reactiv app run ios Try again in a few minutes. When the service answered, the message includes a request id; include it when you report the problem. +## `Version … is published but not recorded` + +`reactiv app submit` published your version, but Reactiv did not record it as a submission, so it does not appear in the Dashboard yet. The first line says why: Reactiv could not be reached (try again in a few minutes), too many submissions (try again later), or a refusal such as a revoked or expired key (fix that first, for example with `reactiv login`). Then run the command the CLI printed on a line of its own, `reactiv app submit --record `. It sends only the record call; it does not pack or publish again, so the version Reactiv reviews is the one already published. Do not run a plain `reactiv app submit` instead: that publishes a new draft version. + ## `Reactiv's token service no longer serves this CLI's API version` Update the CLI: `npm install -g @reactivapp/cli@latest`. diff --git a/packages/cli/src/commands/app/submit.ts b/packages/cli/src/commands/app/submit.ts index 5f3db89..ab73231 100644 --- a/packages/cli/src/commands/app/submit.ts +++ b/packages/cli/src/commands/app/submit.ts @@ -5,7 +5,9 @@ import * as path from 'node:path' import {createAuthContext, reportAuthError} from '../../lib/auth/context.js' import {SUBMISSIONS_SCOPE} from '../../lib/auth/npmrc.js' -import {ensureRegistryAuth, refreshAfterRegistryAuthError, type RegistryAuth, takeRegistryRetry} from '../../lib/auth/token.js' +import type {SubmitResponse} from '../../lib/auth/contract/submit.js' +import {type AuthContext, ensureRegistryAuth, refreshAfterRegistryAuthError, type RegistryAuth, takeRegistryRetry} from '../../lib/auth/token.js' +import {describeRecordFailure, isRetryable, publishedNotRecorded, recordCommand, recordSubmission} from '../../lib/devtools-submit.js' import {assertImportsDeclared, type DeclaredPackages, readDeclaredPackages} from '../../lib/imports.js' import { assertDependenciesInSync, @@ -18,6 +20,7 @@ import { } from '../../lib/layout.js' import {assertNoAppNativeIntegration} from '../../lib/native-integration.js' import {capture, captureAll, isRegistryAuthError, NPM_LOGLEVEL, npmEnv, runTee} from '../../lib/npm.js' +import {sanitizeForOutput} from '../../lib/auth/errors.js' import {loadProjectIdentity, type ProjectIdentity} from '../../lib/project.js' import {findSecretsInDirectory, formatSecretFindings} from '../../lib/secret-scan.js' import { @@ -28,6 +31,7 @@ import { assertTarballContents, checkSizeCap, computeSha256, + DRAFT_VERSION_PATTERN, draftBaseVersion, findEntryInTarball, findForbiddenPaths, @@ -56,11 +60,17 @@ export class AppSubmit extends Command { static override flags = { 'max-size-mb': Flags.integer({description: 'maximum unpacked size in MB', default: DEFAULT_SIZE_CAP_MB, min: 1}), 'dry-run': Flags.boolean({description: 'run everything including pack but skip the actual publish', default: false}), + record: Flags.string({ + description: 'record an already published version as a submission, without packing or publishing again', + helpValue: '', + exclusive: ['dry-run'], + }), } async run(): Promise { const {renderSuccess, renderInfo} = await import('@reactivapp/cli-ui') const {flags} = await this.parse(AppSubmit) + if (flags.record !== undefined) return this.recordOnly(flags.record) const projectRoot = process.cwd() if (!fs.existsSync(path.join(projectRoot, 'reactiv.conf.js'))) { @@ -250,14 +260,60 @@ export class AppSubmit extends Command { this.error(`the registry rejected the publish — npm publish exited with ${publish.status}`) } + // The version is published from here on: a failure below never publishes again. + let record: SubmitResponse + try { + record = await this.record(ctx, version) + } catch (error) { + const reason = await describeRecordFailure(ctx, error) + const {renderWarning} = await import('@reactivapp/cli-ui') + renderWarning({headline: 'Submission published, not recorded', body: receipt}) + this.fail([reason, publishedNotRecorded(version), ` ${recordCommand(version)}`]) + } + renderSuccess({ headline: 'Submission published', - body: receipt, + body: [...receipt, ...recordLines(record)], }) + this.log(sanitizeForOutput(record.dashboardUrl)) } catch (error) { reportAuthError(this, error) } finally { fs.rmSync(stagingDir, {recursive: true, force: true}) } } + + private async record(ctx: AuthContext, version: string): Promise { + this.log('Recording the submission with Reactiv…') + return recordSubmission(ctx, version) + } + + // Plain lines: oclif's error gutter would wrap the command to run. + private fail(lines: string[]): never { + for (const line of lines) this.logToStderr(line) + return this.exit(2) + } + + private async recordOnly(version: string): Promise { + if (!DRAFT_VERSION_PATTERN.test(version)) { + this.error(`--record takes the version a failed submit printed, such as 0.1.8-draft.2; "${sanitizeForOutput(version)}" is not one.`) + } + const {renderSuccess} = await import('@reactivapp/cli-ui') + const ctx = createAuthContext(this) + let record: SubmitResponse + try { + record = await this.record(ctx, version) + } catch (error) { + const reason = await describeRecordFailure(ctx, error) + // A refusal (a 4xx other than 429) is not fixed by running the same call again. + this.fail(isRetryable(error) ? [reason, 'Then run:', ` ${recordCommand(version)}`] : [reason]) + } + renderSuccess({headline: 'Submission recorded', body: recordLines(record)}) + this.log(sanitizeForOutput(record.dashboardUrl)) + } } + +const recordLines = (record: SubmitResponse): string[] => [ + `submission ${sanitizeForOutput(record.submissionId)}`, + `dashboard ${sanitizeForOutput(record.dashboardUrl)}`, +] diff --git a/packages/cli/src/lib/auth/contract/submit.ts b/packages/cli/src/lib/auth/contract/submit.ts new file mode 100644 index 0000000..da439f2 --- /dev/null +++ b/packages/cli/src/lib/auth/contract/submit.ts @@ -0,0 +1,12 @@ +// Wire types of POST /v1/submissions; responses are wrapped in {data}. Update +// this copy in the same change as the service's published submissions contract. + +export interface SubmitRequest { + version: string +} + +export interface SubmitResponse { + submissionId: string + status: string + dashboardUrl: string +} diff --git a/packages/cli/src/lib/auth/messages.ts b/packages/cli/src/lib/auth/messages.ts index 9dc847b..e7f21c1 100644 --- a/packages/cli/src/lib/auth/messages.ts +++ b/packages/cli/src/lib/auth/messages.ts @@ -49,7 +49,7 @@ export const vendingUnreachable = (requestId: string | undefined, cachedTokenExp export const registryRefreshFailed = (vendingMessage: string): string => `Registry token could not be refreshed: ${vendingMessage}` -const withRequestId = (message: string, requestId: string | undefined): string => +export const withRequestId = (message: string, requestId: string | undefined): string => requestId ? `${message}\nRequest id: ${sanitizeForOutput(requestId)}` : message export const describeVendingError = (error: VendingError, cachedTokenExpiresAt?: string): string => { diff --git a/packages/cli/src/lib/auth/token.ts b/packages/cli/src/lib/auth/token.ts index 0883987..c835933 100644 --- a/packages/cli/src/lib/auth/token.ts +++ b/packages/cli/src/lib/auth/token.ts @@ -128,7 +128,7 @@ const deleteFileLogin = async (ctx: AuthContext, keyId: string): Promise = }, ctx.lockOptions) } -const vendingFailure = async (ctx: AuthContext, identity: Identity | undefined, error: unknown): Promise => { +export const vendingFailure = async (ctx: AuthContext, identity: Identity | undefined, error: unknown): Promise => { if (!(error instanceof VendingError)) throw error if ((error.code === 'key_revoked' || error.code === 'key_expired') && identity?.source === 'file') { await deleteFileLogin(ctx, identity.keyId) diff --git a/packages/cli/src/lib/auth/vending-client.ts b/packages/cli/src/lib/auth/vending-client.ts index 568bb77..7fea325 100644 --- a/packages/cli/src/lib/auth/vending-client.ts +++ b/packages/cli/src/lib/auth/vending-client.ts @@ -1,5 +1,6 @@ import type {ApiKey} from './credentials' import type {ErrorCode, ErrorResponse, MeResponse, TermsAcceptRequest, TermsAcceptResponse, TermsResponse, TokenResponse} from './contract' +import type {SubmitRequest, SubmitResponse} from './contract/submit' import {AuthError} from './errors' export const DEFAULT_VENDING_API_URL = 'https://plus-devtools-staging.dev.reactivapp.com' @@ -71,6 +72,7 @@ export interface VendingClient { terms(): Promise acceptTerms(key: ApiKey, request: TermsAcceptRequest): Promise mint(key: ApiKey): Promise + submit(key: ApiKey, request: SubmitRequest): Promise<{data: SubmitResponse}> } export interface VendingClientOptions { @@ -130,6 +132,9 @@ export const isErrorResponse = (value: unknown): value is Pick = (value): value is {data: SubmitResponse} => + isRecord(value) && isRecord(value.data) && isString(value.data.submissionId) && isString(value.data.dashboardUrl) + const parseJson = (text: string): unknown => { try { return JSON.parse(text) as unknown @@ -168,7 +173,15 @@ export const createVendingClient = (options: VendingClientOptions): VendingClien const timeoutMs = options.timeoutMs ?? REQUEST_TIMEOUT_MS const userAgent = `reactiv-cli/${options.cliVersion} (${options.platform ?? process.platform})` - const call = async (method: 'GET' | 'POST', path: string, guard: Guard, key?: ApiKey, body?: unknown): Promise => { + // waitOnRateLimit false: a 429 fails at once. + const call = async ( + method: 'GET' | 'POST', + path: string, + guard: Guard, + key?: ApiKey, + body?: unknown, + {waitOnRateLimit = true}: {waitOnRateLimit?: boolean} = {}, + ): Promise => { const headers: Record = {'User-Agent': userAgent, Accept: 'application/json'} if (key) headers.Authorization = `Bearer ${key.reveal()}` if (body !== undefined) headers['Content-Type'] = 'application/json' @@ -214,7 +227,7 @@ export const createVendingClient = (options: VendingClientOptions): VendingClien const retryAfter = parseRetryAfter(retryAfterHeader, now()) const waitSeconds = retryAfter ?? FALLBACK_RATE_LIMIT_WAIT_S // Beyond setTimeout's range the timer would fire at once instead of waiting. - if (!rateLimitRetried && waitSeconds * 1000 <= MAX_TIMER_MS) { + if (waitOnRateLimit && !rateLimitRetried && waitSeconds * 1000 <= MAX_TIMER_MS) { rateLimitRetried = true options.onWait?.(`Reactiv's token service is rate limiting; retrying in ${waitSeconds} s.`) await sleep(waitSeconds * 1000) @@ -250,5 +263,8 @@ export const createVendingClient = (options: VendingClientOptions): VendingClien terms: () => call('GET', '/v1/terms', isTermsResponse), acceptTerms: (key, request) => call('POST', '/v1/terms/accept', isTermsAcceptResponse, key, request), mint: key => call('POST', '/v1/tokens', isTokenResponse, key), + // Submits are limited per hour and a published version can be recorded later, so a 429 is not waited out. + submit: (key, request) => + call('POST', '/v1/submissions', isSubmitEnvelope, key, request, {waitOnRateLimit: false}), } } diff --git a/packages/cli/src/lib/devtools-submit.ts b/packages/cli/src/lib/devtools-submit.ts new file mode 100644 index 0000000..4deb021 --- /dev/null +++ b/packages/cli/src/lib/devtools-submit.ts @@ -0,0 +1,52 @@ +import type {SubmitResponse} from './auth/contract/submit' +import {AuthError, sanitizeForOutput} from './auth/errors' +import {withRequestId} from './auth/messages' +import {type AuthContext, resolveIdentity, vendingFailure} from './auth/token' +import {VendingError} from './auth/vending-client' + +export const recordSubmission = async (ctx: AuthContext, version: string): Promise => { + const identity = await resolveIdentity(ctx) + return (await ctx.vending.submit(identity.apiKey, {version})).data +} + +// The submissions route answered 404, or answered 2xx without a submission. +const isUnservedRecord = (error: VendingError): boolean => + error.kind === 'api' && (error.code === 'not_found' || error.status === 404 || (error.status !== undefined && error.status < 300)) + +/** True when running the same record call again later can succeed. */ +export const isRetryable = (error: unknown): boolean => + error instanceof VendingError && (error.kind === 'unreachable' || error.kind === 'rate_limited' || isUnservedRecord(error)) + +/** + * The reason to print for a failed record call. Key and store refusals get the + * same text and stored-login cleanup as every other call. The cases where that + * text would speak of the token service, the token cache or updating the CLI + * have their own sentence here. + */ +export const describeRecordFailure = async (ctx: AuthContext, error: unknown): Promise => { + if (error instanceof VendingError && error.kind === 'rate_limited') { + return withRequestId('Too many submissions — try again later.', error.requestId) + } + if (error instanceof VendingError && error.kind === 'unreachable') { + return withRequestId('Reactiv could not be reached to record the submission.', error.requestId) + } + if (error instanceof VendingError && isUnservedRecord(error)) { + const sentence = + error.status === 404 || error.code === 'not_found' + ? 'Reactiv could not find the submissions service (HTTP 404). Contact Reactiv if this continues.' + : `Reactiv's answer did not contain the submission (HTTP ${error.status}). Contact Reactiv if this continues.` + return withRequestId(sentence, error.requestId) + } + try { + await vendingFailure(ctx, ctx.memo?.identity, error) + } catch (failure) { + if (failure instanceof AuthError) return failure.message + if (failure instanceof Error) return `The submission could not be recorded: ${sanitizeForOutput(failure.message)}` + } + return 'The submission could not be recorded.' +} + +export const recordCommand = (version: string): string => `reactiv app submit --record ${sanitizeForOutput(version)}` + +export const publishedNotRecorded = (version: string): string => + `Version ${sanitizeForOutput(version)} is published but not recorded. Once the cause is fixed, record it without publishing again:` diff --git a/packages/cli/test/devtools-submit.test.ts b/packages/cli/test/devtools-submit.test.ts new file mode 100644 index 0000000..2da852b --- /dev/null +++ b/packages/cli/test/devtools-submit.test.ts @@ -0,0 +1,214 @@ +import {mkdtempSync, rmSync} from 'node:fs' +import {tmpdir} from 'node:os' +import {join} from 'node:path' +import {afterEach, describe, expect, it} from 'vitest' + +import {parseApiKey} from '../src/lib/auth/credentials' +import type {AuthContext} from '../src/lib/auth/token' +import {createVendingClient} from '../src/lib/auth/vending-client' +import {describeRecordFailure, isRetryable, publishedNotRecorded, recordCommand, recordSubmission} from '../src/lib/devtools-submit' +import { + API_KEY, + assertNoSecrets, + DASHBOARD_URL, + errorReply, + KEY_ID, + MERCHANT, + opaqueRequestId, + SUBMISSION_ID, + submitResponse, + type MockReply, +} from './helpers/fixtures' + +const key = parseApiKey(API_KEY) +const homes: string[] = [] + +afterEach(() => { + for (const home of homes.splice(0)) rmSync(home, {recursive: true, force: true}) +}) + +// A client on a fake fetch with recorded sleeps; the identity is already resolved, so only the record call goes out. +const fakeRecord = (replies: Array) => { + const sleeps: number[] = [] + const calls: Array<{url: string; init: RequestInit}> = [] + const fetchImpl = (async (url: string, init: RequestInit) => { + calls.push({url, init}) + const next = replies.shift() + if (!next) throw new Error('no reply queued') + if (next instanceof Error) throw next + const body = next.body === undefined ? '' : typeof next.body === 'string' ? next.body : JSON.stringify(next.body) + return new Response(body, {status: next.status, headers: {'x-request-id': opaqueRequestId(), ...next.headers}}) + }) as unknown as typeof fetch + const vending = createVendingClient({ + baseUrl: 'https://devtools.test', + cliVersion: '9.9.9', + platform: 'darwin', + fetch: fetchImpl, + sleep: async ms => { + sleeps.push(ms) + }, + onWait: () => { + throw new Error('the record call must not wait out a 429') + }, + }) + const home = mkdtempSync(join(tmpdir(), 'record-')) + homes.push(home) + const ctx = { + env: {HOME: home}, + vending, + log: () => undefined, + warn: () => undefined, + now: Date.now, + memo: {identity: {source: 'env', apiKey: key, keyId: KEY_ID, merchant: MERCHANT}}, + } as unknown as AuthContext + const record = () => recordSubmission(ctx, '0.1.8-draft.2') + const failure = async (): Promise<{error: unknown; reason: string}> => { + try { + await record() + } catch (error) { + return {error, reason: await describeRecordFailure(ctx, error)} + } + throw new Error('expected the record call to fail') + } + return {record, failure, ctx, sleeps, calls} +} + +const unavailable = (): MockReply => errorReply(503, 'upstream_unavailable') +const refusal = (status: number, code: string, message: string, details?: Record): MockReply => ({ + status, + body: {code, message, retryable: false, requestId: 'req-1', ...(details ? {details} : {})}, +}) + +describe('recordSubmission', () => { + it('posts only the version and returns the unwrapped record', async () => { + const {record, calls, sleeps} = fakeRecord([{status: 200, body: submitResponse()}]) + await expect(record()).resolves.toEqual({submissionId: SUBMISSION_ID, status: 'Processing', dashboardUrl: DASHBOARD_URL}) + expect(calls).toHaveLength(1) + expect(calls[0].url).toBe('https://devtools.test/v1/submissions') + expect(calls[0].init.method).toBe('POST') + expect(calls[0].init.body).toBe('{"version":"0.1.8-draft.2"}') + expect(calls[0].init.redirect).toBe('error') + expect(calls[0].init.headers).toEqual({ + 'User-Agent': 'reactiv-cli/9.9.9 (darwin)', + Accept: 'application/json', + 'Content-Type': 'application/json', + Authorization: `Bearer ${API_KEY}`, + }) + expect(sleeps).toEqual([]) + }) + + it('accepts any status and any link text, so a change on the service does not fail the record', async () => { + const dashboardUrl = 'a new kind of link' + const {record} = fakeRecord([{status: 200, body: {data: {submissionId: 'any-id', status: 'Some New Status', dashboardUrl}}}]) + await expect(record()).resolves.toMatchObject({submissionId: 'any-id', dashboardUrl}) + }) + + it('tries a 5xx three times in all with the same body, backing off 1 s then 2 s', async () => { + const {record, calls, sleeps} = fakeRecord([unavailable(), unavailable(), {status: 200, body: submitResponse()}]) + await expect(record()).resolves.toMatchObject({submissionId: SUBMISSION_ID}) + expect(calls.map(call => call.init.body)).toEqual(Array(3).fill('{"version":"0.1.8-draft.2"}')) + expect(sleeps).toEqual([1000, 2000]) + }) + + it('gives up after a third 5xx, as retryable and unreachable', async () => { + const {failure, calls, sleeps} = fakeRecord([unavailable(), unavailable(), unavailable(), {status: 200, body: submitResponse()}]) + const {error, reason} = await failure() + expect(isRetryable(error)).toBe(true) + expect(reason).toMatch(/^Reactiv could not be reached to record the submission\.\nRequest id: \S+$/) + expect(calls).toHaveLength(3) + expect(sleeps).toEqual([1000, 2000]) + }) + + it('gives up after three network errors', async () => { + const {failure, calls, sleeps} = fakeRecord([new TypeError('fetch failed'), new TypeError('fetch failed'), new TypeError('fetch failed')]) + const {error, reason} = await failure() + expect(isRetryable(error)).toBe(true) + expect(reason).toBe('Reactiv could not be reached to record the submission.') + expect(calls).toHaveLength(3) + expect(sleeps).toEqual([1000, 2000]) + }) + + it('does not wait out a 429 and says the limit is on submissions', async () => { + const {failure, calls, sleeps} = fakeRecord([ + {status: 429, headers: {'retry-after': '1'}, body: {code: 'rate_limited', message: 'Too many requests. Retry later.', retryable: true, requestId: 'req-2'}}, + ]) + const {error, reason} = await failure() + expect(isRetryable(error)).toBe(true) + expect(reason).toBe('Too many submissions — try again later.\nRequest id: req-2') + expect(calls).toHaveLength(1) + expect(sleeps).toEqual([]) + }) + + it('does not retry an invalid request, and prints the server message', async () => { + const {failure, calls, sleeps} = fakeRecord([refusal(400, 'invalid_request', 'The request is malformed.')]) + const {error, reason} = await failure() + expect(isRetryable(error)).toBe(false) + expect(reason).toBe('The request is malformed.\nRequest id: req-1') + expect(calls).toHaveLength(1) + expect(sleeps).toEqual([]) + }) + + it('gives a revoked key the same guidance as every other call', async () => { + const {failure, calls} = fakeRecord([ + refusal(401, 'key_revoked', 'This API key has been revoked.', {revokedAt: '2026-11-01T00:00:00Z', reason: 'contract ended'}), + ]) + const {error, reason} = await failure() + expect(isRetryable(error)).toBe(false) + expect(reason).toContain('2026-11-01T00:00:00Z') + expect(reason).toContain('contract ended') + expect(calls).toHaveLength(1) + }) + + it.each([ + ['a missing data envelope', submitResponse().data], + ['a submission id that is not a string', submitResponse({submissionId: 42 as never})], + ['a missing link', {data: {submissionId: SUBMISSION_ID, status: 'Processing'}}], + ['a link that is not a string', submitResponse({dashboardUrl: 42 as never})], + ])('rejects a 2xx with %s and keeps its request id', async (_label, body) => { + const {failure, calls} = fakeRecord([{status: 200, body, headers: {'x-request-id': 'req-7'}}]) + const {error, reason} = await failure() + expect(isRetryable(error)).toBe(true) + expect(reason).toBe("Reactiv's answer did not contain the submission (HTTP 200). Contact Reactiv if this continues.\nRequest id: req-7") + expect(calls).toHaveLength(1) + }) + + it.each([ + ['a not_found error body', refusal(404, 'not_found', 'No such route. If you are calling /v1/…, update the Reactiv CLI.')], + ['no error body', {status: 404, body: ''} as MockReply], + ])('says the submissions service was not found on a 404 with %s, and does not suggest updating the CLI', async (_label, reply) => { + const {failure, calls, sleeps} = fakeRecord([{...reply, headers: {'x-request-id': 'req-4'}}]) + const {error, reason} = await failure() + expect(isRetryable(error)).toBe(true) + expect(reason).toMatch(/^Reactiv could not find the submissions service \(HTTP 404\)\. Contact Reactiv if this continues\.\nRequest id: req-[14]$/) + expect(reason).not.toContain('update') + expect(calls).toHaveLength(1) + expect(sleeps).toEqual([]) + }) + + it('never prints the key or control characters from server text', async () => { + const {failure} = fakeRecord([refusal(400, 'invalid_request', `bad ${API_KEY}\u001b[31m`)]) + const {reason} = await failure() + expect(reason).toBe('bad [redacted][31m\nRequest id: req-1') + assertNoSecrets(reason) + }) +}) + +describe('describeRecordFailure', () => { + it('gives any other error a plain reason instead of rethrowing it', async () => { + const {ctx} = fakeRecord([]) + expect(isRetryable(new Error('EACCES'))).toBe(false) + await expect(describeRecordFailure(ctx, new Error('EACCES: permission denied\u001b[2J'))).resolves.toBe( + 'The submission could not be recorded: EACCES: permission denied[2J', + ) + await expect(describeRecordFailure(ctx, 'thrown string')).resolves.toBe('The submission could not be recorded.') + }) +}) + +describe('recovery text', () => { + it('names the version, and the command stands alone', () => { + expect(publishedNotRecorded('0.1.8-draft.2')).toBe( + 'Version 0.1.8-draft.2 is published but not recorded. Once the cause is fixed, record it without publishing again:', + ) + expect(recordCommand('0.1.8-draft.2')).toBe('reactiv app submit --record 0.1.8-draft.2') + }) +}) diff --git a/packages/cli/test/helpers/fixtures.ts b/packages/cli/test/helpers/fixtures.ts index 33da5c2..84c5488 100644 --- a/packages/cli/test/helpers/fixtures.ts +++ b/packages/cli/test/helpers/fixtures.ts @@ -5,6 +5,7 @@ import {join} from 'node:path' import {expect} from 'vitest' import type {MeResponse, TokenResponse} from '../../src/lib/auth/contract' +import type {SubmitResponse} from '../../src/lib/auth/contract/submit' export const binPath = join(__dirname, '..', '..', 'bin', 'run') @@ -55,6 +56,13 @@ export const tokenResponse = (overrides: Partial = {}, now = Date ...overrides, }) +export const SUBMISSION_ID = '01JC2Y7N4M3K5T8R6P9Q1W0X2Z' +export const DASHBOARD_URL = `https://dashboard.example.test/store/acme-outfitters/apps/reactiv/app/plus/submissions/${SUBMISSION_ID}` + +export const submitResponse = (overrides: Partial = {}): {data: SubmitResponse} => ({ + data: {submissionId: SUBMISSION_ID, status: 'Processing', dashboardUrl: DASHBOARD_URL, ...overrides}, +}) + export const assertNoSecrets = (...outputs: string[]): void => { for (const output of outputs) { expect(output).not.toContain(TOKEN) diff --git a/packages/cli/test/submit-dry-run.test.ts b/packages/cli/test/submit-dry-run.test.ts index 3620f66..93246ac 100644 --- a/packages/cli/test/submit-dry-run.test.ts +++ b/packages/cli/test/submit-dry-run.test.ts @@ -7,6 +7,8 @@ import {afterEach, beforeEach, describe, expect, it} from 'vitest' import { API_KEY, assertNoSecrets, + DASHBOARD_URL, + errorReply, isolatedEnv, MERCHANT, meResponse, @@ -14,11 +16,14 @@ import { REGISTRY_URL, runCli, startMockVending, + SUBMISSION_ID, + submitResponse, tokenResponse, type MockReply, } from './helpers/fixtures' import {installNpmShim, type NpmShim} from './helpers/npm-shim' import {SECRET_PATTERNS} from '../src/lib/secret-scan.js' +import {computeSha256} from '../src/lib/submission.js' const PLATFORM_PEERS = {'@reactivapp/mobile': '2608.13.1', react: '19.2.3', 'react-native': '0.86.0'} @@ -73,6 +78,7 @@ describe('app submit against a mock vending API and a fixture registry', () => { let shim: NpmShim let mock: Awaited> let tokenReplies: MockReply[] + let submitReply: MockReply let env: NodeJS.ProcessEnv beforeEach(async () => { @@ -82,9 +88,11 @@ describe('app submit against a mock vending API and a fixture registry', () => { writeFixtureProject(projectDir) shim = installNpmShim(workDir) tokenReplies = [] + submitReply = {status: 200, body: submitResponse()} mock = await startMockVending({ 'GET /v1/me': () => ({status: 200, body: meResponse()}), 'POST /v1/tokens': () => tokenReplies.shift() ?? {status: 200, body: tokenResponse()}, + 'POST /v1/submissions': () => submitReply, }) env = isolatedEnv(join(workDir, 'home'), { ...shim.env, @@ -119,6 +127,8 @@ describe('app submit against a mock vending API and a fixture registry', () => { // oclif wraps long error lines behind a ' ›' gutter; join them back up. const flat = (text: string): string => text.replace(/\s*›\s*/g, ' ').replace(/\s+/g, ' ') + const recordCalls = () => mock.requests.filter(request => request.method === 'POST' && request.path === '/v1/submissions') + const publishedTarball = (): string => { if (npmCalls('publish').length === 0) throw new Error('nothing was published') return join(workDir, 'published.tgz') @@ -242,10 +252,139 @@ describe('app submit against a mock vending API and a fixture registry', () => { expect(npmCalls('view')).toEqual([]) }, 30_000) - it('never publishes on a dry run', async () => { + it('never publishes or records on a dry run', async () => { await submit(['0.1.7']) expect(npmCalls('publish')).toEqual([]) - }, 30_000) + expect(recordCalls()).toEqual([]) + }, 30_000) + + describe('recording the published version', () => { + const ANSI_CODES = /\u001b\[[0-9;]*m/g + // The banner as cli-ui draws it into a pipe, so wrapped lines compare as drawn. + const banner = async (kind: 'info' | 'success', headline: string, body: string[]): Promise => { + const ui = await import('@reactivapp/cli-ui') + let out = '' + const render = kind === 'info' ? ui.renderInfo : ui.renderSuccess + render({headline, body}, {write: chunk => (out += chunk)}) + return out.replace(ANSI_CODES, '') + } + const todaysReceipt = (sha256: string): string[] => [ + '@reactiv-submissions/acme@0.1.8-draft.2', + 'review cycle 0.1.8 (approval will publish 0.1.8)', + `appUuid ${MERCHANT.appUuid}`, + 'dependencies date-fns', + 'dist-tag draft', + `registry ${REGISTRY_URL}`, + `sha256 ${sha256}`, + ] + const lines = (text: string): string[] => text.replace(ANSI_CODES, '').split('\n') + const record = (version: string, extra: string[] = []) => + runCli(['app', 'submit', '--record', version, ...extra], {cwd: workDir, env}).then(result => { + assertNoSecrets(result.stdout, result.stderr) + return result + }) + // Retries of a 5xx and their 1 s and 2 s waits are covered with an injected sleep in devtools-submit.test.ts; + // these runs use replies that are not retried, so no test waits for real time. + const tooMany = (): MockReply => errorReply(429, 'rate_limited') + + it('keeps the seven receipt lines, adds the submission id and Dashboard link, then prints the link on its own', async () => { + const dryRun = await submit(['0.1.7', '0.1.8-draft.1']) + const published = await submit(['0.1.7', '0.1.8-draft.1'], {dryRun: false}) + expect(published.code).toBe(0) + const receipt = todaysReceipt(computeSha256(publishedTarball())) + expect(dryRun.stdout.replace(ANSI_CODES, '')).toContain(await banner('info', 'Dry run complete (publish skipped)', receipt)) + const successBanner = await banner('success', 'Submission published', [...receipt, `submission ${SUBMISSION_ID}`, `dashboard ${DASHBOARD_URL}`]) + expect(published.stdout.replace(ANSI_CODES, '')).toContain(`Recording the submission with Reactiv…\n${successBanner}${DASHBOARD_URL}\n`) + expect(recordCalls().map(request => request.body)).toEqual(['{"version":"0.1.8-draft.2"}']) + expect(recordCalls()[0].headers.authorization).toBe(`Bearer ${API_KEY}`) + }, 30_000) + + it('keeps the publish, prints the recovery command on its own line and fails when recording fails', async () => { + submitReply = tooMany() + const result = await submit(['0.1.7', '0.1.8-draft.1'], {dryRun: false}) + expect(result.code).toBe(2) + expect(npmCalls('publish')).toHaveLength(1) + expect(recordCalls()).toHaveLength(1) + expect(result.stdout).not.toContain('Submission published') + expect(result.stderr).toContain('Submission published, not recorded') + expect(result.stderr).toContain('@reactiv-submissions/acme@0.1.8-draft.2') + const tail = lines(result.stderr).slice(-5) + expect(tail[0]).toBe('Too many submissions — try again later.') + expect(tail[1]).toMatch(/^Request id: \S+$/) + expect(tail.slice(2)).toEqual([ + 'Version 0.1.8-draft.2 is published but not recorded. Once the cause is fixed, record it without publishing again:', + ' reactiv app submit --record 0.1.8-draft.2', + '', + ]) + }, 30_000) + + it('--record sends the same body as the publish run, and nothing else runs', async () => { + submitReply = tooMany() + await submit(['0.1.7', '0.1.8-draft.1'], {dryRun: false}) + const sentByPublishRun = recordCalls()[0].body + const npmLog = readFileSync(shim.log, 'utf8') + const requestsBefore = mock.requests.length + + submitReply = {status: 200, body: submitResponse()} + const result = await record('0.1.8-draft.2') + expect(result.code).toBe(0) + expect(result.stdout.replace(ANSI_CODES, '')).toContain( + `${await banner('success', 'Submission recorded', [`submission ${SUBMISSION_ID}`, `dashboard ${DASHBOARD_URL}`])}${DASHBOARD_URL}\n`, + ) + const sinceRecord = mock.requests.slice(requestsBefore) + expect(sinceRecord.map(request => `${request.method} ${request.path}`)).toEqual(['GET /v1/me', 'POST /v1/submissions']) + expect(sinceRecord[1].body).toBe(sentByPublishRun) + expect(readFileSync(shim.log, 'utf8')).toBe(npmLog) + }, 30_000) + + it('--record refuses a value that is not a draft version before any call', async () => { + const result = await record('not-a-version') + expect(result.code).not.toBe(0) + expect(flat(result.errorText)).toContain('--record takes the version a failed submit printed, such as 0.1.8-draft.2; "not-a-version" is not one.') + expect(mock.requests).toEqual([]) + expect((await record('0.1.8')).code).not.toBe(0) + expect(mock.requests).toEqual([]) + }, 30_000) + + it('--record shows a refusal without a rerun hint and without claiming a publish', async () => { + submitReply = {status: 400, body: {code: 'invalid_request', message: 'The request is malformed.', retryable: false, requestId: 'req-9'}} + const result = await record('0.1.8-draft.2') + expect(result.code).toBe(2) + expect(recordCalls()).toHaveLength(1) + expect(lines(result.stderr)).toEqual(['The request is malformed.', 'Request id: req-9', '']) + }, 30_000) + + it('--record on a 404 names the missing service, not a CLI update, and offers the command again', async () => { + submitReply = errorReply(404, 'not_found') + const result = await record('0.1.8-draft.2') + expect(result.code).toBe(2) + expect(result.stderr).not.toContain('update the CLI') + expect(lines(result.stderr).slice(-5)).toEqual([ + 'Reactiv could not find the submissions service (HTTP 404). Contact Reactiv if this continues.', + expect.stringMatching(/^Request id: \S+$/), + 'Then run:', + ' reactiv app submit --record 0.1.8-draft.2', + '', + ]) + }, 30_000) + + it('--record offers the same command again when the failure can pass', async () => { + submitReply = tooMany() + const result = await record('0.1.8-draft.2') + expect(result.code).toBe(2) + expect(result.stderr).not.toContain('published') + expect(lines(result.stderr).slice(-3)).toEqual(['Then run:', ' reactiv app submit --record 0.1.8-draft.2', '']) + }, 30_000) + + it.each([ + [['--dry-run'], '--dry-run=true cannot also be provided when using --record'], + ])('--record cannot be combined with %j', async (extra, message) => { + const result = await runCli(['app', 'submit', '--record', '0.1.8-draft.2', ...extra], {cwd: projectDir, env}) + expect(result.code).not.toBe(0) + expect(result.errorText).toContain(message) + expect(mock.requests).toEqual([]) + }, 30_000) + }) // Assembled at runtime so no credential-shaped literal sits in this file. const underscore = '_'