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

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
@@ -144,6 +144,27 @@ 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
 
@@ -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
+ }
package/package.json CHANGED
@@ -66,7 +66,7 @@
66
66
  "test:unit": "node scripts/test-runner.mjs --unit",
67
67
  "typecheck": "tsc --noEmit -p tsconfig.test.json"
68
68
  },
69
- "version": "5.15.0",
69
+ "version": "5.16.0-beta.1",
70
70
  "bugs": {
71
71
  "url": "https://discord.gg/gm3mJwcNw8"
72
72
  },
@@ -79,6 +79,15 @@
79
79
  "testing"
80
80
  ],
81
81
  "types": "dist/index.d.ts",
82
+ "exports": {
83
+ ".": "./dist/index.js",
84
+ "./e2e": {
85
+ "types": "./dist/e2e/index.d.ts",
86
+ "default": "./dist/e2e/index.js"
87
+ },
88
+ "./package.json": "./package.json",
89
+ "./dist/*": "./dist/*"
90
+ },
82
91
  "packageManager": "pnpm@10.17.1",
83
92
  "pnpm": {
84
93
  "overrides": {