Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
- `pnpm build` — clean, compile TypeScript to `dist/`, and `chmod +x dist/index.js dist/mcp/index.js` so both published binaries are directly executable.
- `pnpm build:binaries` — `scripts/build-binaries.mjs` produces the bun-compiled, self-contained `dcd-<platform>-<arch>` binaries published to GitHub Releases (the install `dcd upgrade` self-updates). The platform/arch keys must stay in sync with `ASSET_BY_PLATFORM` in `src/commands/upgrade.ts`.
- `pnpm lint` — ESLint over `src/` and `test/`.
- `pnpm typecheck` — `tsc --noEmit -p tsconfig.test.json` over `src/` and `test/` (strict mode; `pnpm build` only compiles `src/`). Requires Node `>=22`.
- `pnpm typecheck` — `tsc --noEmit -p tsconfig.test.json` over `src/` and `test/` (strict mode; `pnpm build` only compiles `src/`). Requires Node `>=22.8`.
- `pnpm test` — runs `scripts/test-runner.mjs`: builds the CLI, boots the mock API if one is available, then runs mocha. TypeScript is loaded by **tsx** (`.mocharc.json`'s `node-option: ["import=tsx"]`), *not* ts-node — Mocha 11 imports specs as ESM, which bypasses the `require: ts-node/register` hook. The runner isolates `DCD_CONFIG_DIR` to a temp dir so tests never touch your real `dcd login` session.
- `pnpm test:unit` — the same runner with `--unit`: unit specs only, no mock API. **This is what CI runs.**
- Tests split into `test/unit/*` (pure, no backend) and `test/integration/*` (drive the built CLI against a Prism mock of the dcd API on port 3001).
Expand Down
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ is a one-time step. PRs cannot be merged until the CLA check is green.

## Getting started

You need **Node.js 22+** and **[pnpm](https://pnpm.io)** (`packageManager` pins
You need **Node.js 22.8+** and **[pnpm](https://pnpm.io)** (`packageManager` pins
the exact version; [Corepack](https://nodejs.org/api/corepack.html) will pick it
up automatically).

Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ On Windows:
irm https://get.devicecloud.dev/install.ps1 | iex
```

Or via npm if you already have Node 22+:
Or via npm if you already have Node 22.8+:

```sh-session
$ npm install -g @devicecloud.dev/dcd
Expand Down Expand Up @@ -105,7 +105,7 @@ $ claude mcp add --scope user devicecloud -- dcd mcp
$ codex mcp add devicecloud -- dcd mcp
```

If you use the npm package instead of the standalone binary, the command is `npx` with `"args": ["-y", "@devicecloud.dev/dcd", "mcp"]`. That needs Node 22 or newer on the app's PATH, and it checks npm each time it starts.
If you use the npm package instead of the standalone binary, the command is `npx` with `"args": ["-y", "@devicecloud.dev/dcd", "mcp"]`. That needs Node 22.8 or newer on the app's PATH, and it checks npm each time it starts.

It signs in the same way as the CLI: with your `dcd login` session, which it renews as it runs, or with `DEVICE_CLOUD_API_KEY`. Point it at a non-prod environment with `DCD_API_URL` (https, or plain http to `localhost` only).

Expand Down Expand Up @@ -168,7 +168,7 @@ Run `npx e2e run` with `DEVICE_CLOUD_API_KEY` set. The provider uploads `appPath

## Development

Requires Node 22+ and [pnpm](https://pnpm.io). `pnpm install` builds the CLI and installs the git hooks automatically.
Requires Node 22.8+ and [pnpm](https://pnpm.io). `pnpm install` builds the CLI and installs the git hooks automatically.

```sh-session
$ pnpm install # install deps, build, set up git hooks
Expand Down
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
"@modelcontextprotocol/sdk": "^1.31.0",
"@supabase/supabase-js": "^2.108.2",
"bplist-parser": "^0.6.0",
"chalk": "^6.0.0",
"citty": "^0.2.2",
"js-yaml": "^5.2.2",
"node-stream-zip": "^1.15.0",
Expand Down Expand Up @@ -37,7 +36,7 @@
"typescript-eslint": "^8.73.0"
},
"engines": {
"node": ">=22.0.0"
"node": ">=22.8.0"
},
"files": [
"/dist"
Expand Down
9 changes: 0 additions & 9 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion src/commands/artifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
import { resolveAuth } from '../utils/auth.js';
import { CliError, logger, validateEnum } from '../utils/cli.js';
import { resolveApiUrl } from '../utils/config-store.js';
import { forStderr } from '../utils/styling.js';
import { ui } from '../utils/ui.js';

const DOWNLOAD_OPTIONS = ['ALL', 'FAILED'] as const;
Expand Down Expand Up @@ -104,7 +105,7 @@ export const artifactsCommand = defineCommand({
// deprecation notice nor the API's submit warning reaches it.
const deprecation = reportFormatDeprecation(report);
if (deprecation) {
process.stderr.write(`${ui.deprecation(deprecation)}\n`);
process.stderr.write(`${forStderr(ui.deprecation(deprecation))}\n`);
}

const auth = await resolveAuth({ apiKeyFlag });
Expand Down
2 changes: 1 addition & 1 deletion src/commands/cloud.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1012,7 +1012,7 @@ export const cloudCommand = defineCommand({
if (!results?.length) {
throw new CliError('No tests created: ' + message);
}
out(`${ui.success('Submitted')} ${colors.dim(message)}`);
out(message ? `${ui.success('Submitted')} ${colors.dim(message)}` : ui.success('Submitted'));

const testNames = results
.map((r) => r.test_file_name)
Expand Down
4 changes: 2 additions & 2 deletions src/commands/live.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import type { LiveSession } from '../types/domain/live.types.js';
import { resolveAuth } from '../utils/auth.js';
import { CliError, logger, validateEnum, wantsJson } from '../utils/cli.js';
import { resolveApiUrl } from '../utils/config-store.js';
import { colors, formatUrl } from '../utils/styling.js';
import { colors, formatUrl, forStderr } from '../utils/styling.js';
import { type Field, ui } from '../utils/ui.js';

const PLATFORM_OPTIONS = ['android', 'ios'] as const;
Expand Down Expand Up @@ -722,7 +722,7 @@ export const liveCommand = defineCommand({
subCommands,
// Runs before any subcommand. On stderr, so --json output is unchanged.
setup() {
process.stderr.write(`${LIVE_DEPRECATION}\n`);
process.stderr.write(`${forStderr(LIVE_DEPRECATION)}\n`);
},
// citty's runCommand does not early-return after dispatching to a
// subcommand — it still invokes the parent `run` afterwards. So when a
Expand Down
4 changes: 2 additions & 2 deletions src/commands/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ import { canPrompt } from '../utils/ci.js';
import { CliError, logger } from '../utils/cli.js';
import { readConfig, writeConfig } from '../utils/config-store.js';
import { fetchOrgs, selectOrg } from '../utils/orgs.js';
import { colors } from '../utils/styling.js';
import { colors, forStderr } from '../utils/styling.js';
import { ui } from '../utils/ui.js';

interface ClaimedSession {
Expand Down Expand Up @@ -105,7 +105,7 @@ export const loginCommand = defineCommand({
// Login is interactive, so under --json the human rows and prompts move to
// stderr (the user still needs the URL) and stdout gets only the result.
const say = (m: string) => {
if (json) process.stderr.write(`${m}\n`);
if (json) process.stderr.write(`${forStderr(m)}\n`);
else logger.log(m);
};
const promptOutput = json ? process.stderr : undefined;
Expand Down
3 changes: 2 additions & 1 deletion src/mcp/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,11 @@
import type { AuthContext } from '../types/domain/auth.types.js';
import { isAuthExpiring, resolveAuth } from '../utils/auth.js';
import { resolveApiUrl } from '../utils/config-store.js';
import { forStderr } from '../utils/styling.js';

/** Write a line to stderr. Safe under stdio transport; stdout is reserved. */
export function logStderr(message: string): void {
process.stderr.write(`${message}\n`);
process.stderr.write(`${forStderr(message)}\n`);
}

export interface McpContext {
Expand Down
6 changes: 3 additions & 3 deletions src/utils/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { stripVTControlCharacters } from 'node:util';

import { telemetry } from '../services/telemetry.service.js';

import { symbols } from './styling.js';
import { forStderr, symbols } from './styling.js';

// Resolve version at runtime. The bun-compiled binary can't read package.json
// off disk (it isn't bundled next to the embedded module), so the build stamps
Expand Down Expand Up @@ -73,7 +73,7 @@ export const logger: Logger = {
console.log(message);
},
warn(message: string): void {
console.warn(symbols.warning + ' ' + message);
console.warn(forStderr(symbols.warning + ' ' + message));
},
json(value: unknown): void {
// The one stdout write under --json; everything else is gated off.
Expand All @@ -92,7 +92,7 @@ export const logger: Logger = {
} else {
// The literal "Error:" prefix is important for tests and for grep-friendly
// CI logs — it survives color stripping and matches /error/i assertions.
console.error(symbols.error + ' Error: ' + text);
console.error(forStderr(symbols.error + ' Error: ' + text));
}
return logger.fail(message, opts.exit ?? 1);
},
Expand Down
4 changes: 2 additions & 2 deletions src/utils/device-output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { DeviceApiError, DeviceGateway } from '../gateways/device-gateway.js';
import type { AuthContext } from '../types/domain/auth.types.js';
import type { DeviceHumanStatus, DeviceSession, DeviceSessionStarter } from '../types/domain/device-session.types.js';
import { CliError, logger } from './cli.js';
import { colors, formatUrl } from './styling.js';
import { colors, formatUrl, forStderr } from './styling.js';
import { type Field, ui } from './ui.js';

/**
Expand Down Expand Up @@ -135,7 +135,7 @@ export async function runDeviceCommand<T>(
*/
export function deviceProgress(json: boolean): (message: string) => void {
return (message) => {
if (!json) process.stderr.write(`${message}\n`);
if (!json) process.stderr.write(`${forStderr(message)}\n`);
};
}

Expand Down
102 changes: 80 additions & 22 deletions src/utils/styling.ts
Original file line number Diff line number Diff line change
@@ -1,46 +1,104 @@
import chalk from 'chalk';
import { styleText } from 'node:util';

import { findEnvByApiUrl } from '../config/environments.js';

/**
* Centralized styling utilities for CLI output
* Provides consistent, developer-friendly visual formatting
*
* Colours come from Node's `util.styleText`. Text is styled only when stdout
* takes colour (see {@link takesColour}); text bound for stderr goes through
* {@link forStderr}.
*/

/** Strip ANSI color escape sequences for visible-width calculations. */
// eslint-disable-next-line no-control-regex -- matches ANSI escape sequences
export const stripAnsi = (s: string): string => s.replace(/\u001B\[[0-9;]*m/g, '');

/**
* Whether `stream` takes colour, by the rule Node's `styleText` applies:
* `FORCE_COLOR` decides when set; otherwise the stream must be a terminal
* whose colour depth (which folds in `NO_COLOR`, `NODE_DISABLE_COLORS` and
* `TERM=dumb`) is above monochrome.
*
* Decided here rather than left to `styleText`'s own check because not every
* runtime makes that check: bun 1.3, which compiles the standalone binaries,
* and Node before 22.8 colour unconditionally.
*/
function takesColour(stream: NodeJS.WriteStream): boolean {
const force = process.env.FORCE_COLOR;
if (force !== undefined) return ['', '1', '2', '3', 'true'].includes(force);
return (
stream.isTTY === true &&
(typeof stream.getColorDepth !== 'function' || stream.getColorDepth() > 2)
);
}

/**
* One format at a time; combined styles nest single-format calls, which every
* supported runtime handles alike, where an array of formats does not.
*/
type StyleFormat = Extract<Parameters<typeof styleText>[0], string>;

/**
* Apply `format` to `text` when stdout takes colour. `styleText` throws on
* anything but a string, so a value the types call a string but an API sent
* as null or a number is printed, never fatal.
*/
function style(format: StyleFormat, text: string): string {
const s = String(text);
return takesColour(process.stdout) ? styleText(format, s, { validateStream: false }) : s;
}

const paint =
(format: StyleFormat) =>
(text: string): string =>
style(format, text);

const cyan = paint('cyan');
const underline = paint('underline');

/**
* Status symbols with associated colors
*/
export const symbols = {
cancelled: chalk.gray('⊘'),
deprecation: chalk.red('⚠'),
error: chalk.red('✗'),
info: chalk.blue('ℹ'),
pending: chalk.yellow('⏸'),
queued: chalk.gray('⏳'),
running: chalk.blue('▶'),
success: chalk.green('✓'),
unknown: chalk.gray('?'),
warning: chalk.yellow('⚠'),
cancelled: style('gray', '⊘'),
deprecation: style('red', '⚠'),
error: style('red', '✗'),
info: style('blue', 'ℹ'),
pending: style('yellow', '⏸'),
queued: style('gray', '⏳'),
running: style('blue', '▶'),
success: style('green', '✓'),
unknown: style('gray', '?'),
warning: style('yellow', '⚠'),
} as const;

/**
* Color utility functions for semantic styling
*/
export const colors = {
bold: chalk.bold,
dim: chalk.gray,
error: chalk.red,
highlight: chalk.cyan,
info: chalk.blue,
success: chalk.green,
url: chalk.cyan.underline,
warning: chalk.yellow,
bold: paint('bold'),
dim: paint('gray'),
error: paint('red'),
highlight: cyan,
info: paint('blue'),
success: paint('green'),
url: (text: string): string => cyan(underline(text)),
warning: paint('yellow'),
} as const;

/**
* Prepare styled text for stderr. The palette above follows stdout, so when
* stdout is a terminal but stderr is not (`dcd cloud 2> err.log`), the colour
* codes are stripped here to keep the file plain.
* @param text - Text that may carry colour codes from {@link colors} or {@link symbols}
* @returns The text, without colour codes unless stderr takes colour
*/
export function forStderr(text: string): string {
return takesColour(process.stderr) ? text : stripAnsi(text);
}

/**
* Structural glyphs that give the CLI its tree-shaped layout. `section` marks a
* top-level heading; `branch` opens the group of detail rows beneath it.
Expand Down Expand Up @@ -148,7 +206,7 @@ export function formatTestSummary(summary: {
total: number;
}): string {
const parts = [
chalk.bold(`${summary.completed}/${summary.total}`),
colors.bold(`${summary.completed}/${summary.total}`),
colors.success(`✓ ${summary.passed}`),
colors.error(`✗ ${summary.failed}`),
colors.info(`▶ ${summary.running}`),
Expand Down Expand Up @@ -189,8 +247,8 @@ export function table<T>(
return s + ' '.repeat(Math.max(0, width - visibleLen));
};

printLine(headers.map((h, i) => pad(chalk.bold(h), widths[i])).join(' '));
printLine(widths.map((w) => chalk.gray('─'.repeat(w))).join(' '));
printLine(headers.map((h, i) => pad(colors.bold(h), widths[i])).join(' '));
printLine(widths.map((w) => colors.dim('─'.repeat(w))).join(' '));
for (const row of cells) {
printLine(row.map((c, i) => pad(c, widths[i])).join(' '));
}
Expand Down
Loading
Loading