@devicecloud.dev/dcd 5.15.0 → 5.16.0-beta.2

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.
package/README.md CHANGED
@@ -16,7 +16,7 @@ On Windows:
16
16
  irm https://get.devicecloud.dev/install.ps1 | iex
17
17
  ```
18
18
 
19
- Or via npm if you already have Node 22+:
19
+ Or via npm if you already have Node 22.8+:
20
20
 
21
21
  ```sh-session
22
22
  $ npm install -g @devicecloud.dev/dcd
@@ -105,7 +105,7 @@ $ claude mcp add --scope user devicecloud -- dcd mcp
105
105
  $ codex mcp add devicecloud -- dcd mcp
106
106
  ```
107
107
 
108
- 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.
108
+ 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.
109
109
 
110
110
  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).
111
111
 
@@ -144,10 +144,31 @@ The npm package also ships `dcd-mcp`, an older server with the same `dcd_*` tool
144
144
 
145
145
  `--package` matters: the package's default bin is `dcd`, so `npx @devicecloud.dev/dcd dcd-mcp` would run `dcd dcd-mcp` (an unknown command) instead of the server. It signs in like `dcd mcp`, and takes `--read-only` and `DCD_MCP_READONLY=1` the same way.
146
146
 
147
+ ## e2e tests on DeviceCloud devices (early access)
148
+
149
+ `@devicecloud.dev/dcd/e2e` is a device provider for [e2e](https://github.com/e2e-inc/e2e). Each e2e worker gets its own DeviceCloud device session, and e2e drives the device directly. The session shows in the console, is recorded, and is billed like any other. Your organization needs this turned on by DeviceCloud first.
150
+
151
+ ```ts
152
+ // e2e.config.ts
153
+ import type { E2EConfig } from 'e2e';
154
+ import { mobile } from '@e2e-dev/mobile';
155
+ import { deviceCloud } from '@devicecloud.dev/dcd/e2e';
156
+
157
+ const engine = mobile({ platform: 'android', device: deviceCloud() });
158
+
159
+ export default {
160
+ targets: [{ name: 'android', engine, app: { bundleId: 'com.example.app', appPath: './build/app.apk' } }],
161
+ // The first screen read after a launch can take a few seconds.
162
+ assertionTimeout: 20_000,
163
+ } satisfies E2EConfig;
164
+ ```
165
+
166
+ Run `npx e2e run` with `DEVICE_CLOUD_API_KEY` set. The provider uploads `appPath` once per run and each session installs it, so e2e installs nothing itself. To use a build you already uploaded, pass `deviceCloud({ appBinaryId })`. It also takes `model`, `os` and `maxDurationMin`. Each session's console link is printed as the run starts, and the session is stopped when e2e is done with it.
167
+
147
168
 
148
169
  ## Development
149
170
 
150
- Requires Node 22+ and [pnpm](https://pnpm.io). `pnpm install` builds the CLI and installs the git hooks automatically.
171
+ Requires Node 22.8+ and [pnpm](https://pnpm.io). `pnpm install` builds the CLI and installs the git hooks automatically.
151
172
 
152
173
  ```sh-session
153
174
  $ pnpm install # install deps, build, set up git hooks
@@ -5,6 +5,7 @@ import { downloadsSucceeded, ReportDownloadService, reportFormatDeprecation, } f
5
5
  import { resolveAuth } from '../utils/auth.js';
6
6
  import { CliError, logger, validateEnum } from '../utils/cli.js';
7
7
  import { resolveApiUrl } from '../utils/config-store.js';
8
+ import { forStderr } from '../utils/styling.js';
8
9
  import { ui } from '../utils/ui.js';
9
10
  const DOWNLOAD_OPTIONS = ['ALL', 'FAILED'];
10
11
  const REPORT_OPTIONS = ['allure', 'html', 'html-detailed', 'junit'];
@@ -79,7 +80,7 @@ export const artifactsCommand = defineCommand({
79
80
  // deprecation notice nor the API's submit warning reaches it.
80
81
  const deprecation = reportFormatDeprecation(report);
81
82
  if (deprecation) {
82
- process.stderr.write(`${ui.deprecation(deprecation)}\n`);
83
+ process.stderr.write(`${forStderr(ui.deprecation(deprecation))}\n`);
83
84
  }
84
85
  const auth = await resolveAuth({ apiKeyFlag });
85
86
  if (downloadArtifacts && report) {
@@ -1,4 +1,3 @@
1
- /* eslint-disable complexity */
2
1
  import { defineCommand } from 'citty';
3
2
  import { existsSync } from 'node:fs';
4
3
  import * as path from 'node:path';
@@ -37,7 +36,6 @@ process.on('warning', (warning) => {
37
36
  warning.message.includes('punycode')) {
38
37
  return;
39
38
  }
40
- // eslint-disable-next-line no-console
41
39
  console.warn(warning.stack ?? `${warning.name}: ${warning.message}`);
42
40
  });
43
41
  const DOWNLOAD_OPTIONS = ['ALL', 'FAILED'];
@@ -75,7 +73,6 @@ export const cloudCommand = defineCommand({
75
73
  description: 'The flow file to run against the app, e.g. test.yaml',
76
74
  },
77
75
  },
78
- // eslint-disable-next-line complexity
79
76
  async run({ args, rawArgs }) {
80
77
  const cliVersion = getCliVersion();
81
78
  const deviceValidationService = new DeviceValidationService();
@@ -716,7 +713,7 @@ export const cloudCommand = defineCommand({
716
713
  if (!results?.length) {
717
714
  throw new CliError('No tests created: ' + message);
718
715
  }
719
- out(`${ui.success('Submitted')} ${colors.dim(message)}`);
716
+ out(message ? `${ui.success('Submitted')} ${colors.dim(message)}` : ui.success('Submitted'));
720
717
  const testNames = results
721
718
  .map((r) => r.test_file_name)
722
719
  .sort((a, b) => a.localeCompare(b))
@@ -7,7 +7,7 @@ import { ApiGateway } from '../gateways/api-gateway.js';
7
7
  import { resolveAuth } from '../utils/auth.js';
8
8
  import { CliError, logger, validateEnum, wantsJson } from '../utils/cli.js';
9
9
  import { resolveApiUrl } from '../utils/config-store.js';
10
- import { colors, formatUrl } from '../utils/styling.js';
10
+ import { colors, formatUrl, forStderr } from '../utils/styling.js';
11
11
  import { ui } from '../utils/ui.js';
12
12
  const PLATFORM_OPTIONS = ['android', 'ios'];
13
13
  /** Printed to stderr by every `dcd live` command. */
@@ -600,7 +600,7 @@ export const liveCommand = defineCommand({
600
600
  subCommands,
601
601
  // Runs before any subcommand. On stderr, so --json output is unchanged.
602
602
  setup() {
603
- process.stderr.write(`${LIVE_DEPRECATION}\n`);
603
+ process.stderr.write(`${forStderr(LIVE_DEPRECATION)}\n`);
604
604
  },
605
605
  // citty's runCommand does not early-return after dispatching to a
606
606
  // subcommand — it still invokes the parent `run` afterwards. So when a
@@ -41,7 +41,7 @@ import { canPrompt } from '../utils/ci.js';
41
41
  import { CliError, logger } from '../utils/cli.js';
42
42
  import { readConfig, writeConfig } from '../utils/config-store.js';
43
43
  import { fetchOrgs, selectOrg } from '../utils/orgs.js';
44
- import { colors } from '../utils/styling.js';
44
+ import { colors, forStderr } from '../utils/styling.js';
45
45
  import { ui } from '../utils/ui.js';
46
46
  const LOGIN_TIMEOUT_MS = 10 * 60 * 1000;
47
47
  // 1s feels snappy after the user clicks "Authorize" in the browser. The api
@@ -90,7 +90,7 @@ export const loginCommand = defineCommand({
90
90
  // stderr (the user still needs the URL) and stdout gets only the result.
91
91
  const say = (m) => {
92
92
  if (json)
93
- process.stderr.write(`${m}\n`);
93
+ process.stderr.write(`${forStderr(m)}\n`);
94
94
  else
95
95
  logger.log(m);
96
96
  };
@@ -52,7 +52,6 @@ export const statusCommand = defineCommand({
52
52
  description: 'UUID of the upload to check status for',
53
53
  },
54
54
  },
55
- // eslint-disable-next-line complexity
56
55
  async run({ args }) {
57
56
  const apiKeyFlag = args['api-key'];
58
57
  const apiUrl = resolveApiUrl(args['api-url']);
@@ -0,0 +1,4 @@
1
+ import { type DeviceCloudOptions, type DeviceCloudProvider } from './provider.js';
2
+ export type { DeviceCloudOptions, DeviceCloudProvider, E2eDeviceLease, E2eDeviceRequest, E2eReleaseContext, } from './provider.js';
3
+ /** A DeviceCloud device provider, for `mobile({ device })` in an e2e config. */
4
+ export declare function deviceCloud(options?: DeviceCloudOptions): DeviceCloudProvider;
@@ -0,0 +1,41 @@
1
+ /**
2
+ * `@devicecloud.dev/dcd/e2e`: run e2e (https://github.com/e2e-inc/e2e) tests
3
+ * on DeviceCloud devices.
4
+ *
5
+ * import { mobile } from '@e2e-dev/mobile';
6
+ * import { deviceCloud } from '@devicecloud.dev/dcd/e2e';
7
+ *
8
+ * const engine = mobile({ platform: 'android', device: deviceCloud() });
9
+ *
10
+ * Each e2e worker gets its own DeviceCloud device session, which shows in the
11
+ * console, is recorded, and is billed like any other. Reads
12
+ * `DEVICE_CLOUD_API_KEY` from the run's environment. Early access: the
13
+ * organization needs it turned on by DeviceCloud.
14
+ *
15
+ * Importing this module has no side effects; it does not start the CLI.
16
+ */
17
+ import { uploadLocalApp } from '../utils/app-upload.js';
18
+ import { getCliVersion } from '../utils/cli.js';
19
+ import { createProvider, } from './provider.js';
20
+ /** A DeviceCloud device provider, for `mobile({ device })` in an e2e config. */
21
+ export function deviceCloud(options = {}) {
22
+ return createProvider(options, {
23
+ fetch: (input, init) => fetch(input, init),
24
+ pollMs: 3000,
25
+ startTimeoutMs: 20 * 60_000,
26
+ upload: ({ apiKey, apiUrl, filePath, log }) => uploadLocalApp({
27
+ apiUrl,
28
+ auth: {
29
+ headers: {
30
+ 'x-app-api-key': apiKey,
31
+ 'x-dcd-cli-version': getCliVersion(),
32
+ },
33
+ mode: 'apiKey',
34
+ },
35
+ filePath,
36
+ log,
37
+ showProgress: false,
38
+ }),
39
+ version: getCliVersion(),
40
+ });
41
+ }
@@ -0,0 +1,80 @@
1
+ /** What e2e asks for: one device for one worker slot of a run. */
2
+ export interface E2eDeviceRequest {
3
+ readonly platform: 'android' | 'ios';
4
+ /** The agent-device version the e2e client speaks. */
5
+ readonly agentDeviceVersion: string;
6
+ /** The target's `app.bundleId`, when the config names one. */
7
+ readonly app?: string | undefined;
8
+ /** The target's `app.appPath`, resolved to an absolute path, when the config names one. */
9
+ readonly appPath?: string | undefined;
10
+ /** The run's environment. A provider reads its credentials from here, never `process.env`. */
11
+ readonly env: Readonly<Record<string, string | undefined>>;
12
+ /** Aborts when the run is interrupted. */
13
+ readonly signal: AbortSignal;
14
+ /** One line of progress in the run's output. */
15
+ readonly log: (line: string) => void;
16
+ }
17
+ /** One leased device, as `acquire` returns it and `release` gets it back. */
18
+ export interface E2eDeviceLease {
19
+ /** The device session's id. */
20
+ readonly id: string;
21
+ readonly daemon?: {
22
+ readonly authToken: string;
23
+ readonly baseUrl: string;
24
+ } | undefined;
25
+ readonly deviceId?: string | undefined;
26
+ /** The bundle id or package of the build this provider installed from the request's `appPath`. */
27
+ readonly installedApp?: string | undefined;
28
+ }
29
+ /** Handed to `release`, once per lease at the end of the run. */
30
+ export interface E2eReleaseContext {
31
+ readonly env: Readonly<Record<string, string | undefined>>;
32
+ readonly signal: AbortSignal;
33
+ readonly log: (line: string) => void;
34
+ }
35
+ /** A source of DeviceCloud devices for e2e, the shape of `@e2e-dev/mobile`'s `DeviceProvider`. */
36
+ export interface DeviceCloudProvider {
37
+ readonly name: string;
38
+ acquire(request: E2eDeviceRequest): Promise<E2eDeviceLease>;
39
+ release(lease: E2eDeviceLease, context: E2eReleaseContext): Promise<void>;
40
+ }
41
+ export interface DeviceCloudOptions {
42
+ /**
43
+ * The DeviceCloud API key. Without it, `DEVICE_CLOUD_API_KEY` from the run's
44
+ * environment. The key needs access to device sessions.
45
+ */
46
+ apiKey?: string;
47
+ /** The DeviceCloud API. Without it, `DCD_API_URL` from the run's environment, then https://api.devicecloud.dev. */
48
+ apiUrl?: string;
49
+ /**
50
+ * A build already uploaded (the id `dcd upload` prints). Without it, the
51
+ * provider uploads the target's `app.appPath`, when the config names one,
52
+ * once per run. Either way the session installs the build, and e2e
53
+ * installs nothing itself.
54
+ */
55
+ appBinaryId?: string;
56
+ /** Device model, as `GET /device/models` lists them. The platform's default without. */
57
+ model?: string;
58
+ /** OS version for that model. Its default without. */
59
+ os?: string;
60
+ /** How long each session may last, in minutes. The organization's limit without. */
61
+ maxDurationMin?: number;
62
+ }
63
+ /** What the provider calls out to: the network, the upload, and the clock. */
64
+ export interface ProviderDeps {
65
+ fetch: typeof fetch;
66
+ /** Uploads a local build the way `dcd upload` does and answers its binary id. */
67
+ upload: (args: {
68
+ apiKey: string;
69
+ apiUrl: string;
70
+ filePath: string;
71
+ log: (line: string) => void;
72
+ }) => Promise<string>;
73
+ /** Sent as `x-dcd-cli-version`, so the API knows which provider version called. */
74
+ version: string;
75
+ /** Between polls. */
76
+ pollMs: number;
77
+ /** How long a session may take to be ready: queued, starting, installing. */
78
+ startTimeoutMs: number;
79
+ }
80
+ export declare function createProvider(options: DeviceCloudOptions, deps: ProviderDeps): DeviceCloudProvider;
@@ -0,0 +1,233 @@
1
+ /**
2
+ * The DeviceCloud device provider for e2e (https://github.com/e2e-inc/e2e),
3
+ * published as `@devicecloud.dev/dcd/e2e`. The public entry point is
4
+ * `./index.ts`; this module takes its dependencies as arguments so the unit
5
+ * tests can replace the network and the upload.
6
+ *
7
+ * Each e2e worker slot gets its own DeviceCloud device session. The provider
8
+ * starts it, waits until its device is up and the build is installed, then
9
+ * asks for the device's engine (`POST /device/sessions/:id/engine`). The
10
+ * answer is the address of the session's own agent-device daemon, reached
11
+ * through DeviceCloud's relay, and a token for it: that is what an e2e lease
12
+ * is. e2e then drives the device directly, so its calls do not pass through
13
+ * the API's command queue. `release` stops the session.
14
+ *
15
+ * The types below describe e2e's provider contract (`DeviceProvider` in
16
+ * `@e2e-dev/mobile`) by shape, for the fields this provider uses, so the
17
+ * package does not depend on e2e. An object of this type can be passed to
18
+ * `mobile({ device })`.
19
+ */
20
+ import { checkApiUrl } from '../utils/api-url.js';
21
+ const DEFAULT_API_URL = 'https://api.devicecloud.dev';
22
+ const ENDED = new Set(['expired', 'failed', 'released']);
23
+ /** How many times to ask for the engine while the device is up but not quite ready for it (425). */
24
+ const ENGINE_ATTEMPTS = 10;
25
+ /**
26
+ * How many times a request that is safe to repeat is sent again after the
27
+ * network failed it (no answer at all). Polls run for minutes, and one lost
28
+ * request must not end a run. Never a session start: sent twice, it could
29
+ * start two sessions.
30
+ */
31
+ const NETWORK_RETRIES = 4;
32
+ const wait = (ms, signal) => new Promise((resolve, reject) => {
33
+ if (signal?.aborted) {
34
+ reject(signal.reason ?? new Error('Interrupted'));
35
+ return;
36
+ }
37
+ const onAbort = () => {
38
+ clearTimeout(timer);
39
+ reject(signal?.reason ?? new Error('Interrupted'));
40
+ };
41
+ const timer = setTimeout(() => {
42
+ signal?.removeEventListener('abort', onAbort);
43
+ resolve();
44
+ }, ms);
45
+ signal?.addEventListener('abort', onAbort, { once: true });
46
+ });
47
+ /** The API's own words for a failed request: its message, or the start of the body. */
48
+ function failure(what, reply) {
49
+ const message = reply.json?.message;
50
+ const said = Array.isArray(message)
51
+ ? message.join('; ')
52
+ : String(message ?? reply.text).slice(0, 300);
53
+ const code = typeof reply.json?.error === 'string' && reply.json.error !== said
54
+ ? ` (${reply.json.error})`
55
+ : '';
56
+ return new Error(`DeviceCloud: ${what} answered ${reply.status}: ${said}${code}`);
57
+ }
58
+ /** Where to send requests, and with which key: checked before the key goes anywhere. */
59
+ function connection(options, env, log) {
60
+ const apiKey = (options.apiKey ?? env.DEVICE_CLOUD_API_KEY ?? '').trim();
61
+ if (!apiKey) {
62
+ throw new Error('DeviceCloud: no API key. Set DEVICE_CLOUD_API_KEY in the environment e2e runs with, or pass apiKey to deviceCloud().');
63
+ }
64
+ const raw = (options.apiUrl ?? env.DCD_API_URL ?? '').trim() || DEFAULT_API_URL;
65
+ const check = checkApiUrl(raw);
66
+ if (!check.ok)
67
+ throw new Error(`DeviceCloud: ${check.reason}`);
68
+ if (check.warning)
69
+ log(check.warning);
70
+ return { apiKey, apiUrl: check.origin };
71
+ }
72
+ export function createProvider(options, deps) {
73
+ // One upload per build per run: e2e acquires every worker slot at once.
74
+ const uploads = new Map();
75
+ const client = (apiKey, apiUrl) => async (method, path, body, signal, { repeatable = method !== 'POST' } = {}) => {
76
+ let response;
77
+ for (let attempt = 0;; attempt++) {
78
+ try {
79
+ response = await deps.fetch(`${apiUrl}${path}`, {
80
+ headers: {
81
+ 'x-app-api-key': apiKey,
82
+ 'x-dcd-cli-version': deps.version,
83
+ 'x-dcd-source': 'cli',
84
+ ...(body === undefined
85
+ ? {}
86
+ : { 'content-type': 'application/json' }),
87
+ },
88
+ method,
89
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
90
+ ...(signal ? { signal } : {}),
91
+ });
92
+ break;
93
+ }
94
+ catch (error) {
95
+ if (signal?.aborted)
96
+ throw signal.reason ?? error;
97
+ if (!repeatable || attempt >= NETWORK_RETRIES) {
98
+ const cause = error.cause;
99
+ const why = cause?.code ?? cause?.message ?? error.message;
100
+ throw new Error(`DeviceCloud: ${method} ${path} could not reach ${apiUrl} (${why})`, { cause: error });
101
+ }
102
+ await wait(deps.pollMs * (attempt + 1), signal);
103
+ }
104
+ }
105
+ const text = await response.text();
106
+ let json = null;
107
+ try {
108
+ json = JSON.parse(text);
109
+ }
110
+ catch {
111
+ // Not JSON: the status and the text say what happened.
112
+ }
113
+ return { json, status: response.status, text };
114
+ };
115
+ const binaryFor = async (request, apiKey, apiUrl) => {
116
+ if (options.appBinaryId) {
117
+ if (request.appPath)
118
+ request.log(`installing build ${options.appBinaryId}, not uploading ${request.appPath}`);
119
+ return options.appBinaryId;
120
+ }
121
+ if (!request.appPath)
122
+ return undefined;
123
+ let upload = uploads.get(request.appPath);
124
+ if (!upload) {
125
+ request.log(`uploading ${request.appPath}`);
126
+ upload = deps.upload({
127
+ apiKey,
128
+ apiUrl,
129
+ filePath: request.appPath,
130
+ log: request.log,
131
+ });
132
+ uploads.set(request.appPath, upload);
133
+ // A failed upload is tried again by the next run, not remembered.
134
+ upload.catch(() => uploads.delete(request.appPath));
135
+ }
136
+ return upload;
137
+ };
138
+ return {
139
+ async acquire(request) {
140
+ // e2e cannot install a build on a DeviceCloud device; the session does.
141
+ // e2e is told so (installedApp), which needs the build's bundle id.
142
+ if (request.appPath && !request.app) {
143
+ throw new Error("DeviceCloud: the target names app.appPath but not app.bundleId. Set app.bundleId to the build's bundle id or package name.");
144
+ }
145
+ const { apiKey, apiUrl } = connection(options, request.env, request.log);
146
+ const api = client(apiKey, apiUrl);
147
+ const binaryUploadId = await binaryFor(request, apiKey, apiUrl);
148
+ const started = await api('POST', '/device/sessions', {
149
+ clientLabel: 'e2e',
150
+ platform: request.platform,
151
+ ...(binaryUploadId ? { binaryUploadId } : {}),
152
+ ...(options.model ? { model: options.model } : {}),
153
+ ...(options.os ? { os: options.os } : {}),
154
+ ...(options.maxDurationMin
155
+ ? { maxDurationMin: options.maxDurationMin }
156
+ : {}),
157
+ }, request.signal);
158
+ if (started.status >= 300 || !started.json?.session)
159
+ throw failure('starting a device session', started);
160
+ let session = started.json.session;
161
+ const path = `/device/sessions/${encodeURIComponent(session.id)}`;
162
+ // A session left running is billed until it idles out.
163
+ const stop = () => api('DELETE', path).catch(() => { });
164
+ try {
165
+ if (session.monitor_url)
166
+ request.log(`watch at ${session.monitor_url}`);
167
+ // Queued, then starting, then installing: minutes when the fleet is busy.
168
+ const deadline = Date.now() + deps.startTimeoutMs;
169
+ for (;;) {
170
+ if (ENDED.has(session.state)) {
171
+ throw new Error(`DeviceCloud: session ${session.id} ended before it was ready (${session.release_reason ?? session.state})`);
172
+ }
173
+ if (session.install?.status === 'failed') {
174
+ throw new Error(`DeviceCloud: the build could not be installed on session ${session.id}: ${session.install.error ?? 'no reason given'}`);
175
+ }
176
+ if ((session.state === 'ready' || session.state === 'active') &&
177
+ session.install?.status !== 'installing')
178
+ break;
179
+ if (Date.now() > deadline) {
180
+ throw new Error(`DeviceCloud: session ${session.id} was not ready within ${Math.round(deps.startTimeoutMs / 60_000)} minutes`);
181
+ }
182
+ await wait(deps.pollMs, request.signal);
183
+ const read = await api('GET', path, undefined, request.signal);
184
+ if (read.status >= 300 || !read.json?.session)
185
+ throw failure('reading the device session', read);
186
+ session = read.json.session;
187
+ }
188
+ // The device is up; its engine may need a moment more (425).
189
+ let engine = null;
190
+ for (let attempt = 0; attempt < ENGINE_ATTEMPTS && !engine; attempt++) {
191
+ // Asking again is safe: the session has one engine, and every answer names it.
192
+ const asked = await api('POST', `${path}/engine`, {}, request.signal, { repeatable: true });
193
+ if (asked.status === 425) {
194
+ await wait(deps.pollMs, request.signal);
195
+ continue;
196
+ }
197
+ if (asked.status >= 300 || !asked.json?.engine)
198
+ throw failure("asking for the device's engine", asked);
199
+ engine = asked.json.engine;
200
+ }
201
+ if (!engine)
202
+ throw new Error(`DeviceCloud: session ${session.id} never became ready for e2e`);
203
+ if (engine.agentDeviceVersion &&
204
+ engine.agentDeviceVersion !== request.agentDeviceVersion) {
205
+ // Same wire protocol; said so that a difference can be read off a report.
206
+ request.log(`the device runs agent-device ${engine.agentDeviceVersion}, this e2e ${request.agentDeviceVersion}`);
207
+ }
208
+ return {
209
+ daemon: engine.daemon,
210
+ deviceId: engine.deviceId,
211
+ id: session.id,
212
+ // Only when the target names a build (appPath): the session installed one, so e2e installs nothing.
213
+ ...(request.appPath ? { installedApp: request.app } : {}),
214
+ };
215
+ }
216
+ catch (error) {
217
+ await stop();
218
+ throw error;
219
+ }
220
+ },
221
+ name: 'devicecloud',
222
+ async release(lease, context) {
223
+ const { apiKey, apiUrl } = connection(options, context.env, context.log);
224
+ const stopped = await client(apiKey, apiUrl)('DELETE', `/device/sessions/${encodeURIComponent(lease.id)}`, undefined, context.signal);
225
+ // 404 and 409: already gone, which is what was asked for.
226
+ if (stopped.status >= 300 &&
227
+ stopped.status !== 404 &&
228
+ stopped.status !== 409) {
229
+ throw failure(`stopping device session ${lease.id}`, stopped);
230
+ }
231
+ },
232
+ };
233
+ }
@@ -1,8 +1,9 @@
1
1
  import { isAuthExpiring, resolveAuth } from '../utils/auth.js';
2
2
  import { resolveApiUrl } from '../utils/config-store.js';
3
+ import { forStderr } from '../utils/styling.js';
3
4
  /** Write a line to stderr. Safe under stdio transport; stdout is reserved. */
4
5
  export function logStderr(message) {
5
- process.stderr.write(`${message}\n`);
6
+ process.stderr.write(`${forStderr(message)}\n`);
6
7
  }
7
8
  let cached = null;
8
9
  /**
package/dist/methods.js CHANGED
@@ -70,7 +70,6 @@ export const compressFilesFromRelativePath = async (basePath, files, commonRoot)
70
70
  return zipToBuffer(zipfile);
71
71
  };
72
72
  export const verifyAppZip = async (zipPath) => {
73
- // eslint-disable-next-line new-cap
74
73
  const zip = await new StreamZip.async({
75
74
  file: zipPath,
76
75
  storeEntries: true,
@@ -382,7 +382,6 @@ export async function plan(options) {
382
382
  : new Error(`Workspace does not contain any Flows: ${path.resolve(normalizedInput)}`);
383
383
  throw error;
384
384
  }
385
- // eslint-disable-next-line unicorn/no-array-reduce
386
385
  const configPerFlowFile = unfilteredFlowFiles.reduce((acc, filePath) => {
387
386
  const { config } = readTestYamlFileAsJson(filePath);
388
387
  acc[filePath] = config;
@@ -408,7 +407,6 @@ export async function plan(options) {
408
407
  throw new Error(`Include / Exclude tags did not match any Flows:\n\nInclude Tags:\n${allIncludeTags.join('\n')}\n\nExclude Tags:\n${allExcludeTags.join('\n')}`);
409
408
  }
410
409
  const allFiles = await Promise.all(allFlows.map((filePath) => checkDependencies(filePath))).then((results) => [...new Set(results.flat())]);
411
- // eslint-disable-next-line unicorn/no-array-reduce
412
410
  const pathsByName = allFlows.reduce((acc, filePath) => {
413
411
  const config = configPerFlowFile[filePath];
414
412
  const name = config?.name || path.parse(filePath).name;
@@ -98,7 +98,6 @@ export class MoropoService {
98
98
  await pipeline(source, fs.createWriteStream(zipPath));
99
99
  }
100
100
  async extractZipFile(zipPath, extractPath) {
101
- // eslint-disable-next-line new-cap
102
101
  const zip = new StreamZip.async({ file: zipPath });
103
102
  await zip.extract(null, extractPath);
104
103
  await zip.close();
@@ -167,7 +167,6 @@ export class ResultsPollingService {
167
167
  ticker?.unref?.();
168
168
  try {
169
169
  // Poll in a loop until all tests complete
170
- // eslint-disable-next-line no-constant-condition
171
170
  while (true) {
172
171
  try {
173
172
  nextPollAt = null;
@@ -313,7 +312,6 @@ export class ResultsPollingService {
313
312
  },
314
313
  },
315
314
  ...(hasFailedTests && {
316
- // eslint-disable-next-line camelcase
317
315
  fail_reason: {
318
316
  get(row) {
319
317
  return row.status === 'FAILED' && row.fail_reason
@@ -223,7 +223,6 @@ export class TestSubmissionService {
223
223
  return paths.map((p) => this.normalizeFilePath(p, commonRoot));
224
224
  }
225
225
  parseKeyValuePairs(pairs) {
226
- // eslint-disable-next-line unicorn/no-array-reduce
227
226
  return pairs.reduce((acc, cur) => {
228
227
  const [key, ...value] = cur.split('=');
229
228
  // handle case where value includes an equals sign
package/dist/utils/cli.js CHANGED
@@ -9,7 +9,7 @@
9
9
  import { readFileSync } from 'node:fs';
10
10
  import { stripVTControlCharacters } from 'node:util';
11
11
  import { telemetry } from '../services/telemetry.service.js';
12
- import { symbols } from './styling.js';
12
+ import { forStderr, symbols } from './styling.js';
13
13
  // Resolve version at runtime. The bun-compiled binary can't read package.json
14
14
  // off disk (it isn't bundled next to the embedded module), so the build stamps
15
15
  // the version in via `bun --define __DCD_CLI_VERSION__` (see
@@ -51,16 +51,13 @@ export class CliError extends Error {
51
51
  }
52
52
  export const logger = {
53
53
  log(message) {
54
- // eslint-disable-next-line no-console
55
54
  console.log(message);
56
55
  },
57
56
  warn(message) {
58
- // eslint-disable-next-line no-console
59
- console.warn(symbols.warning + ' ' + message);
57
+ console.warn(forStderr(symbols.warning + ' ' + message));
60
58
  },
61
59
  json(value) {
62
60
  // The one stdout write under --json; everything else is gated off.
63
- // eslint-disable-next-line no-console
64
61
  console.log(JSON.stringify(value, null, 2));
65
62
  },
66
63
  error(message, opts = {}) {
@@ -74,8 +71,7 @@ export const logger = {
74
71
  else {
75
72
  // The literal "Error:" prefix is important for tests and for grep-friendly
76
73
  // CI logs — it survives color stripping and matches /error/i assertions.
77
- // eslint-disable-next-line no-console
78
- console.error(symbols.error + ' Error: ' + text);
74
+ console.error(forStderr(symbols.error + ' Error: ' + text));
79
75
  }
80
76
  return logger.fail(message, opts.exit ?? 1);
81
77
  },
@@ -33,7 +33,6 @@ export function readConfig() {
33
33
  const raw = readFileSync(p, 'utf8');
34
34
  const parsed = JSON.parse(raw);
35
35
  if (parsed.version !== CONFIG_SCHEMA_VERSION) {
36
- // eslint-disable-next-line no-console
37
36
  console.warn(`Warning: config at ${p} was written by an incompatible CLI version (config version ${parsed.version}); ignoring it. Run \`dcd login\` to recreate it.`);
38
37
  return null;
39
38
  }
@@ -42,7 +41,6 @@ export function readConfig() {
42
41
  catch {
43
42
  // Surface the corruption instead of silently behaving as logged-out, so
44
43
  // downstream "Not authenticated" errors aren't mystifying.
45
- // eslint-disable-next-line no-console
46
44
  console.warn(`Warning: could not parse config at ${p}; treating as logged out. Run \`dcd login\` to recreate it.`);
47
45
  return null;
48
46
  }
@@ -1,7 +1,7 @@
1
1
  import { stripVTControlCharacters } from 'node:util';
2
2
  import { DeviceApiError, DeviceGateway } from '../gateways/device-gateway.js';
3
3
  import { CliError, logger } from './cli.js';
4
- import { colors, formatUrl } from './styling.js';
4
+ import { colors, formatUrl, forStderr } from './styling.js';
5
5
  import { ui } from './ui.js';
6
6
  /**
7
7
  * Exit codes for `dcd device` (dcd docs/device-v1-plan.md, section 4.2).
@@ -102,7 +102,7 @@ export async function runDeviceCommand(json, fn) {
102
102
  export function deviceProgress(json) {
103
103
  return (message) => {
104
104
  if (!json)
105
- process.stderr.write(`${message}\n`);
105
+ process.stderr.write(`${forStderr(message)}\n`);
106
106
  };
107
107
  }
108
108
  /**
@@ -90,7 +90,6 @@ class Action {
90
90
  this.current = null;
91
91
  this._status = '';
92
92
  if (line) {
93
- // eslint-disable-next-line no-console
94
93
  console.log(line);
95
94
  }
96
95
  }
@@ -100,14 +99,12 @@ class Action {
100
99
  if (line === this._lastPrinted)
101
100
  return;
102
101
  this._lastPrinted = line;
103
- // eslint-disable-next-line no-console
104
102
  console.log(line);
105
103
  }
106
104
  }
107
105
  export const ux = {
108
106
  action: new Action(),
109
107
  info(message) {
110
- // eslint-disable-next-line no-console
111
108
  console.log(message);
112
109
  },
113
110
  };
@@ -1,6 +1,10 @@
1
1
  /**
2
2
  * Centralized styling utilities for CLI output
3
3
  * Provides consistent, developer-friendly visual formatting
4
+ *
5
+ * Colours come from Node's `util.styleText`. Text is styled only when stdout
6
+ * takes colour (see {@link takesColour}); text bound for stderr goes through
7
+ * {@link forStderr}.
4
8
  */
5
9
  /** Strip ANSI color escape sequences for visible-width calculations. */
6
10
  export declare const stripAnsi: (s: string) => string;
@@ -23,15 +27,23 @@ export declare const symbols: {
23
27
  * Color utility functions for semantic styling
24
28
  */
25
29
  export declare const colors: {
26
- readonly bold: import("chalk").ChalkInstance;
27
- readonly dim: import("chalk").ChalkInstance;
28
- readonly error: import("chalk").ChalkInstance;
29
- readonly highlight: import("chalk").ChalkInstance;
30
- readonly info: import("chalk").ChalkInstance;
31
- readonly success: import("chalk").ChalkInstance;
32
- readonly url: import("chalk").ChalkInstance;
33
- readonly warning: import("chalk").ChalkInstance;
30
+ readonly bold: (text: string) => string;
31
+ readonly dim: (text: string) => string;
32
+ readonly error: (text: string) => string;
33
+ readonly highlight: (text: string) => string;
34
+ readonly info: (text: string) => string;
35
+ readonly success: (text: string) => string;
36
+ readonly url: (text: string) => string;
37
+ readonly warning: (text: string) => string;
34
38
  };
39
+ /**
40
+ * Prepare styled text for stderr. The palette above follows stdout, so when
41
+ * stdout is a terminal but stderr is not (`dcd cloud 2> err.log`), the colour
42
+ * codes are stripped here to keep the file plain.
43
+ * @param text - Text that may carry colour codes from {@link colors} or {@link symbols}
44
+ * @returns The text, without colour codes unless stderr takes colour
45
+ */
46
+ export declare function forStderr(text: string): string;
35
47
  /**
36
48
  * Structural glyphs that give the CLI its tree-shaped layout. `section` marks a
37
49
  * top-level heading; `branch` opens the group of detail rows beneath it.
@@ -1,40 +1,83 @@
1
- import chalk from 'chalk';
1
+ import { styleText } from 'node:util';
2
2
  import { findEnvByApiUrl } from '../config/environments.js';
3
3
  /**
4
4
  * Centralized styling utilities for CLI output
5
5
  * Provides consistent, developer-friendly visual formatting
6
+ *
7
+ * Colours come from Node's `util.styleText`. Text is styled only when stdout
8
+ * takes colour (see {@link takesColour}); text bound for stderr goes through
9
+ * {@link forStderr}.
6
10
  */
7
11
  /** Strip ANSI color escape sequences for visible-width calculations. */
8
12
  // eslint-disable-next-line no-control-regex -- matches ANSI escape sequences
9
13
  export const stripAnsi = (s) => s.replace(/\u001B\[[0-9;]*m/g, '');
14
+ /**
15
+ * Whether `stream` takes colour, by the rule Node's `styleText` applies:
16
+ * `FORCE_COLOR` decides when set; otherwise the stream must be a terminal
17
+ * whose colour depth (which folds in `NO_COLOR`, `NODE_DISABLE_COLORS` and
18
+ * `TERM=dumb`) is above monochrome.
19
+ *
20
+ * Decided here rather than left to `styleText`'s own check because not every
21
+ * runtime makes that check: bun 1.3, which compiles the standalone binaries,
22
+ * and Node before 22.8 colour unconditionally.
23
+ */
24
+ function takesColour(stream) {
25
+ const force = process.env.FORCE_COLOR;
26
+ if (force !== undefined)
27
+ return ['', '1', '2', '3', 'true'].includes(force);
28
+ return (stream.isTTY === true &&
29
+ (typeof stream.getColorDepth !== 'function' || stream.getColorDepth() > 2));
30
+ }
31
+ /**
32
+ * Apply `format` to `text` when stdout takes colour. `styleText` throws on
33
+ * anything but a string, so a value the types call a string but an API sent
34
+ * as null or a number is printed, never fatal.
35
+ */
36
+ function style(format, text) {
37
+ const s = String(text);
38
+ return takesColour(process.stdout) ? styleText(format, s, { validateStream: false }) : s;
39
+ }
40
+ const paint = (format) => (text) => style(format, text);
41
+ const cyan = paint('cyan');
42
+ const underline = paint('underline');
10
43
  /**
11
44
  * Status symbols with associated colors
12
45
  */
13
46
  export const symbols = {
14
- cancelled: chalk.gray('⊘'),
15
- deprecation: chalk.red('⚠'),
16
- error: chalk.red('✗'),
17
- info: chalk.blue('ℹ'),
18
- pending: chalk.yellow('⏸'),
19
- queued: chalk.gray('⏳'),
20
- running: chalk.blue('▶'),
21
- success: chalk.green('✓'),
22
- unknown: chalk.gray('?'),
23
- warning: chalk.yellow('⚠'),
47
+ cancelled: style('gray', '⊘'),
48
+ deprecation: style('red', '⚠'),
49
+ error: style('red', '✗'),
50
+ info: style('blue', 'ℹ'),
51
+ pending: style('yellow', '⏸'),
52
+ queued: style('gray', '⏳'),
53
+ running: style('blue', '▶'),
54
+ success: style('green', '✓'),
55
+ unknown: style('gray', '?'),
56
+ warning: style('yellow', '⚠'),
24
57
  };
25
58
  /**
26
59
  * Color utility functions for semantic styling
27
60
  */
28
61
  export const colors = {
29
- bold: chalk.bold,
30
- dim: chalk.gray,
31
- error: chalk.red,
32
- highlight: chalk.cyan,
33
- info: chalk.blue,
34
- success: chalk.green,
35
- url: chalk.cyan.underline,
36
- warning: chalk.yellow,
62
+ bold: paint('bold'),
63
+ dim: paint('gray'),
64
+ error: paint('red'),
65
+ highlight: cyan,
66
+ info: paint('blue'),
67
+ success: paint('green'),
68
+ url: (text) => cyan(underline(text)),
69
+ warning: paint('yellow'),
37
70
  };
71
+ /**
72
+ * Prepare styled text for stderr. The palette above follows stdout, so when
73
+ * stdout is a terminal but stderr is not (`dcd cloud 2> err.log`), the colour
74
+ * codes are stripped here to keep the file plain.
75
+ * @param text - Text that may carry colour codes from {@link colors} or {@link symbols}
76
+ * @returns The text, without colour codes unless stderr takes colour
77
+ */
78
+ export function forStderr(text) {
79
+ return takesColour(process.stderr) ? text : stripAnsi(text);
80
+ }
38
81
  /**
39
82
  * Structural glyphs that give the CLI its tree-shaped layout. `section` marks a
40
83
  * top-level heading; `branch` opens the group of detail rows beneath it.
@@ -119,7 +162,7 @@ export function formatId(id) {
119
162
  */
120
163
  export function formatTestSummary(summary) {
121
164
  const parts = [
122
- chalk.bold(`${summary.completed}/${summary.total}`),
165
+ colors.bold(`${summary.completed}/${summary.total}`),
123
166
  colors.success(`✓ ${summary.passed}`),
124
167
  colors.error(`✗ ${summary.failed}`),
125
168
  colors.info(`▶ ${summary.running}`),
@@ -135,7 +178,6 @@ export function formatTestSummary(summary) {
135
178
  */
136
179
  export function table(rows, columns, options = {}) {
137
180
  const printLine = options.printLine ?? ((line) => {
138
- // eslint-disable-next-line no-console
139
181
  console.log(line);
140
182
  });
141
183
  const keys = Object.keys(columns);
@@ -146,8 +188,8 @@ export function table(rows, columns, options = {}) {
146
188
  const visibleLen = stripAnsi(s).length;
147
189
  return s + ' '.repeat(Math.max(0, width - visibleLen));
148
190
  };
149
- printLine(headers.map((h, i) => pad(chalk.bold(h), widths[i])).join(' '));
150
- printLine(widths.map((w) => chalk.gray('─'.repeat(w))).join(' '));
191
+ printLine(headers.map((h, i) => pad(colors.bold(h), widths[i])).join(' '));
192
+ printLine(widths.map((w) => colors.dim('─'.repeat(w))).join(' '));
151
193
  for (const row of cells) {
152
194
  printLine(row.map((c, i) => pad(c, widths[i])).join(' '));
153
195
  }
package/package.json CHANGED
@@ -8,8 +8,7 @@
8
8
  "@clack/prompts": "^1.6.0",
9
9
  "@modelcontextprotocol/sdk": "^1.31.0",
10
10
  "@supabase/supabase-js": "^2.108.2",
11
- "bplist-parser": "^0.5.0",
12
- "chalk": "^6.0.0",
11
+ "bplist-parser": "^0.6.0",
13
12
  "citty": "^0.2.2",
14
13
  "js-yaml": "^5.2.2",
15
14
  "node-stream-zip": "^1.15.0",
@@ -29,7 +28,6 @@
29
28
  "chai": "^6.2.2",
30
29
  "eslint": "^10.15.0",
31
30
  "eslint-config-prettier": "^10.1.8",
32
- "eslint-plugin-unicorn": "^79.0.0",
33
31
  "husky": "^9.1.7",
34
32
  "mocha": "^12.0.0",
35
33
  "prettier": "^3.8.4",
@@ -38,7 +36,7 @@
38
36
  "typescript-eslint": "^8.73.0"
39
37
  },
40
38
  "engines": {
41
- "node": ">=22.0.0"
39
+ "node": ">=22.8.0"
42
40
  },
43
41
  "files": [
44
42
  "/dist"
@@ -66,7 +64,7 @@
66
64
  "test:unit": "node scripts/test-runner.mjs --unit",
67
65
  "typecheck": "tsc --noEmit -p tsconfig.test.json"
68
66
  },
69
- "version": "5.15.0",
67
+ "version": "5.16.0-beta.2",
70
68
  "bugs": {
71
69
  "url": "https://discord.gg/gm3mJwcNw8"
72
70
  },
@@ -79,18 +77,20 @@
79
77
  "testing"
80
78
  ],
81
79
  "types": "dist/index.d.ts",
80
+ "exports": {
81
+ ".": "./dist/index.js",
82
+ "./e2e": {
83
+ "types": "./dist/e2e/index.d.ts",
84
+ "default": "./dist/e2e/index.js"
85
+ },
86
+ "./package.json": "./package.json",
87
+ "./dist/*": "./dist/*"
88
+ },
82
89
  "packageManager": "pnpm@10.17.1",
83
90
  "pnpm": {
84
91
  "overrides": {
85
92
  "minimatch@>=10.0.0 <11.0.1": "11.0.1",
86
93
  "glob@>=9.0.0 <14.0.2": "14.0.2"
87
- },
88
- "auditConfig": {
89
- "ignoreGhsas": [
90
- "GHSA-frvp-7c67-39w9",
91
- "GHSA-vfj7-8cjw-p6xm",
92
- "GHSA-fc5q-39xc-vjpf"
93
- ]
94
94
  }
95
95
  }
96
96
  }