@devicecloud.dev/dcd 5.10.0 → 5.11.0-beta.10
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 +75 -3
- package/dist/commands/cloud.d.ts +1 -1
- package/dist/commands/cloud.js +7 -6
- package/dist/commands/device.d.ts +36 -0
- package/dist/commands/device.js +1151 -0
- package/dist/commands/live.d.ts +2 -0
- package/dist/commands/live.js +10 -1
- package/dist/commands/login.js +2 -17
- package/dist/commands/mcp.d.ts +13 -0
- package/dist/commands/mcp.js +180 -0
- package/dist/commands/upload.js +2 -8
- package/dist/config/flags/device.flags.d.ts +1 -1
- package/dist/config/flags/device.flags.js +1 -1
- package/dist/constants.d.ts +1 -1
- package/dist/gateways/device-gateway.d.ts +88 -0
- package/dist/gateways/device-gateway.js +140 -0
- package/dist/index.js +4 -0
- package/dist/mcp/bridge.d.ts +52 -0
- package/dist/mcp/bridge.js +288 -0
- package/dist/mcp/tools/run-cloud-test.d.ts +13 -0
- package/dist/mcp/tools/run-cloud-test.js +18 -8
- package/dist/methods.d.ts +24 -0
- package/dist/methods.js +147 -169
- package/dist/services/device-validation.service.js +1 -1
- package/dist/services/execution-plan.service.d.ts +27 -0
- package/dist/services/execution-plan.service.js +9 -1
- package/dist/services/metadata-extractor.service.d.ts +13 -0
- package/dist/services/metadata-extractor.service.js +35 -1
- package/dist/services/moropo.service.js +1 -1
- package/dist/services/results-polling.service.js +1 -1
- package/dist/types/domain/device-session.types.d.ts +211 -0
- package/dist/types/domain/device-session.types.js +5 -0
- package/dist/types/domain/device.types.d.ts +0 -2
- package/dist/types/domain/device.types.js +0 -2
- package/dist/types.d.ts +11 -0
- package/dist/utils/app-upload.d.ts +19 -0
- package/dist/utils/app-upload.js +63 -0
- package/dist/utils/auth.d.ts +0 -8
- package/dist/utils/auth.js +31 -27
- package/dist/utils/b2-retry.d.ts +49 -0
- package/dist/utils/b2-retry.js +77 -0
- package/dist/utils/browser.d.ts +16 -0
- package/dist/utils/browser.js +48 -0
- package/dist/utils/compatibility.d.ts +5 -7
- package/dist/utils/compatibility.js +5 -13
- package/dist/utils/device-artifacts.d.ts +55 -0
- package/dist/utils/device-artifacts.js +211 -0
- package/dist/utils/device-bundle.d.ts +35 -0
- package/dist/utils/device-bundle.js +162 -0
- package/dist/utils/device-matrix.js +1 -1
- package/dist/utils/device-output.d.ts +81 -0
- package/dist/utils/device-output.js +204 -0
- package/dist/utils/device-run.d.ts +29 -0
- package/dist/utils/device-run.js +113 -0
- package/dist/utils/mcp-install.d.ts +50 -0
- package/dist/utils/mcp-install.js +132 -0
- package/dist/utils/progress.d.ts +4 -0
- package/dist/utils/progress.js +45 -21
- package/package.json +2 -2
|
@@ -1,25 +1,17 @@
|
|
|
1
1
|
let cachedCompatibilityData = null;
|
|
2
|
-
|
|
2
|
+
/**
|
|
3
|
+
* The CLI / CI identity the API version-filters and targets notices by rides
|
|
4
|
+
* on `auth.headers`, like on every other request (see resolveAuth).
|
|
5
|
+
*/
|
|
6
|
+
export async function fetchCompatibilityData(apiUrl, auth) {
|
|
3
7
|
if (cachedCompatibilityData) {
|
|
4
8
|
return cachedCompatibilityData;
|
|
5
9
|
}
|
|
6
|
-
// Forward CLI / CI identity so the API can version-filter and target notices.
|
|
7
|
-
const noticeHeaders = {};
|
|
8
|
-
if (clientContext?.cliVersion) {
|
|
9
|
-
noticeHeaders['x-dcd-cli-version'] = clientContext.cliVersion;
|
|
10
|
-
}
|
|
11
|
-
if (clientContext?.ciProvider) {
|
|
12
|
-
noticeHeaders['x-dcd-ci-provider'] = clientContext.ciProvider;
|
|
13
|
-
}
|
|
14
|
-
if (clientContext?.ciWrapperVersion) {
|
|
15
|
-
noticeHeaders['x-dcd-ci-wrapper-version'] = clientContext.ciWrapperVersion;
|
|
16
|
-
}
|
|
17
10
|
try {
|
|
18
11
|
const response = await fetch(`${apiUrl}/results/compatibility/data`, {
|
|
19
12
|
headers: {
|
|
20
13
|
'Content-Type': 'application/json',
|
|
21
14
|
...auth.headers,
|
|
22
|
-
...noticeHeaders,
|
|
23
15
|
},
|
|
24
16
|
method: 'GET',
|
|
25
17
|
});
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { AuthContext } from '../types/domain/auth.types.js';
|
|
2
|
+
import { type DeviceArtifactsPage, type DeviceSession } from '../types/domain/device-session.types.js';
|
|
3
|
+
/** One file a session left behind, and where it goes on disk. */
|
|
4
|
+
export interface DeviceArtifactFile {
|
|
5
|
+
/** recording, logs, screenshot or hierarchy. */
|
|
6
|
+
kind: 'hierarchy' | 'logs' | 'recording' | 'screenshot';
|
|
7
|
+
/** Relative to the output directory. */
|
|
8
|
+
file: string;
|
|
9
|
+
url: null | string;
|
|
10
|
+
bytes: null | number;
|
|
11
|
+
/** The action a screenshot or screen dump was taken after. */
|
|
12
|
+
command_id?: null | string;
|
|
13
|
+
created_at: string;
|
|
14
|
+
}
|
|
15
|
+
/** Every page of a session's artifacts. */
|
|
16
|
+
export declare function fetchAllArtifacts(apiUrl: string, auth: AuthContext, id: string): Promise<{
|
|
17
|
+
pages: DeviceArtifactsPage[];
|
|
18
|
+
session: DeviceSession;
|
|
19
|
+
}>;
|
|
20
|
+
/**
|
|
21
|
+
* What a session's runner is still uploading: the video (`recording`) and
|
|
22
|
+
* the device log (`logs`) land up to a minute or so after the session ends.
|
|
23
|
+
* The API says so in `pending`. An API older than that field gets a guess:
|
|
24
|
+
* an ended session missing either file whose last activity (its newest
|
|
25
|
+
* action, else its start) was under three minutes ago. The session summary
|
|
26
|
+
* carries no end time, so the last activity stands in for it.
|
|
27
|
+
*/
|
|
28
|
+
export declare function pendingArtifacts(pages: DeviceArtifactsPage[], now?: number): ('logs' | 'recording')[];
|
|
29
|
+
/** The warning for {@link pendingArtifacts}, or null when nothing is pending. */
|
|
30
|
+
export declare function pendingArtifactsWarning(pending: ('logs' | 'recording')[]): null | string;
|
|
31
|
+
/**
|
|
32
|
+
* Lay the artifacts out as files: `recording.mp4`, `device.log`, and per
|
|
33
|
+
* action `actions/001-screenshot.jpg` and `actions/001-screen.json`,
|
|
34
|
+
* numbered oldest first so the folder reads in order.
|
|
35
|
+
*/
|
|
36
|
+
export declare function planArtifactFiles(pages: DeviceArtifactsPage[]): DeviceArtifactFile[];
|
|
37
|
+
/** Timeouts and retries for one artifact download. */
|
|
38
|
+
export interface DownloadArtifactOptions {
|
|
39
|
+
/** Give up on an attempt that receives no data for this long. */
|
|
40
|
+
idleTimeoutMs?: number;
|
|
41
|
+
/** Give up on an attempt that takes longer than this in total. */
|
|
42
|
+
totalTimeoutMs?: number;
|
|
43
|
+
/** How many times to try each file before reporting it failed. */
|
|
44
|
+
attempts?: number;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Download every file with a link into `dir`, four at a time. Each file is
|
|
48
|
+
* tried twice (a stalled CDN response usually succeeds on a second
|
|
49
|
+
* request). Returns the files that could not be fetched, with why, rather
|
|
50
|
+
* than failing the rest.
|
|
51
|
+
*/
|
|
52
|
+
export declare function downloadArtifactFiles(dir: string, files: DeviceArtifactFile[], onFile?: (file: DeviceArtifactFile) => void, options?: DownloadArtifactOptions): Promise<{
|
|
53
|
+
file: string;
|
|
54
|
+
reason: string;
|
|
55
|
+
}[]>;
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import { createWriteStream } from 'node:fs';
|
|
2
|
+
import { mkdir, rm } from 'node:fs/promises';
|
|
3
|
+
import * as path from 'node:path';
|
|
4
|
+
import { Readable } from 'node:stream';
|
|
5
|
+
import { pipeline } from 'node:stream/promises';
|
|
6
|
+
import { DeviceGateway } from '../gateways/device-gateway.js';
|
|
7
|
+
import { ENDED_STATES, } from '../types/domain/device-session.types.js';
|
|
8
|
+
const EXTENSIONS = {
|
|
9
|
+
'application/json': 'json',
|
|
10
|
+
'image/jpeg': 'jpg',
|
|
11
|
+
'image/png': 'png',
|
|
12
|
+
'text/plain': 'log',
|
|
13
|
+
'video/mp4': 'mp4',
|
|
14
|
+
};
|
|
15
|
+
function extensionFor(link, fallback) {
|
|
16
|
+
return EXTENSIONS[link.content_type.split(';')[0].trim()] ?? fallback;
|
|
17
|
+
}
|
|
18
|
+
/** Every page of a session's artifacts. */
|
|
19
|
+
export async function fetchAllArtifacts(apiUrl, auth, id) {
|
|
20
|
+
const pages = [];
|
|
21
|
+
let before;
|
|
22
|
+
do {
|
|
23
|
+
const page = await DeviceGateway.artifacts(apiUrl, auth, id, before);
|
|
24
|
+
pages.push(page);
|
|
25
|
+
before = page.next_before ?? undefined;
|
|
26
|
+
} while (before);
|
|
27
|
+
return { pages, session: pages.at(-1).session };
|
|
28
|
+
}
|
|
29
|
+
/** How long after a session ends its video and log may still be uploading. */
|
|
30
|
+
const PENDING_WINDOW_MS = 3 * 60 * 1000;
|
|
31
|
+
/**
|
|
32
|
+
* What a session's runner is still uploading: the video (`recording`) and
|
|
33
|
+
* the device log (`logs`) land up to a minute or so after the session ends.
|
|
34
|
+
* The API says so in `pending`. An API older than that field gets a guess:
|
|
35
|
+
* an ended session missing either file whose last activity (its newest
|
|
36
|
+
* action, else its start) was under three minutes ago. The session summary
|
|
37
|
+
* carries no end time, so the last activity stands in for it.
|
|
38
|
+
*/
|
|
39
|
+
export function pendingArtifacts(pages, now = Date.now()) {
|
|
40
|
+
const first = pages[0];
|
|
41
|
+
if (!first)
|
|
42
|
+
return [];
|
|
43
|
+
if (Array.isArray(first.pending))
|
|
44
|
+
return first.pending;
|
|
45
|
+
if (!ENDED_STATES.includes(first.session.state))
|
|
46
|
+
return [];
|
|
47
|
+
const lastActivity = Date.parse(first.actions[0]?.created_at ?? first.session.created_at);
|
|
48
|
+
if (!Number.isFinite(lastActivity) || now - lastActivity > PENDING_WINDOW_MS)
|
|
49
|
+
return [];
|
|
50
|
+
const pending = [];
|
|
51
|
+
if (!first.recording)
|
|
52
|
+
pending.push('recording');
|
|
53
|
+
if (!first.logs)
|
|
54
|
+
pending.push('logs');
|
|
55
|
+
return pending;
|
|
56
|
+
}
|
|
57
|
+
/** The warning for {@link pendingArtifacts}, or null when nothing is pending. */
|
|
58
|
+
export function pendingArtifactsWarning(pending) {
|
|
59
|
+
if (pending.length === 0)
|
|
60
|
+
return null;
|
|
61
|
+
const what = pending.length === 2
|
|
62
|
+
? 'The video and device log are'
|
|
63
|
+
: pending[0] === 'recording'
|
|
64
|
+
? 'The video is'
|
|
65
|
+
: 'The device log is';
|
|
66
|
+
return `${what} still uploading. Run this again in a minute.`;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Lay the artifacts out as files: `recording.mp4`, `device.log`, and per
|
|
70
|
+
* action `actions/001-screenshot.jpg` and `actions/001-screen.json`,
|
|
71
|
+
* numbered oldest first so the folder reads in order.
|
|
72
|
+
*/
|
|
73
|
+
export function planArtifactFiles(pages) {
|
|
74
|
+
const files = [];
|
|
75
|
+
const first = pages[0];
|
|
76
|
+
if (first?.recording) {
|
|
77
|
+
files.push({
|
|
78
|
+
kind: 'recording',
|
|
79
|
+
file: `recording.${extensionFor(first.recording, 'mp4')}`,
|
|
80
|
+
url: first.recording.url,
|
|
81
|
+
bytes: first.recording.bytes,
|
|
82
|
+
created_at: first.recording.created_at,
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
if (first?.logs) {
|
|
86
|
+
files.push({
|
|
87
|
+
kind: 'logs',
|
|
88
|
+
file: `device.${extensionFor(first.logs, 'log')}`,
|
|
89
|
+
url: first.logs.url,
|
|
90
|
+
bytes: first.logs.bytes,
|
|
91
|
+
created_at: first.logs.created_at,
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
const actions = pages.flatMap((p) => p.actions).reverse();
|
|
95
|
+
const width = Math.max(3, String(actions.length).length);
|
|
96
|
+
for (const [i, action] of actions.entries()) {
|
|
97
|
+
const n = String(i + 1).padStart(width, '0');
|
|
98
|
+
if (action.screenshot) {
|
|
99
|
+
files.push({
|
|
100
|
+
kind: 'screenshot',
|
|
101
|
+
file: path.join('actions', `${n}-screenshot.${extensionFor(action.screenshot, 'jpg')}`),
|
|
102
|
+
url: action.screenshot.url,
|
|
103
|
+
bytes: action.screenshot.bytes,
|
|
104
|
+
command_id: action.command_id,
|
|
105
|
+
created_at: action.created_at,
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
if (action.hierarchy) {
|
|
109
|
+
files.push({
|
|
110
|
+
kind: 'hierarchy',
|
|
111
|
+
file: path.join('actions', `${n}-screen.${extensionFor(action.hierarchy, 'json')}`),
|
|
112
|
+
url: action.hierarchy.url,
|
|
113
|
+
bytes: action.hierarchy.bytes,
|
|
114
|
+
command_id: action.command_id,
|
|
115
|
+
created_at: action.created_at,
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return files;
|
|
120
|
+
}
|
|
121
|
+
const CONCURRENCY = 4;
|
|
122
|
+
const DEFAULT_IDLE_TIMEOUT_MS = 30_000;
|
|
123
|
+
const DEFAULT_TOTAL_TIMEOUT_MS = 10 * 60_000;
|
|
124
|
+
const DEFAULT_ATTEMPTS = 2;
|
|
125
|
+
function seconds(ms) {
|
|
126
|
+
return ms >= 1000 ? `${Math.round(ms / 1000)}s` : `${ms}ms`;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Fetch one URL to `target`. Aborts when no data arrives for `idleMs`
|
|
130
|
+
* (including while waiting for the response headers) or when the whole
|
|
131
|
+
* download takes longer than `totalMs`. A CDN stream can stall without
|
|
132
|
+
* closing, and without these the command would wait for it forever.
|
|
133
|
+
*/
|
|
134
|
+
async function downloadOnce(url, target, idleMs, totalMs) {
|
|
135
|
+
const controller = new AbortController();
|
|
136
|
+
const abort = (reason) => controller.abort(new Error(reason));
|
|
137
|
+
let idle = setTimeout(() => abort(`timed out: no data for ${seconds(idleMs)}`), idleMs);
|
|
138
|
+
const total = setTimeout(() => abort(`timed out: took longer than ${seconds(totalMs)}`), totalMs);
|
|
139
|
+
const resetIdle = () => {
|
|
140
|
+
clearTimeout(idle);
|
|
141
|
+
idle = setTimeout(() => abort(`timed out: no data for ${seconds(idleMs)}`), idleMs);
|
|
142
|
+
};
|
|
143
|
+
try {
|
|
144
|
+
const res = await fetch(url, { signal: controller.signal });
|
|
145
|
+
if (!res.ok || !res.body)
|
|
146
|
+
throw new Error(`HTTP ${res.status}`);
|
|
147
|
+
resetIdle();
|
|
148
|
+
const body = Readable.fromWeb(res.body);
|
|
149
|
+
await pipeline(body, async function* (source) {
|
|
150
|
+
for await (const chunk of source) {
|
|
151
|
+
resetIdle();
|
|
152
|
+
yield chunk;
|
|
153
|
+
}
|
|
154
|
+
}, createWriteStream(target), { signal: controller.signal });
|
|
155
|
+
}
|
|
156
|
+
catch (error) {
|
|
157
|
+
// Report the timeout, not the AbortError it surfaces as.
|
|
158
|
+
if (controller.signal.aborted && controller.signal.reason instanceof Error) {
|
|
159
|
+
throw controller.signal.reason;
|
|
160
|
+
}
|
|
161
|
+
throw error;
|
|
162
|
+
}
|
|
163
|
+
finally {
|
|
164
|
+
clearTimeout(idle);
|
|
165
|
+
clearTimeout(total);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Download every file with a link into `dir`, four at a time. Each file is
|
|
170
|
+
* tried twice (a stalled CDN response usually succeeds on a second
|
|
171
|
+
* request). Returns the files that could not be fetched, with why, rather
|
|
172
|
+
* than failing the rest.
|
|
173
|
+
*/
|
|
174
|
+
export async function downloadArtifactFiles(dir, files, onFile = () => { }, options = {}) {
|
|
175
|
+
const idleMs = options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
|
|
176
|
+
const totalMs = options.totalTimeoutMs ?? DEFAULT_TOTAL_TIMEOUT_MS;
|
|
177
|
+
const attempts = Math.max(1, options.attempts ?? DEFAULT_ATTEMPTS);
|
|
178
|
+
const failed = [];
|
|
179
|
+
const queue = [...files];
|
|
180
|
+
async function worker() {
|
|
181
|
+
for (let next = queue.shift(); next; next = queue.shift()) {
|
|
182
|
+
if (!next.url) {
|
|
183
|
+
failed.push({ file: next.file, reason: 'no download link (it may have been cleaned up)' });
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
const target = path.join(dir, next.file);
|
|
187
|
+
let reason = '';
|
|
188
|
+
for (let attempt = 1; attempt <= attempts; attempt++) {
|
|
189
|
+
try {
|
|
190
|
+
await mkdir(path.dirname(target), { recursive: true });
|
|
191
|
+
await downloadOnce(next.url, target, idleMs, totalMs);
|
|
192
|
+
reason = '';
|
|
193
|
+
break;
|
|
194
|
+
}
|
|
195
|
+
catch (error) {
|
|
196
|
+
reason = error instanceof Error ? error.message : String(error);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if (reason) {
|
|
200
|
+
// Don't leave a half-written file that looks like a real one.
|
|
201
|
+
await rm(target, { force: true }).catch(() => { });
|
|
202
|
+
failed.push({ file: next.file, reason: attempts > 1 ? `${reason} (after ${attempts} tries)` : reason });
|
|
203
|
+
}
|
|
204
|
+
else {
|
|
205
|
+
onFile(next);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
await Promise.all(Array.from({ length: CONCURRENCY }, () => worker()));
|
|
210
|
+
return failed;
|
|
211
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { AuthContext } from '../types/domain/auth.types.js';
|
|
2
|
+
import type { DeviceFlowBundle } from '../types/domain/device-session.types.js';
|
|
3
|
+
/** The API's limit on a bundle (dcd plan 2.5b). */
|
|
4
|
+
export declare const MAX_BUNDLE_BYTES: number;
|
|
5
|
+
/**
|
|
6
|
+
* The files under `dir` a bundle needs, relative to it, in a stable order:
|
|
7
|
+
* every YAML file (flows, subflows, config), the files the flows use
|
|
8
|
+
* (runScript, addMedia, assertScreenshot and the like), and config's
|
|
9
|
+
* includedPaths. Nothing else: an agent's samples folder sent 265 MB of .apk
|
|
10
|
+
* and .zip files with its flows.
|
|
11
|
+
*
|
|
12
|
+
* `entry` is the one flow that will run. Its files must all be inside `dir`.
|
|
13
|
+
* Without an entry every flow may run, so that goes for all of them. Another
|
|
14
|
+
* flow's missing file doesn't stop the entry running, so it is left out.
|
|
15
|
+
*/
|
|
16
|
+
export declare function bundleFiles(dir: string, entry?: string, warn?: (message: string) => void): string[];
|
|
17
|
+
export interface UploadFlowBundleOptions {
|
|
18
|
+
apiUrl: string;
|
|
19
|
+
auth: AuthContext;
|
|
20
|
+
dir: string;
|
|
21
|
+
/** The one flow that will run, a path inside `dir`. Omitted, all of them. */
|
|
22
|
+
entry?: string;
|
|
23
|
+
log: (message: string) => void;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Zip the files a directory's flows need (bundleFiles) and upload them as a
|
|
27
|
+
* flow bundle: ask the API for
|
|
28
|
+
* upload URLs, PUT the zip to both copies, then register it with its
|
|
29
|
+
* SHA-256. Encrypted like `dcd cloud`'s flow zips when the org's default
|
|
30
|
+
* (or DCD_ENCRYPT) says so. Entries are relative to `dir`, so a run's
|
|
31
|
+
* `flow` is a path inside it, e.g. `login.yaml`.
|
|
32
|
+
*/
|
|
33
|
+
export declare function uploadFlowBundle(opts: UploadFlowBundleOptions): Promise<DeviceFlowBundle & {
|
|
34
|
+
files: number;
|
|
35
|
+
}>;
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { existsSync, readdirSync } from 'node:fs';
|
|
3
|
+
import * as path from 'node:path';
|
|
4
|
+
import { DeviceGateway } from '../gateways/device-gateway.js';
|
|
5
|
+
import { compressFilesFromRelativePath } from '../methods.js';
|
|
6
|
+
import { resolveIncludedPaths } from '../services/execution-plan.service.js';
|
|
7
|
+
import { isWorkspaceConfigFile, loadWorkspaceConfig, processDependencies, readTestYamlFileAsJson, } from '../services/execution-plan.utils.js';
|
|
8
|
+
import { CliError } from './cli.js';
|
|
9
|
+
import { fetchCompatibilityData } from './compatibility.js';
|
|
10
|
+
import { checkKekForEncryption, encryptFlowBuffer, resolveEncryption, resolveKekPublicKey, } from './envelope.js';
|
|
11
|
+
/** The API's limit on a bundle (dcd plan 2.5b). */
|
|
12
|
+
export const MAX_BUNDLE_BYTES = 50 * 1024 * 1024;
|
|
13
|
+
/** Never bundled: version control, dependencies, and other dot-folders. */
|
|
14
|
+
function skipped(relativePath) {
|
|
15
|
+
return relativePath
|
|
16
|
+
.split(path.sep)
|
|
17
|
+
.some((part) => part === 'node_modules' || (part.startsWith('.') && part !== '.'));
|
|
18
|
+
}
|
|
19
|
+
const YAML_FILE = /\.ya?ml$/i;
|
|
20
|
+
/** Every file under `dir`, relative to it. */
|
|
21
|
+
function allFiles(dir) {
|
|
22
|
+
return readdirSync(dir, { recursive: true, withFileTypes: true })
|
|
23
|
+
.filter((entry) => entry.isFile())
|
|
24
|
+
.map((entry) => path.relative(dir, path.join(entry.parentPath, entry.name)))
|
|
25
|
+
.filter((file) => !skipped(file));
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The files under `dir` a bundle needs, relative to it, in a stable order:
|
|
29
|
+
* every YAML file (flows, subflows, config), the files the flows use
|
|
30
|
+
* (runScript, addMedia, assertScreenshot and the like), and config's
|
|
31
|
+
* includedPaths. Nothing else: an agent's samples folder sent 265 MB of .apk
|
|
32
|
+
* and .zip files with its flows.
|
|
33
|
+
*
|
|
34
|
+
* `entry` is the one flow that will run. Its files must all be inside `dir`.
|
|
35
|
+
* Without an entry every flow may run, so that goes for all of them. Another
|
|
36
|
+
* flow's missing file doesn't stop the entry running, so it is left out.
|
|
37
|
+
*/
|
|
38
|
+
export function bundleFiles(dir, entry, warn = () => { }) {
|
|
39
|
+
const root = path.resolve(dir);
|
|
40
|
+
const yamlFiles = allFiles(dir).filter((file) => YAML_FILE.test(file));
|
|
41
|
+
const entryFile = entry === undefined ? undefined : path.normalize(entry);
|
|
42
|
+
if (entryFile !== undefined && !yamlFiles.includes(entryFile)) {
|
|
43
|
+
throw new CliError(`No flow ${entry} in ${dir}.`);
|
|
44
|
+
}
|
|
45
|
+
const needed = new Set(yamlFiles);
|
|
46
|
+
const problems = [];
|
|
47
|
+
const add = (absolute, strict, from) => {
|
|
48
|
+
const relative = path.relative(root, absolute);
|
|
49
|
+
if (relative.startsWith('..') || path.isAbsolute(relative)) {
|
|
50
|
+
if (strict)
|
|
51
|
+
problems.push(`${from} uses ${absolute}, which is outside ${dir}. Pass a directory that holds both.`);
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
needed.add(relative);
|
|
55
|
+
};
|
|
56
|
+
for (const file of yamlFiles) {
|
|
57
|
+
const absolute = path.join(root, file);
|
|
58
|
+
const strict = entryFile === undefined || entryFile === file;
|
|
59
|
+
if (isWorkspaceConfigFile(absolute))
|
|
60
|
+
continue;
|
|
61
|
+
let deps;
|
|
62
|
+
try {
|
|
63
|
+
const { config, testSteps } = readTestYamlFileAsJson(absolute);
|
|
64
|
+
deps = processDependencies({ config, input: absolute, testSteps });
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
// Not a flow (a data file, say), or one Maestro will report itself.
|
|
68
|
+
if (entryFile === file)
|
|
69
|
+
throw new CliError(error.message);
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
if (strict)
|
|
73
|
+
problems.push(...deps.allErrors);
|
|
74
|
+
for (const dep of deps.allFiles) {
|
|
75
|
+
if (existsSync(dep))
|
|
76
|
+
add(dep, strict, file);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
for (const name of ['config.yaml', 'config.yml']) {
|
|
80
|
+
if (!yamlFiles.includes(name))
|
|
81
|
+
continue;
|
|
82
|
+
const config = loadWorkspaceConfig(path.join(root, name), warn);
|
|
83
|
+
for (const file of resolveIncludedPaths(config, root, warn))
|
|
84
|
+
add(file, true, name);
|
|
85
|
+
}
|
|
86
|
+
if (problems.length > 0)
|
|
87
|
+
throw new CliError(problems.join('\n'));
|
|
88
|
+
return [...needed].sort();
|
|
89
|
+
}
|
|
90
|
+
/** PUT the zip to one signed URL. The URL is the credential. */
|
|
91
|
+
async function put(url, body) {
|
|
92
|
+
for (let attempt = 1; attempt <= 2; attempt++) {
|
|
93
|
+
try {
|
|
94
|
+
const res = await fetch(url, {
|
|
95
|
+
method: 'PUT',
|
|
96
|
+
headers: { 'content-type': 'application/zip' },
|
|
97
|
+
body: new Uint8Array(body),
|
|
98
|
+
});
|
|
99
|
+
await res.body?.cancel();
|
|
100
|
+
if (res.ok)
|
|
101
|
+
return true;
|
|
102
|
+
if (res.status >= 400 && res.status < 500 && res.status !== 408 && res.status !== 429) {
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
// A network error: try once more.
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Zip the files a directory's flows need (bundleFiles) and upload them as a
|
|
114
|
+
* flow bundle: ask the API for
|
|
115
|
+
* upload URLs, PUT the zip to both copies, then register it with its
|
|
116
|
+
* SHA-256. Encrypted like `dcd cloud`'s flow zips when the org's default
|
|
117
|
+
* (or DCD_ENCRYPT) says so. Entries are relative to `dir`, so a run's
|
|
118
|
+
* `flow` is a path inside it, e.g. `login.yaml`.
|
|
119
|
+
*/
|
|
120
|
+
export async function uploadFlowBundle(opts) {
|
|
121
|
+
const { apiUrl, auth, dir, entry, log } = opts;
|
|
122
|
+
const files = bundleFiles(dir, entry, log);
|
|
123
|
+
if (!files.some((f) => YAML_FILE.test(f))) {
|
|
124
|
+
throw new CliError(`No flow files (.yaml) in ${dir}.`);
|
|
125
|
+
}
|
|
126
|
+
const zip = await compressFilesFromRelativePath(dir, files, '');
|
|
127
|
+
let serverDefault;
|
|
128
|
+
try {
|
|
129
|
+
const compatibility = await fetchCompatibilityData(apiUrl, auth);
|
|
130
|
+
serverDefault = compatibility.encryption?.defaultOn;
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
serverDefault = undefined;
|
|
134
|
+
}
|
|
135
|
+
const encryption = await checkKekForEncryption(resolveEncryption({ serverDefault }), apiUrl);
|
|
136
|
+
if (encryption.notice)
|
|
137
|
+
log(encryption.notice);
|
|
138
|
+
const kek = encryption.enabled ? await resolveKekPublicKey(apiUrl) : null;
|
|
139
|
+
const sealed = kek ? encryptFlowBuffer(zip, kek) : null;
|
|
140
|
+
const body = sealed ? sealed.ciphertext : zip;
|
|
141
|
+
if (body.length > MAX_BUNDLE_BYTES) {
|
|
142
|
+
throw new CliError(`${dir} zips to ${(body.length / 1024 / 1024).toFixed(1)} MB; a bundle can be at most ${MAX_BUNDLE_BYTES / 1024 / 1024} MB.`);
|
|
143
|
+
}
|
|
144
|
+
const sha = createHash('sha256').update(body).digest('hex');
|
|
145
|
+
const urls = await DeviceGateway.bundleUploadUrls(apiUrl, auth, body.length);
|
|
146
|
+
const [supabase, backblaze] = await Promise.all([
|
|
147
|
+
urls.upload ? put(urls.upload.signedUrl, body) : Promise.resolve(false),
|
|
148
|
+
urls.mirror ? put(urls.mirror.signedUrl, body) : Promise.resolve(false),
|
|
149
|
+
]);
|
|
150
|
+
if (!supabase && !backblaze) {
|
|
151
|
+
throw new Error('The flow bundle could not be uploaded. Please retry.');
|
|
152
|
+
}
|
|
153
|
+
const { bundle } = await DeviceGateway.registerBundle(apiUrl, auth, {
|
|
154
|
+
id: urls.id,
|
|
155
|
+
sha,
|
|
156
|
+
bytes: body.length,
|
|
157
|
+
supabase,
|
|
158
|
+
backblaze,
|
|
159
|
+
...(sealed && { enc: sealed.enc }),
|
|
160
|
+
});
|
|
161
|
+
return { ...bundle, files: files.length };
|
|
162
|
+
}
|
|
@@ -54,7 +54,7 @@ export function parseDeviceMatrix(iosConfigs, androidConfigs) {
|
|
|
54
54
|
!parts[0] ||
|
|
55
55
|
!parts[1] ||
|
|
56
56
|
(parts.length === 3 && parts[2] !== 'play')) {
|
|
57
|
-
throw new CliError(`Invalid --android-device-matrix "${raw}". Expected <device>:<apiLevel> or <device>:<apiLevel>:play, e.g. pixel-
|
|
57
|
+
throw new CliError(`Invalid --android-device-matrix "${raw}". Expected <device>:<apiLevel> or <device>:<apiLevel>:play, e.g. pixel-8:34 or pixel-8:34:play.`);
|
|
58
58
|
}
|
|
59
59
|
configs.push({
|
|
60
60
|
androidDevice: parts[0],
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import type { AuthContext } from '../types/domain/auth.types.js';
|
|
2
|
+
import type { DeviceHumanStatus, DeviceSession } from '../types/domain/device-session.types.js';
|
|
3
|
+
import { type Field } from './ui.js';
|
|
4
|
+
/**
|
|
5
|
+
* Exit codes for `dcd device` (dcd docs/device-v1-plan.md, section 4.2).
|
|
6
|
+
* Scripts and agents branch on these, so they are a contract.
|
|
7
|
+
*/
|
|
8
|
+
export declare const DEVICE_EXIT: {
|
|
9
|
+
readonly ok: 0;
|
|
10
|
+
/** Called wrongly: a bad flag, a bad value, or no session to pick. */
|
|
11
|
+
readonly usage: 1;
|
|
12
|
+
/** It ran and failed: a flow or action failed, or the API could not do it. */
|
|
13
|
+
readonly failed: 2;
|
|
14
|
+
/** A limit: concurrency, spend cap or rate limit. */
|
|
15
|
+
readonly limit: 3;
|
|
16
|
+
/** The session has ended, or there is no such session. */
|
|
17
|
+
readonly gone: 4;
|
|
18
|
+
};
|
|
19
|
+
export declare function deviceExitCode(error: unknown): number;
|
|
20
|
+
/**
|
|
21
|
+
* The one object `--json` prints, on success and on failure alike. `session`
|
|
22
|
+
* is left out by the commands that are not about one session (`list`,
|
|
23
|
+
* `models`, `stop --all`), so it never reads as "no session".
|
|
24
|
+
*/
|
|
25
|
+
export interface DeviceEnvelope<T> {
|
|
26
|
+
ok: boolean;
|
|
27
|
+
session?: DeviceSession | null;
|
|
28
|
+
data: T | null;
|
|
29
|
+
error: {
|
|
30
|
+
code: null | string;
|
|
31
|
+
message: string;
|
|
32
|
+
} | null;
|
|
33
|
+
}
|
|
34
|
+
export interface DeviceOutcome<T> {
|
|
35
|
+
/** The session the command was about; undefined when it is not about one. */
|
|
36
|
+
session: DeviceSession | null | undefined;
|
|
37
|
+
data: T;
|
|
38
|
+
/** Prints the result for a person. Not called under --json. */
|
|
39
|
+
print(): void;
|
|
40
|
+
/**
|
|
41
|
+
* Set when the command ran but did not succeed (a failed launch, a failed
|
|
42
|
+
* flow). The CLI then exits 2, still printing `data`.
|
|
43
|
+
*/
|
|
44
|
+
failure?: {
|
|
45
|
+
code: null | string;
|
|
46
|
+
message: string;
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Runs one `dcd device` command and prints its result: one envelope under
|
|
51
|
+
* --json, readable text otherwise. Errors leave with the matching exit code.
|
|
52
|
+
* Under --json the error is printed here, as an envelope, so the top-level
|
|
53
|
+
* handler's `{ status, error }` never appears.
|
|
54
|
+
*/
|
|
55
|
+
export declare function runDeviceCommand<T>(json: boolean, fn: () => Promise<DeviceOutcome<T>>): Promise<void>;
|
|
56
|
+
/**
|
|
57
|
+
* Progress for a person, on stderr, so stdout carries only the result. Off
|
|
58
|
+
* under --json. These are plain lines, never a spinner, so they read the same
|
|
59
|
+
* in a terminal, a CI log or an agent's tool output.
|
|
60
|
+
*/
|
|
61
|
+
export declare function deviceProgress(json: boolean): (message: string) => void;
|
|
62
|
+
/**
|
|
63
|
+
* The default-session rule: `<id>` may be left out when the org has exactly
|
|
64
|
+
* one open session. With none, or several, the command is a usage error and
|
|
65
|
+
* lists what there is to choose from.
|
|
66
|
+
*/
|
|
67
|
+
export declare function resolveSessionId(apiUrl: string, auth: AuthContext, given: string | undefined): Promise<string>;
|
|
68
|
+
export declare function formatSeconds(seconds: number): string;
|
|
69
|
+
/** The rows that describe a session, for {@link ui.fields}. */
|
|
70
|
+
export declare function sessionFields(session: DeviceSession): Field[];
|
|
71
|
+
/** A session as a branch group, with its warnings after it. */
|
|
72
|
+
export declare function printSession(session: DeviceSession): void;
|
|
73
|
+
/**
|
|
74
|
+
* An API timestamp for a person: how far off it is and the local time, e.g.
|
|
75
|
+
* "in 12m (14:32)" or "3m ago (14:17)". The text as given when unreadable.
|
|
76
|
+
*/
|
|
77
|
+
export declare function formatWhen(iso: string, now?: number): string;
|
|
78
|
+
/** Where the hand-over stands, in a few words. */
|
|
79
|
+
export declare function humanState(human: DeviceHumanStatus): string;
|
|
80
|
+
/** The rows that describe a request for a person, for {@link ui.fields}. */
|
|
81
|
+
export declare function humanFields(human: DeviceHumanStatus, now?: number): Field[];
|