diff --git a/CLAUDE.md b/CLAUDE.md index d3e8a6b..f4aa91d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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--` 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). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6907aa1..aa315cc 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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). diff --git a/README.md b/README.md index 6b164af..8033e6d 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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). @@ -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 diff --git a/package.json b/package.json index 020bc9e..646b3c9 100644 --- a/package.json +++ b/package.json @@ -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", @@ -37,7 +36,7 @@ "typescript-eslint": "^8.73.0" }, "engines": { - "node": ">=22.0.0" + "node": ">=22.8.0" }, "files": [ "/dist" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c34e112..e921af4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -24,9 +24,6 @@ importers: bplist-parser: specifier: ^0.6.0 version: 0.6.0 - chalk: - specifier: ^6.0.0 - version: 6.0.1 citty: specifier: ^0.2.2 version: 0.2.2 @@ -564,10 +561,6 @@ packages: resolution: {integrity: sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==} engines: {node: '>=18'} - chalk@6.0.1: - resolution: {integrity: sha512-/Ce6KNm3vIbWdMlNna6RVIZ/ICQxnJxCicet5LBKK9ZffBkqzDw0xh9EiKSljdRtiIQ1S1z4YgcscUUGzNCWrA==} - engines: {node: '>=22'} - chokidar@5.0.0: resolution: {integrity: sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==} engines: {node: '>= 20.19.0'} @@ -1758,8 +1751,6 @@ snapshots: chai@6.3.0: {} - chalk@6.0.1: {} - chokidar@5.0.0: dependencies: readdirp: 5.1.1 diff --git a/src/commands/artifacts.ts b/src/commands/artifacts.ts index c0a5c2c..fa33f3f 100644 --- a/src/commands/artifacts.ts +++ b/src/commands/artifacts.ts @@ -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; @@ -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 }); diff --git a/src/commands/cloud.ts b/src/commands/cloud.ts index 867b041..97a12e6 100644 --- a/src/commands/cloud.ts +++ b/src/commands/cloud.ts @@ -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) diff --git a/src/commands/live.ts b/src/commands/live.ts index fa38a9c..273f30f 100644 --- a/src/commands/live.ts +++ b/src/commands/live.ts @@ -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; @@ -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 diff --git a/src/commands/login.ts b/src/commands/login.ts index 5ec68df..ac8e1ef 100644 --- a/src/commands/login.ts +++ b/src/commands/login.ts @@ -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 { @@ -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; diff --git a/src/mcp/context.ts b/src/mcp/context.ts index 175cbc9..80126f6 100644 --- a/src/mcp/context.ts +++ b/src/mcp/context.ts @@ -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 { diff --git a/src/utils/cli.ts b/src/utils/cli.ts index d9695c7..71d6da9 100644 --- a/src/utils/cli.ts +++ b/src/utils/cli.ts @@ -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 @@ -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. @@ -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); }, diff --git a/src/utils/device-output.ts b/src/utils/device-output.ts index 094c26c..a2b19fe 100644 --- a/src/utils/device-output.ts +++ b/src/utils/device-output.ts @@ -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'; /** @@ -135,7 +135,7 @@ export async function runDeviceCommand( */ 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`); }; } diff --git a/src/utils/styling.ts b/src/utils/styling.ts index c034b3a..4a7d18f 100644 --- a/src/utils/styling.ts +++ b/src/utils/styling.ts @@ -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[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. @@ -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}`), @@ -189,8 +247,8 @@ export function table( 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(' ')); } diff --git a/test/unit/styling.test.ts b/test/unit/styling.test.ts new file mode 100644 index 0000000..c147f19 --- /dev/null +++ b/test/unit/styling.test.ts @@ -0,0 +1,75 @@ +import { expect } from 'chai'; +import { execFileSync } from 'node:child_process'; +import * as path from 'node:path'; +import { pathToFileURL } from 'node:url'; + +/** + * Colour support is decided once per process from its streams and env, so each + * case runs the styling module in a child process whose stdout and stderr are + * pipes, never the terminal mocha may be running in. + */ +const stylingUrl = pathToFileURL(path.resolve('src/utils/styling.ts')).href; + +const probe = ` +const { colors, forStderr, symbols } = await import(${JSON.stringify(stylingUrl)}); +process.stdout.write(JSON.stringify({ + bold: colors.bold('b'), + dimNull: colors.dim(null), + error: colors.error('e'), + forStderr: forStderr('\\u001B[31mx\\u001B[39m'), + success: symbols.success, + url: colors.url('u'), +})); +`; + +function runProbe(env: Record): Record { + const inherited = { ...process.env }; + delete inherited.FORCE_COLOR; + delete inherited.NO_COLOR; + delete inherited.NODE_DISABLE_COLORS; + const out = execFileSync( + process.execPath, + ['--import', 'tsx/esm', '--input-type=module', '-e', probe], + { encoding: 'utf8', env: { ...inherited, ...env }, stdio: ['ignore', 'pipe', 'pipe'] }, + ); + return JSON.parse(out) as Record; +} + +describe('styling', function () { + // Each case starts a node + tsx child process. + this.timeout(30_000); + + it('prints plain text when stdout is not a terminal', () => { + const r = runProbe({}); + expect(r.bold).to.equal('b'); + expect(r.error).to.equal('e'); + expect(r.url).to.equal('u'); + expect(r.success).to.equal('✓'); + }); + + it('strips colour bound for stderr when stderr is not a terminal', () => { + expect(runProbe({}).forStderr).to.equal('x'); + }); + + it('colours under FORCE_COLOR, nesting formats for url', () => { + const r = runProbe({ FORCE_COLOR: '1' }); + expect(r.bold).to.equal('\u001B[1mb\u001B[22m'); + expect(r.error).to.equal('\u001B[31me\u001B[39m'); + expect(r.url).to.equal('\u001B[36m\u001B[4mu\u001B[24m\u001B[39m'); + expect(r.success).to.equal('\u001B[32m✓\u001B[39m'); + }); + + it('prints plain text under FORCE_COLOR=0', () => { + const r = runProbe({ FORCE_COLOR: '0' }); + expect(r.url).to.equal('u'); + expect(r.forStderr).to.equal('x'); + }); + + it('keeps colour bound for stderr when stderr takes colour', () => { + expect(runProbe({ FORCE_COLOR: '1' }).forStderr).to.equal('\u001B[31mx\u001B[39m'); + }); + + it('prints a non-string value instead of throwing', () => { + expect(runProbe({}).dimNull).to.equal('null'); + }); +});