@ohos-perf/cli 0.2.0 → 0.12.0

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.
Files changed (2) hide show
  1. package/dist/index.js +1014 -89
  2. package/package.json +49 -49
package/dist/index.js CHANGED
@@ -1,6 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ // src/commands.ts
4
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "fs";
5
+ import { join } from "path";
6
+ import {
7
+ discoverCases,
8
+ loadCases,
9
+ OhosPerfError as OhosPerfError2,
10
+ parseScenario
11
+ } from "@ohos-perf/core";
12
+
3
13
  // src/doctor.ts
14
+ import { OhosPerfError } from "@ohos-perf/core";
4
15
  function byId(a, b) {
5
16
  if (a.id < b.id) return -1;
6
17
  if (a.id > b.id) return 1;
@@ -14,10 +25,16 @@ function safeMessage(err) {
14
25
  return "<unprintable error>";
15
26
  }
16
27
  }
28
+ function failureLine(err) {
29
+ if (err instanceof OhosPerfError && err.code !== void 0) {
30
+ return `${err.code}: ${safeMessage(err)}`;
31
+ }
32
+ return safeMessage(err);
33
+ }
17
34
  function message(err) {
18
35
  return safeMessage(err);
19
36
  }
20
- async function doctorReport(deps2) {
37
+ async function doctorReport(deps2, target) {
21
38
  const hdc = { ok: false };
22
39
  try {
23
40
  hdc.path = await deps2.resolveHdc();
@@ -38,7 +55,7 @@ async function doctorReport(deps2) {
38
55
  let capabilities = [];
39
56
  let probeError;
40
57
  try {
41
- const connected = await deps2.connectDevice();
58
+ const connected = await deps2.connectDevice(target);
42
59
  const matrix = await connected.capabilities();
43
60
  device = { id: connected.id, kind: connected.kind, abi: connected.abi };
44
61
  capabilities = [...matrix.all()].sort(byId);
@@ -74,7 +91,7 @@ function json(value) {
74
91
  return JSON.stringify(value, null, 2) + "\n";
75
92
  }
76
93
  async function runDoctor(deps2, opts) {
77
- const report = await doctorReport(deps2.doctor);
94
+ const report = await doctorReport(deps2.doctor, opts.target);
78
95
  const exitCode = report.hdc.ok ? 0 : 1;
79
96
  if (opts.json) return { stdout: json(report), stderr: "", exitCode };
80
97
  let stdout = "";
@@ -109,7 +126,7 @@ async function runDoctor(deps2, opts) {
109
126
  return { stdout, stderr: "", exitCode };
110
127
  }
111
128
  async function runCaps(deps2, opts) {
112
- const report = await deps2.capsReport();
129
+ const report = await deps2.capsReport(opts.target);
113
130
  if (!report.hdcOk) {
114
131
  return { stdout: "", stderr: `hdc unavailable: ${report.hdcError}
115
132
  `, exitCode: 1 };
@@ -136,7 +153,7 @@ async function runAnalyze(deps2, sceneDir, opts) {
136
153
  `;
137
154
  return { stdout: metrics + summary, stderr: "", exitCode: 0 };
138
155
  } catch (err) {
139
- return { stdout: "", stderr: `${safeMessage(err)}
156
+ return { stdout: "", stderr: `${failureLine(err)}
140
157
  `, exitCode: 1 };
141
158
  }
142
159
  }
@@ -153,13 +170,43 @@ async function runCollect(deps2, req, opts) {
153
170
  const samples = [
154
171
  ...result.hiperf === void 0 ? [] : [`hiperf ${result.hiperf.samples}`],
155
172
  ...result.hidumper === void 0 ? [] : [`hidumper ${result.hidumper.frames}`],
156
- ...result.ui === void 0 ? [] : [`ui ${result.ui.nodes}`]
173
+ ...result.ui === void 0 ? [] : [`ui ${result.ui.nodes}`],
174
+ ...result.screenshot === void 0 ? [] : [`screenshot ${result.screenshot.width}x${result.screenshot.height}`]
157
175
  ];
158
176
  if (samples.length > 0) stdout += `samples ${samples.join(", ")}
177
+ `;
178
+ if (result.soDir !== void 0) stdout += `symbols ${result.soDir}
159
179
  `;
160
180
  return { stdout, stderr: "", exitCode: 0 };
161
181
  } catch (err) {
162
- return { stdout: "", stderr: `${safeMessage(err)}
182
+ return { stdout: "", stderr: `${failureLine(err)}
183
+ `, exitCode: 1 };
184
+ }
185
+ }
186
+ function gestureSummary(gesture) {
187
+ switch (gesture.action) {
188
+ case "click":
189
+ return `click ${gesture.x} ${gesture.y}`;
190
+ case "swipe": {
191
+ const velocity = gesture.velocity === void 0 ? "" : ` (velocity ${gesture.velocity})`;
192
+ return `swipe ${gesture.fromX},${gesture.fromY} -> ${gesture.toX},${gesture.toY}${velocity}`;
193
+ }
194
+ case "key":
195
+ return `key ${gesture.key}`;
196
+ case "inputText":
197
+ return `input ${gesture.x} ${gesture.y} ${JSON.stringify(gesture.text)}`;
198
+ case "text":
199
+ return `text ${JSON.stringify(gesture.text)}`;
200
+ }
201
+ }
202
+ async function runGesture(deps2, req, opts) {
203
+ try {
204
+ const result = await deps2.gesture(req);
205
+ if (opts.json) return { stdout: json(result), stderr: "", exitCode: 0 };
206
+ return { stdout: `${gestureSummary(req.gesture)} accepted
207
+ `, stderr: "", exitCode: 0 };
208
+ } catch (err) {
209
+ return { stdout: "", stderr: `${failureLine(err)}
163
210
  `, exitCode: 1 };
164
211
  }
165
212
  }
@@ -172,7 +219,7 @@ async function runQuery(deps2, req, opts) {
172
219
  const rows = result.rows.map((row) => JSON.stringify(row) + "\n").join("");
173
220
  return { stdout: summary + rows, stderr: "", exitCode: 0 };
174
221
  } catch (err) {
175
- return { stdout: "", stderr: `${safeMessage(err)}
222
+ return { stdout: "", stderr: `${failureLine(err)}
176
223
  `, exitCode: 1 };
177
224
  }
178
225
  }
@@ -201,10 +248,273 @@ async function runCompare(deps2, req, opts) {
201
248
  return { stdout: rows.join("") + `totals ${totals}
202
249
  `, stderr: "", exitCode: 0 };
203
250
  } catch (err) {
204
- return { stdout: "", stderr: `${safeMessage(err)}
251
+ return { stdout: "", stderr: `${failureLine(err)}
252
+ `, exitCode: 1 };
253
+ }
254
+ }
255
+ async function runUiCompare(deps2, req, opts) {
256
+ try {
257
+ const result = await deps2.uiCompare(req);
258
+ if (opts.json) return { stdout: json(result), stderr: "", exitCode: 0 };
259
+ const lines = [];
260
+ if (result.tree === null) {
261
+ lines.push("tree not compared (no ui.json on either side)\n");
262
+ } else {
263
+ lines.push(
264
+ `tree ${result.tree.added} added, ${result.tree.removed} removed, ${result.tree.changed} changed, ${result.tree.unchanged} unchanged
265
+ `
266
+ );
267
+ }
268
+ if (result.image === null) {
269
+ lines.push("image not compared (no screenshot.png on either side)\n");
270
+ } else {
271
+ lines.push(
272
+ `image similarity ${result.image.similarity} (hamming ${result.image.hamming}/64), changed ${result.image.changedRatio} at tolerance ${result.image.tolerance}
273
+ `
274
+ );
275
+ }
276
+ lines.push(`regions ${result.regions}
277
+ `);
278
+ for (const line of result.degraded) lines.push(`degraded ${line}
279
+ `);
280
+ lines.push(`wrote ${result.files.join(", ")} in ${result.outDir}
281
+ `);
282
+ return { stdout: lines.join(""), stderr: "", exitCode: 0 };
283
+ } catch (err) {
284
+ return { stdout: "", stderr: `${failureLine(err)}
285
+ `, exitCode: 1 };
286
+ }
287
+ }
288
+ async function runReport(deps2, req, opts) {
289
+ try {
290
+ const result = await deps2.report(req);
291
+ if (opts.json) return { stdout: json(result), stderr: "", exitCode: 0 };
292
+ const sections = result.sections.degraded === 0 ? `sections ${result.sections.total} measured
293
+ ` : `sections ${result.sections.measured} measured, ${result.sections.degraded} degraded
294
+ `;
295
+ const comparison = result.comparison === void 0 ? "" : `comparison ${DELTA_ORDER.map(
296
+ (status) => `${status} ${result.comparison[status]}`
297
+ ).join(", ")}
298
+ `;
299
+ return {
300
+ stdout: `report ${result.outDir}/report.html
301
+ artifacts ${result.files.join(" ")}
302
+ ` + sections + `totals ${result.metrics} metrics, ${result.evidence} evidence (info ${result.bySeverity.info}, warn ${result.bySeverity.warn}, critical ${result.bySeverity.critical})
303
+ ` + comparison,
304
+ stderr: "",
305
+ exitCode: 0
306
+ };
307
+ } catch (err) {
308
+ return { stdout: "", stderr: `${failureLine(err)}
309
+ `, exitCode: 1 };
310
+ }
311
+ }
312
+ async function runHap(deps2, req, opts) {
313
+ const pathError = packagePathError(req.packagePath);
314
+ if (pathError !== void 0) return { stdout: "", stderr: `${pathError}
315
+ `, exitCode: 1 };
316
+ try {
317
+ const result = await deps2.hap(req);
318
+ if (opts.json) {
319
+ return {
320
+ stdout: json({ analysis: result.analysis, capabilities: result.capabilities }),
321
+ stderr: "",
322
+ exitCode: 0
323
+ };
324
+ }
325
+ const analysis = result.analysis;
326
+ const app = analysis.package;
327
+ const identity = [app.bundleName === "" ? "" : app.bundleName, app.versionName].filter((part) => part !== "").join(" ");
328
+ const version = app.versionCode === 0 ? "" : ` (${app.versionCode})`;
329
+ const label = app.appName === "" ? "" : ` ${app.appName}`;
330
+ let stdout = `package ${app.name}${identity === "" ? "" : ` ${identity}${version}`}${label}
331
+ `;
332
+ stdout += `files ${analysis.totals.files}, ${analysis.totals.size} bytes (${analysis.totals.compressedSize} compressed)
333
+ `;
334
+ stdout += analysis.technologies.length === 0 ? "tech none detected\n" : analysis.technologies.map(
335
+ (entry) => `tech ${entry.type} (rule ${entry.ruleId}) ${entry.files.length} file(s), ${entry.bytes} bytes
336
+ `
337
+ ).join("");
338
+ const wasted = analysis.duplicates.reduce((sum, group) => sum + group.wastedBytes, 0);
339
+ stdout += `duplicates ${analysis.duplicates.length} group(s), ${wasted} bytes wasted
340
+ `;
341
+ stdout += `oversized ${analysis.oversized.length} file(s)
342
+ `;
343
+ if (analysis.largest.length > 0) {
344
+ stdout += `largest ${analysis.largest.map((file) => `${file.path} ${file.size} bytes`).join("\n ")}
345
+ `;
346
+ }
347
+ if (result.outDir !== void 0 && result.artifacts !== void 0) {
348
+ stdout += `wrote ${result.artifacts.join(", ")} in ${result.outDir}
349
+ `;
350
+ }
351
+ return { stdout, stderr: "", exitCode: 0 };
352
+ } catch (err) {
353
+ return { stdout: "", stderr: `${failureLine(err)}
354
+ `, exitCode: 1 };
355
+ }
356
+ }
357
+ function packagePathError(packagePath) {
358
+ let stats;
359
+ try {
360
+ stats = statSync(packagePath);
361
+ } catch {
362
+ return `no such package: ${packagePath}`;
363
+ }
364
+ if (!stats.isFile()) return `not a file: ${packagePath}`;
365
+ const dot = packagePath.lastIndexOf(".");
366
+ const extension = dot <= 0 ? "" : packagePath.slice(dot + 1).toLowerCase();
367
+ if (extension !== "hap" && extension !== "hsp" && extension !== "zip") {
368
+ return `not a package (expected .hap, .hsp or .zip): ${packagePath}`;
369
+ }
370
+ return void 0;
371
+ }
372
+ async function runScenarioCommand(deps2, input, opts) {
373
+ if (input.casesDir !== void 0) {
374
+ if (input.scenarioPath !== "") {
375
+ return {
376
+ stdout: "",
377
+ stderr: "run: give either a scenario file or --cases <dir>, not both\n",
378
+ exitCode: 1
379
+ };
380
+ }
381
+ return runCases(deps2, input, opts);
382
+ }
383
+ let scenario;
384
+ try {
385
+ let text;
386
+ try {
387
+ text = readFileSync(input.scenarioPath, "utf8");
388
+ } catch (err) {
389
+ throw new OhosPerfError2(
390
+ `cannot read scenario ${input.scenarioPath}: ${safeMessage(err)}`,
391
+ { code: "SCENARIO_UNREADABLE", cause: err }
392
+ );
393
+ }
394
+ scenario = parseScenario(text);
395
+ } catch (err) {
396
+ return { stdout: "", stderr: `${failureLine(err)}
397
+ `, exitCode: 1 };
398
+ }
399
+ try {
400
+ const result = await deps2.run({
401
+ scenario,
402
+ scenarioPath: input.scenarioPath,
403
+ outDir: input.outDir,
404
+ ...input.target === void 0 ? {} : { target: input.target },
405
+ ...input.rounds === void 0 ? {} : { rounds: input.rounds },
406
+ ...input.only === void 0 ? {} : { only: input.only },
407
+ ...input.keepGoing === true ? { keepGoing: true } : {}
408
+ });
409
+ if (opts.json) {
410
+ return {
411
+ stdout: json(result),
412
+ stderr: "",
413
+ exitCode: result.status === "failed" ? 1 : 0
414
+ };
415
+ }
416
+ const ok = result.steps.filter((step) => step.status === "ok").length;
417
+ const failed = result.steps.length - ok;
418
+ const lines = result.steps.map((step) => {
419
+ const scene = step.sceneDir === void 0 ? "" : ` ${step.sceneDir}`;
420
+ const error = step.status === "ok" ? "" : ` ${step.error ?? "failed"}`;
421
+ return `${step.status === "ok" ? "ok " : "failed"} ${step.id} round ${step.round}${scene}${error}`;
422
+ });
423
+ const summary = failed === 0 ? `steps ${ok}/${result.steps.length} ok` : `steps ${ok}/${result.steps.length} ok, ${failed} failed`;
424
+ return {
425
+ stdout: `${lines.map((line) => `${line}
426
+ `).join("")}${summary}
427
+ `,
428
+ stderr: "",
429
+ exitCode: result.status === "failed" ? 1 : 0
430
+ };
431
+ } catch (err) {
432
+ return { stdout: "", stderr: `${failureLine(err)}
205
433
  `, exitCode: 1 };
206
434
  }
207
435
  }
436
+ async function runCases(deps2, input, opts) {
437
+ let loads;
438
+ try {
439
+ loads = loadCases(discoverCases(input.casesDir, input.filter));
440
+ } catch (err) {
441
+ return { stdout: "", stderr: `${failureLine(err)}
442
+ `, exitCode: 1 };
443
+ }
444
+ const outcomes = [];
445
+ for (const load of loads) {
446
+ if (load.scenario === void 0) {
447
+ outcomes.push({
448
+ id: load.id,
449
+ status: "failed",
450
+ error: load.error ?? "the case could not be read"
451
+ });
452
+ continue;
453
+ }
454
+ const caseOut = join(input.outDir, load.id);
455
+ try {
456
+ const result = await deps2.run({
457
+ scenario: load.scenario,
458
+ scenarioPath: load.path,
459
+ outDir: caseOut,
460
+ ...input.target === void 0 ? {} : { target: input.target },
461
+ ...input.rounds === void 0 ? {} : { rounds: input.rounds },
462
+ ...input.only === void 0 ? {} : { only: input.only },
463
+ ...input.keepGoing === true ? { keepGoing: true } : {}
464
+ });
465
+ const ok = result.steps.filter((step) => step.status === "ok").length;
466
+ outcomes.push({
467
+ id: load.id,
468
+ status: result.status === "failed" ? "failed" : "ok",
469
+ outDir: load.id,
470
+ steps: { ok, total: result.steps.length },
471
+ ...result.status === "failed" ? { error: firstFailure(result) ?? "the run reported failure" } : {}
472
+ });
473
+ } catch (err) {
474
+ outcomes.push({
475
+ id: load.id,
476
+ status: "failed",
477
+ ...existsSync(caseOut) ? { outDir: load.id } : {},
478
+ error: safeMessage(err)
479
+ });
480
+ }
481
+ }
482
+ const index = { version: 1, cases: outcomes };
483
+ try {
484
+ mkdirSync(input.outDir, { recursive: true });
485
+ writeFileSync(join(input.outDir, "cases.json"), `${JSON.stringify(index, null, 2)}
486
+ `);
487
+ } catch (err) {
488
+ return {
489
+ stdout: "",
490
+ stderr: `cannot write cases.json: ${safeMessage(err)}
491
+ `,
492
+ exitCode: 1
493
+ };
494
+ }
495
+ const failed = outcomes.filter((entry) => entry.status === "failed").length;
496
+ const exitCode = failed === 0 ? 0 : 1;
497
+ if (opts.json) {
498
+ return { stdout: `${JSON.stringify(index, null, 2)}
499
+ `, stderr: "", exitCode };
500
+ }
501
+ const lines = outcomes.map((entry) => {
502
+ const steps = entry.steps === void 0 ? "" : ` steps ${entry.steps.ok}/${entry.steps.total} ok`;
503
+ const error = entry.status === "ok" ? "" : ` ${entry.error ?? "failed"}`;
504
+ return `${entry.status === "ok" ? "ok " : "failed"} ${entry.id}${steps}${error}`;
505
+ });
506
+ const summary = failed === 0 ? `cases ${outcomes.length}/${outcomes.length} ok` : `cases ${outcomes.length - failed}/${outcomes.length} ok, ${failed} failed`;
507
+ return {
508
+ stdout: `${lines.map((line) => `${line}
509
+ `).join("")}${summary}
510
+ `,
511
+ stderr: "",
512
+ exitCode
513
+ };
514
+ }
515
+ function firstFailure(result) {
516
+ return result.steps.find((step) => step.status === "failed")?.error;
517
+ }
208
518
  function runTools(deps2, opts) {
209
519
  try {
210
520
  const tools = deps2.tools();
@@ -217,25 +527,97 @@ function runTools(deps2, opts) {
217
527
  });
218
528
  return { stdout: lines.join(""), stderr: "", exitCode: 0 };
219
529
  } catch (err) {
220
- return { stdout: "", stderr: `${safeMessage(err)}
530
+ return { stdout: "", stderr: `${failureLine(err)}
531
+ `, exitCode: 1 };
532
+ }
533
+ }
534
+ function targetsOf(opts) {
535
+ return {
536
+ ...opts.instancePath === void 0 ? {} : { instancePath: opts.instancePath },
537
+ ...opts.imageRoot === void 0 ? {} : { imageRoot: opts.imageRoot },
538
+ ...opts.emulatorPath === void 0 ? {} : { emulatorPath: opts.emulatorPath }
539
+ };
540
+ }
541
+ async function runEmulatorList(deps2, opts) {
542
+ try {
543
+ const instances = await deps2.emulator.list(targetsOf(opts));
544
+ if (opts.json) return { stdout: json({ instances }), stderr: "", exitCode: 0 };
545
+ if (instances.length === 0) return { stdout: "no emulator instances\n", stderr: "", exitCode: 0 };
546
+ const rows = instances.map((instance) => [
547
+ instance.name,
548
+ instance.running ? "yes" : "no",
549
+ instance.target ?? "\u2014",
550
+ instance.apiVersion ?? "\u2014",
551
+ instance.osVersion ?? "\u2014"
552
+ ]);
553
+ const header = ["NAME", "RUNNING", "TARGET", "API", "IMAGE"];
554
+ const widths = header.map((cell, column) => Math.max(cell.length, ...rows.map((row) => row[column].length)));
555
+ const line = (cells) => cells.map((cell, column) => cell.padEnd(widths[column])).join(" ").trimEnd();
556
+ const body = [header, ...rows].map((cells) => line(cells) + "\n").join("");
557
+ return { stdout: body, stderr: "", exitCode: 0 };
558
+ } catch (err) {
559
+ return { stdout: "", stderr: `${failureLine(err)}
560
+ `, exitCode: 1 };
561
+ }
562
+ }
563
+ async function runEmulatorStart(deps2, name, opts) {
564
+ try {
565
+ const result = await deps2.emulator.start(name, {
566
+ ...targetsOf(opts),
567
+ ...opts.timeoutMs === void 0 ? {} : { timeoutMs: opts.timeoutMs }
568
+ });
569
+ if (opts.json) return { stdout: json(result), stderr: "", exitCode: 0 };
570
+ const line = result.alreadyRunning ? `${result.name} was already running on ${result.target}
571
+ ` : `${result.name} started on ${result.target} (booted in ${Math.round(result.waitedMs / 1e3)}s)
572
+ `;
573
+ return { stdout: line, stderr: "", exitCode: 0 };
574
+ } catch (err) {
575
+ return { stdout: "", stderr: `${failureLine(err)}
576
+ `, exitCode: 1 };
577
+ }
578
+ }
579
+ async function runEmulatorStop(deps2, name, opts) {
580
+ try {
581
+ const result = await deps2.emulator.stop(name, targetsOf(opts));
582
+ if (opts.json) return { stdout: json(result), stderr: "", exitCode: 0 };
583
+ const line = result.wasRunning ? `${result.name} stopped
584
+ ` : `${result.name} was not running
585
+ `;
586
+ return { stdout: line, stderr: "", exitCode: 0 };
587
+ } catch (err) {
588
+ return { stdout: "", stderr: `${failureLine(err)}
589
+ `, exitCode: 1 };
590
+ }
591
+ }
592
+ async function runEmulatorCreate(deps2, req, opts) {
593
+ try {
594
+ const instance = await deps2.emulator.create(req);
595
+ if (opts.json) return { stdout: json(instance), stderr: "", exitCode: 0 };
596
+ const line = `Created ${instance.name} (${req.deviceType}, ${req.osVersion}) at ${instance.instancePath}
597
+ `;
598
+ return { stdout: line, stderr: "", exitCode: 0 };
599
+ } catch (err) {
600
+ return { stdout: "", stderr: `${failureLine(err)}
221
601
  `, exitCode: 1 };
222
602
  }
223
603
  }
224
604
 
225
605
  // src/deps.ts
226
- import { existsSync, readFileSync } from "fs";
227
- import { stat } from "fs/promises";
228
- import { dirname, join, resolve } from "path";
606
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
607
+ import { copyFile, mkdir, stat, writeFile } from "fs/promises";
608
+ import { basename, dirname, join as join2, resolve } from "path";
229
609
  import { fileURLToPath } from "url";
230
610
  import {
231
611
  BinderQuery,
232
612
  CallstackQuery,
233
613
  CapabilityMatrix,
614
+ EmulatorClient,
615
+ EmulatorLifecycle,
234
616
  FrameQuery,
235
617
  Hdc,
236
618
  InstantQuery,
237
619
  MemMeasureQuery,
238
- OhosPerfError,
620
+ OhosPerfError as OhosPerfError3,
239
621
  PerfQuery,
240
622
  ProcessQuery,
241
623
  SchedQuery,
@@ -245,26 +627,44 @@ import {
245
627
  ThreadStateQuery,
246
628
  connect,
247
629
  createSceneLayout,
630
+ decodePng,
248
631
  defaultAnalyzers,
249
632
  ingestScene,
250
633
  lookupQuery,
251
634
  queryDefinitions,
252
635
  readHidumperCapture,
253
636
  readProcfsSamples,
637
+ readHilogText,
638
+ parseHilogText,
639
+ analyzeHap,
640
+ buildReport,
254
641
  compareResults,
642
+ compareSceneDirs,
643
+ UI_DIFF_FILES,
644
+ renderEvidenceCsv,
645
+ renderMetricsCsv,
646
+ renderReportHtml,
647
+ renderReportJson,
648
+ renderReportXlsx,
649
+ renderSummaryJson,
650
+ renderFlamegraphHtml,
651
+ renderFlamegraphSvg,
652
+ hapSection,
255
653
  readSceneMetadata,
256
654
  readUiTree,
257
655
  resolveAppIdentity,
656
+ ScenarioRunner,
258
657
  resolveQueryLimit,
259
- runAnalyzers,
658
+ runAnalyzerSections,
260
659
  runNamedQuery,
660
+ summarizeReport,
261
661
  unknownQueryError
262
662
  } from "@ohos-perf/core";
263
663
  var here = dirname(fileURLToPath(import.meta.url));
264
- var manifestPath = join(here, "../package.json");
664
+ var manifestPath = join2(here, "../package.json");
265
665
  function packageVersion(path = manifestPath) {
266
666
  try {
267
- const pkg = JSON.parse(readFileSync(path, "utf8"));
667
+ const pkg = JSON.parse(readFileSync2(path, "utf8"));
268
668
  const version = typeof pkg.version === "string" ? pkg.version.trim() : "";
269
669
  return version === "" ? "0.0.0" : version;
270
670
  } catch {
@@ -297,18 +697,24 @@ var TABLE_RULES = [
297
697
  { id: "mem.procfs", collector: "procfs", tables: ["procfs.jsonl"] },
298
698
  { id: "render.fps_live", collector: "hidumper", tables: ["hidumper.json"] },
299
699
  { id: "ui.tree", collector: "uitest", tables: ["ui.json"] },
700
+ { id: "ui.capture", collector: "uitest", tables: ["screenshot.png"] },
701
+ { id: "hilog.stream", collector: "hilog", tables: ["hilog.log"] },
300
702
  { id: "perf.samples", collector: "hiperf", tables: ["perf_sample"], perf: true },
301
- // `mem.native_hook` is the design's hiprofiler-memory row. Offline it is
302
- // satisfied by the memory-plugin tables, exactly as `trace.frames` is
303
- // satisfied by `frame_slice` + `process` rather than by the hitrace binary.
304
- // The analyzer joins both tables, so a trace missing the filter table would
305
- // crash rather than degrade; requiring both keeps the matrix honest. An
306
- // ftrace-only scene does not offer it, and the engine reports `mem-measure`
307
- // as skipped.
703
+ // `mem.native_hook` is the design's hiprofiler-memory row, and two plugins
704
+ // feed it. The memory plugin's `process_measure` tables back `mem-measure`;
705
+ // the nativehook plugin's `native_hook*` tables back `native-memory`. A
706
+ // scene carries one family or the other, so requiring the memory tables
707
+ // alone would degrade `native-memory` on the very capture
708
+ // `--plugins nativehook` produces. Either family satisfies the row; the
709
+ // analyzers that need a specific one degrade on their own with a reason
710
+ // naming the missing input. An ftrace-only scene offers neither.
308
711
  {
309
712
  id: "mem.native_hook",
310
713
  collector: "hiprofiler",
311
- tables: ["process_measure", "process_measure_filter"]
714
+ anyOf: [
715
+ ["process_measure", "process_measure_filter"],
716
+ ["native_hook"]
717
+ ]
312
718
  }
313
719
  ];
314
720
  function artifactPresent(name, artifacts) {
@@ -319,11 +725,21 @@ function artifactPresent(name, artifacts) {
319
725
  return artifacts.hidumper !== void 0;
320
726
  case "ui.json":
321
727
  return (artifacts.uiTree?.length ?? 0) > 0;
728
+ case "screenshot.png":
729
+ return artifacts.screenshot !== void 0;
730
+ case "hilog.log":
731
+ return (artifacts.hilog?.length ?? 0) > 0;
322
732
  default:
323
733
  return false;
324
734
  }
325
735
  }
326
- var ARTIFACT_NAMES = /* @__PURE__ */ new Set(["procfs.jsonl", "hidumper.json", "ui.json"]);
736
+ var ARTIFACT_NAMES = /* @__PURE__ */ new Set([
737
+ "procfs.jsonl",
738
+ "hidumper.json",
739
+ "ui.json",
740
+ "screenshot.png",
741
+ "hilog.log"
742
+ ]);
327
743
  function offlineCapabilities(db, artifacts, perfDb) {
328
744
  const tablesOf = (target) => new Set(
329
745
  target.query(
@@ -335,9 +751,8 @@ function offlineCapabilities(db, artifacts, perfDb) {
335
751
  const states = [];
336
752
  for (const rule of TABLE_RULES) {
337
753
  const source = rule.perf === true ? perfTables : tables;
338
- const present = rule.tables.every(
339
- (name) => ARTIFACT_NAMES.has(name) ? artifactPresent(name, artifacts) : source.has(name)
340
- );
754
+ const has = (name) => ARTIFACT_NAMES.has(name) ? artifactPresent(name, artifacts) : source.has(name);
755
+ const present = rule.anyOf === void 0 ? (rule.tables ?? []).every(has) : rule.anyOf.some((family) => family.every(has));
341
756
  if (!present) continue;
342
757
  if (rule.perf === true && perfDb !== void 0) {
343
758
  const first = rule.tables[0];
@@ -354,54 +769,96 @@ async function isDirectory(path) {
354
769
  return false;
355
770
  }
356
771
  }
357
- async function analyzeScene(open, sceneDir, app) {
772
+ function analyzeContext(opened) {
773
+ const db = opened.scene.traceDb;
774
+ return {
775
+ db,
776
+ frames: new FrameQuery(db),
777
+ processes: new ProcessQuery(db),
778
+ threads: new ThreadQuery(db),
779
+ sched: new SchedQuery(db),
780
+ instant: new InstantQuery(db),
781
+ threadStates: new ThreadStateQuery(db),
782
+ callstacks: new CallstackQuery(db),
783
+ // A hiperf capture lives in its own converted database; the trace
784
+ // database has no perf_* tables, so reading them from `db` would
785
+ // silently report no samples.
786
+ perf: new PerfQuery(opened.scene.perfDb ?? db),
787
+ binder: new BinderQuery(db),
788
+ startup: new StartupQuery(db),
789
+ // memory-plugin writes an .htrace that converts into trace.db, so the
790
+ // tables are in `db`, not in the separate perf database.
791
+ memMeasure: new MemMeasureQuery(db),
792
+ ...opened.samples.length > 0 ? { procfs: opened.samples } : {},
793
+ ...opened.uiTree === void 0 ? {} : { ui: opened.uiTree },
794
+ ...opened.screenshot === void 0 ? {} : { screenshot: opened.screenshot },
795
+ ...opened.screenshotError === void 0 ? {} : { screenshotError: opened.screenshotError },
796
+ ...opened.hidumper === void 0 ? {} : { hidumper: opened.hidumper },
797
+ ...opened.hilog === void 0 ? {} : { hilog: [...opened.hilog] },
798
+ ...opened.metadata !== void 0 ? { metadata: opened.metadata } : {},
799
+ app: opened.app,
800
+ // The whole database: a CLI run has no capture window to honour.
801
+ window: { startNs: 0, endNs: Number.MAX_SAFE_INTEGER },
802
+ caps: opened.caps,
803
+ deviceId: "offline"
804
+ };
805
+ }
806
+ function sceneWindow(opened) {
807
+ try {
808
+ const rows = opened.scene.traceDb.query(
809
+ "SELECT MIN(start_ts) AS start_ts, MAX(end_ts) AS end_ts FROM trace_range"
810
+ );
811
+ const row = rows[0];
812
+ if (row !== void 0 && typeof row.start_ts === "number" && typeof row.end_ts === "number" && row.end_ts > row.start_ts) {
813
+ return { startNs: row.start_ts, endNs: row.end_ts };
814
+ }
815
+ } catch {
816
+ }
817
+ return { startNs: 0, endNs: Number.MAX_SAFE_INTEGER };
818
+ }
819
+ function flamegraphInputs(opened) {
820
+ const perf = new PerfQuery(opened.scene.perfDb ?? opened.scene.traceDb);
821
+ const threadIds = [...new Set(perf.threads([...opened.app.pids]).map((t) => t.threadId))].sort((a, b) => a - b);
822
+ const stacks = perf.foldedStacks(threadIds, { startNs: 0, endNs: Number.MAX_SAFE_INTEGER });
823
+ const hiperf = opened.metadata?.capture?.hiperf;
824
+ const symbolizationRequested = typeof hiperf?.symbolized === "boolean" ? hiperf.symbolized : null;
825
+ return { stacks, symbolizationRequested };
826
+ }
827
+ async function analyzeSceneDetailed(open, sceneDir, app, options = {}) {
358
828
  const opened = await open(sceneDir, app);
359
829
  try {
360
- const db = opened.scene.traceDb;
361
- const context = {
362
- db,
363
- frames: new FrameQuery(db),
364
- processes: new ProcessQuery(db),
365
- threads: new ThreadQuery(db),
366
- sched: new SchedQuery(db),
367
- instant: new InstantQuery(db),
368
- threadStates: new ThreadStateQuery(db),
369
- callstacks: new CallstackQuery(db),
370
- // A hiperf capture lives in its own converted database; the trace
371
- // database has no perf_* tables, so reading them from `db` would
372
- // silently report no samples.
373
- perf: new PerfQuery(opened.scene.perfDb ?? db),
374
- binder: new BinderQuery(db),
375
- startup: new StartupQuery(db),
376
- // memory-plugin writes an .htrace that converts into trace.db, so the
377
- // tables are in `db`, not in the separate perf database.
378
- memMeasure: new MemMeasureQuery(db),
379
- ...opened.samples.length > 0 ? { procfs: opened.samples } : {},
380
- ...opened.hidumper === void 0 ? {} : { hidumper: opened.hidumper },
381
- ...opened.metadata !== void 0 ? { metadata: opened.metadata } : {},
830
+ const run = await runAnalyzerSections(defaultAnalyzers(), analyzeContext(opened));
831
+ return {
832
+ run,
382
833
  app: opened.app,
383
- // The whole database: a CLI run has no capture window to honour.
384
- window: { startNs: 0, endNs: Number.MAX_SAFE_INTEGER },
385
- caps: opened.caps,
386
- deviceId: "offline"
834
+ device: opened.metadata?.deviceId ?? "offline",
835
+ window: sceneWindow(opened),
836
+ ...opened.metadata?.startedAtNs === void 0 ? {} : { startedAtNs: opened.metadata.startedAtNs },
837
+ ...opened.screenshot === void 0 ? {} : {
838
+ screenshot: { width: opened.screenshot.width, height: opened.screenshot.height },
839
+ screenshotFile: opened.layout.screenshotFile
840
+ },
841
+ ...options.flamegraph === true ? { flamegraph: flamegraphInputs(opened) } : {}
387
842
  };
388
- return await runAnalyzers(defaultAnalyzers(), context);
389
843
  } finally {
390
844
  opened.scene.close();
391
845
  }
392
846
  }
847
+ async function analyzeScene(open, sceneDir, app) {
848
+ return (await analyzeSceneDetailed(open, sceneDir, app)).run.result;
849
+ }
393
850
  function readAnalysisFile(path) {
394
851
  let parsed;
395
852
  try {
396
- parsed = JSON.parse(readFileSync(path, "utf8"));
853
+ parsed = JSON.parse(readFileSync2(path, "utf8"));
397
854
  } catch (err) {
398
- throw new OhosPerfError(
855
+ throw new OhosPerfError3(
399
856
  `cannot read analysis ${path}: ${safeMessage(err)}`,
400
857
  { code: "COMPARE_BAD_INPUT", cause: err }
401
858
  );
402
859
  }
403
860
  if (typeof parsed !== "object" || parsed === null || !Array.isArray(parsed.metrics) || !Array.isArray(parsed.evidence)) {
404
- throw new OhosPerfError(
861
+ throw new OhosPerfError3(
405
862
  `analysis ${path} has no metrics/evidence arrays; pass a scene directory or the output of \`ohos-perf analyze --json\``,
406
863
  { code: "COMPARE_BAD_INPUT" }
407
864
  );
@@ -410,9 +867,10 @@ function readAnalysisFile(path) {
410
867
  }
411
868
  function realDeps(version = packageVersion(), overrides = {}) {
412
869
  const resolveHdc = () => (overrides.hdc ?? new Hdc()).resolvePath();
413
- const connectDevice = overrides.connectDevice ?? (() => connect());
870
+ const connectDevice = overrides.connectDevice ?? ((target) => connect(target === void 0 ? {} : { target }));
414
871
  const ingest = overrides.ingest ?? ingestScene;
415
- const collectDevice = overrides.collectDevice ?? (() => connect());
872
+ const collectDevice = overrides.collectDevice ?? ((target) => connect(target === void 0 ? {} : { target }));
873
+ const gestureDevice = overrides.gestureDevice ?? ((target) => connect(target === void 0 ? {} : { target }));
416
874
  const doctor = {
417
875
  resolveHdc,
418
876
  async resolveStreamer() {
@@ -421,18 +879,44 @@ function realDeps(version = packageVersion(), overrides = {}) {
421
879
  },
422
880
  connectDevice
423
881
  };
882
+ const emulatorClient = (o) => new EmulatorClient({
883
+ ...o.emulatorPath === void 0 ? {} : { emulatorPath: o.emulatorPath },
884
+ ...o.instancePath === void 0 ? {} : { instancePath: o.instancePath },
885
+ ...o.imageRoot === void 0 ? {} : { imageRoot: o.imageRoot }
886
+ });
887
+ const emulator = {
888
+ list: (o) => new EmulatorLifecycle({ client: emulatorClient(o) }).list(),
889
+ start: (name, o) => new EmulatorLifecycle({ client: emulatorClient(o) }).start(name, o.timeoutMs === void 0 ? {} : { timeoutMs: o.timeoutMs }),
890
+ stop: (name, o) => new EmulatorLifecycle({ client: emulatorClient(o) }).stop(name),
891
+ create: (req) => new EmulatorLifecycle({ client: emulatorClient(req) }).create(req)
892
+ };
424
893
  const openOfflineScene = async (sceneDir, app) => {
425
894
  const layout = createSceneLayout(resolve(sceneDir));
426
895
  const scene = await ingest(new Streamer(), layout);
427
896
  try {
428
897
  const db = scene.traceDb;
429
898
  const processes = new ProcessQuery(db);
430
- const hasMetadataFile = existsSync(layout.metadataFile);
899
+ const hasMetadataFile = existsSync2(layout.metadataFile);
431
900
  const metadata = hasMetadataFile ? readSceneMetadata(layout) : void 0;
432
901
  const declared = (collector) => !hasMetadataFile || metadata !== void 0 && (metadata.capture?.collectors.includes(collector) ?? false);
433
902
  const samples = declared("procfs") ? readProcfsSamples(layout.procfsFile) : [];
434
903
  const hidumper = declared("hidumper") ? readHidumperCapture(layout.hidumperFile) : void 0;
435
904
  const uiTree = declared("uitest") ? readUiTree(layout.uiFile) : void 0;
905
+ const screenshotFile = declared("screenshot") ? layout.screenshotFile : void 0;
906
+ let screenshot;
907
+ let screenshotError;
908
+ if (screenshotFile !== void 0 && existsSync2(screenshotFile)) {
909
+ try {
910
+ screenshot = decodePng(new Uint8Array(readFileSync2(screenshotFile)));
911
+ } catch (err) {
912
+ screenshotError = safeMessage(err);
913
+ }
914
+ }
915
+ const hilogText = declared("hilog") ? readHilogText(layout) : void 0;
916
+ const hilog = hilogText === void 0 ? void 0 : parseHilogText(hilogText, {
917
+ ...metadata?.capture === void 0 ? {} : { year: new Date(metadata.capture.startedAtMs).getUTCFullYear() },
918
+ captureNs: (metadata?.capture?.startedAtMs ?? 0) * 1e6
919
+ });
436
920
  let appIdentity;
437
921
  if (app !== void 0) {
438
922
  appIdentity = resolveAppIdentity(processes, app);
@@ -457,12 +941,17 @@ function realDeps(version = packageVersion(), overrides = {}) {
457
941
  {
458
942
  procfsSamples: samples,
459
943
  ...hidumper === void 0 ? {} : { hidumper },
460
- ...uiTree === void 0 ? {} : { uiTree }
944
+ ...uiTree === void 0 ? {} : { uiTree },
945
+ ...screenshot === void 0 ? {} : { screenshot },
946
+ ...hilog === void 0 ? {} : { hilog }
461
947
  },
462
948
  scene.perfDb
463
949
  ),
464
950
  ...uiTree === void 0 ? {} : { uiTree },
465
- ...hidumper === void 0 ? {} : { hidumper }
951
+ ...screenshot === void 0 ? {} : { screenshot },
952
+ ...screenshotError === void 0 ? {} : { screenshotError },
953
+ ...hidumper === void 0 ? {} : { hidumper },
954
+ ...hilog === void 0 ? {} : { hilog }
466
955
  };
467
956
  } catch (err) {
468
957
  scene.close();
@@ -472,14 +961,19 @@ function realDeps(version = packageVersion(), overrides = {}) {
472
961
  return {
473
962
  doctor,
474
963
  version,
475
- async capsReport() {
964
+ emulator,
965
+ async gesture(req) {
966
+ const device = await gestureDevice(req.target);
967
+ return device.gesture(req.gesture);
968
+ },
969
+ async capsReport(target) {
476
970
  try {
477
971
  await resolveHdc();
478
972
  } catch (err) {
479
973
  return { hdcOk: false, hdcError: safeMessage(err), capabilities: [] };
480
974
  }
481
975
  try {
482
- const device = await connectDevice();
976
+ const device = await connectDevice(target);
483
977
  const matrix = await device.capabilities();
484
978
  return { hdcOk: true, capabilities: matrix.all() };
485
979
  } catch (err) {
@@ -498,9 +992,13 @@ function realDeps(version = packageVersion(), overrides = {}) {
498
992
  return runNamedQuery(
499
993
  {
500
994
  db: opened.scene.traceDb,
995
+ // A `--hiperf` scene keeps perf_sample/perf_thread in perf.db;
996
+ // omitting this made every frame.load.* query return [] on device.
997
+ ...opened.scene.perfDb === void 0 ? {} : { perfDb: opened.scene.perfDb },
501
998
  app: opened.app,
502
999
  caps: opened.caps,
503
- ...opened.uiTree === void 0 ? {} : { uiTree: opened.uiTree }
1000
+ ...opened.uiTree === void 0 ? {} : { uiTree: opened.uiTree },
1001
+ ...opened.hilog === void 0 ? {} : { hilog: opened.hilog }
504
1002
  },
505
1003
  req.name,
506
1004
  args,
@@ -515,6 +1013,128 @@ function realDeps(version = packageVersion(), overrides = {}) {
515
1013
  const [baseline, current] = await Promise.all([load(req.baseline), load(req.current)]);
516
1014
  return compareResults(baseline, current);
517
1015
  },
1016
+ async uiCompare(req) {
1017
+ const diff = await compareSceneDirs(req.a, req.b, { outDir: req.outDir });
1018
+ return {
1019
+ outDir: resolve(req.outDir),
1020
+ files: [...UI_DIFF_FILES],
1021
+ tree: diff.tree === null ? null : {
1022
+ added: diff.tree.added.length,
1023
+ removed: diff.tree.removed.length,
1024
+ changed: diff.tree.changed.length,
1025
+ unchanged: diff.tree.unchanged
1026
+ },
1027
+ image: diff.image === null ? null : {
1028
+ hamming: diff.image.hamming,
1029
+ similarity: diff.image.similarity,
1030
+ changedRatio: diff.image.changedRatio,
1031
+ tolerance: diff.image.tolerance
1032
+ },
1033
+ regions: diff.regions.length,
1034
+ degraded: [...diff.degraded]
1035
+ };
1036
+ },
1037
+ async report(req) {
1038
+ const detailed = await analyzeSceneDetailed(
1039
+ openOfflineScene,
1040
+ req.sceneDir,
1041
+ req.app,
1042
+ { flamegraph: true }
1043
+ );
1044
+ let comparison;
1045
+ if (req.baseline !== void 0) {
1046
+ const baseline = await (await isDirectory(req.baseline) ? analyzeScene(openOfflineScene, req.baseline) : readAnalysisFile(req.baseline));
1047
+ comparison = compareResults(baseline, detailed.run.result);
1048
+ }
1049
+ const model = buildReport({
1050
+ generator: { name: "@ohos-perf/core", version },
1051
+ app: detailed.app,
1052
+ device: detailed.device,
1053
+ window: detailed.window,
1054
+ ...detailed.startedAtNs === void 0 ? {} : { startedAtNs: detailed.startedAtNs },
1055
+ sections: detailed.run.sections,
1056
+ ...comparison === void 0 ? {} : { comparison },
1057
+ ...detailed.screenshot === void 0 ? {} : { screenshot: detailed.screenshot }
1058
+ });
1059
+ const artifacts = [
1060
+ ["report.html", renderReportHtml(model)],
1061
+ ["report.json", renderReportJson(model)],
1062
+ ["summary.json", renderSummaryJson(summarizeReport(model))],
1063
+ ["metrics.csv", renderMetricsCsv(model)],
1064
+ ["evidence.csv", renderEvidenceCsv(model)],
1065
+ ["report.xlsx", renderReportXlsx(model)]
1066
+ ];
1067
+ const flamegraph = detailed.flamegraph;
1068
+ if (flamegraph !== void 0 && flamegraph.stacks.length > 0) {
1069
+ const share = model.sections.find((section) => section.id === "symbols")?.metrics.find((metric) => metric.id === "symbol.unresolved.share")?.value;
1070
+ artifacts.push(
1071
+ ["flamegraph.svg", renderFlamegraphSvg(flamegraph.stacks)],
1072
+ ["flamegraph.html", renderFlamegraphHtml({
1073
+ stacks: flamegraph.stacks,
1074
+ app: detailed.app.packageName,
1075
+ window: detailed.window,
1076
+ unresolvedShare: typeof share === "number" ? share : null,
1077
+ symbolizationRequested: flamegraph.symbolizationRequested
1078
+ })]
1079
+ );
1080
+ }
1081
+ const outDir = resolve(req.outDir);
1082
+ await mkdir(outDir, { recursive: true });
1083
+ for (const [name, content] of artifacts) {
1084
+ await writeFile(join2(outDir, name), content);
1085
+ }
1086
+ const files = artifacts.map(([name]) => name);
1087
+ if (detailed.screenshotFile !== void 0 && detailed.screenshot !== void 0) {
1088
+ await mkdir(join2(outDir, "assets"), { recursive: true });
1089
+ await copyFile(detailed.screenshotFile, join2(outDir, "assets", "screenshot.png"));
1090
+ files.push("assets/screenshot.png");
1091
+ }
1092
+ return {
1093
+ outDir,
1094
+ files,
1095
+ sections: {
1096
+ total: model.sections.length,
1097
+ measured: model.totals.measured,
1098
+ degraded: model.totals.degraded
1099
+ },
1100
+ metrics: model.totals.metrics,
1101
+ evidence: model.totals.evidence,
1102
+ bySeverity: { ...model.totals.bySeverity },
1103
+ ...model.comparison === void 0 ? {} : { comparison: { ...model.comparison.totals } }
1104
+ };
1105
+ },
1106
+ async hap(req) {
1107
+ const analysis = analyzeHap(readFileSync2(req.packagePath), basename(req.packagePath));
1108
+ const capabilities = [{
1109
+ id: "static.hap",
1110
+ available: true,
1111
+ collector: "offline",
1112
+ fidelity: "exact",
1113
+ probe: { command: "", stdout: "", stderr: "", code: 0 }
1114
+ }];
1115
+ if (req.outDir === void 0) return { analysis, capabilities };
1116
+ const model = buildReport({
1117
+ generator: { name: "@ohos-perf/core", version },
1118
+ app: {
1119
+ packageName: analysis.package.bundleName === "" ? analysis.package.name : analysis.package.bundleName,
1120
+ pids: [],
1121
+ processNames: []
1122
+ },
1123
+ device: "offline",
1124
+ window: { startNs: 0, endNs: 0 },
1125
+ sections: [hapSection(analysis)]
1126
+ });
1127
+ const artifacts = [
1128
+ ["hap.json", JSON.stringify(analysis, null, 2) + "\n"],
1129
+ ["hap.html", renderReportHtml(model)]
1130
+ ];
1131
+ const outDir = resolve(req.outDir);
1132
+ await mkdir(outDir, { recursive: true });
1133
+ for (const [name, content] of artifacts) {
1134
+ await writeFile(join2(outDir, name), content);
1135
+ }
1136
+ return { analysis, capabilities, outDir, artifacts: artifacts.map(([name]) => name) };
1137
+ },
518
1138
  tools() {
519
1139
  return queryDefinitions().map((definition) => ({
520
1140
  name: definition.name,
@@ -523,9 +1143,19 @@ function realDeps(version = packageVersion(), overrides = {}) {
523
1143
  returns: definition.returns
524
1144
  }));
525
1145
  },
1146
+ async run(req) {
1147
+ const device = await connect(req.target === void 0 ? {} : { target: req.target });
1148
+ const runner = new ScenarioRunner(device, {
1149
+ outDir: resolve(req.outDir),
1150
+ ...req.rounds === void 0 ? {} : { rounds: req.rounds },
1151
+ ...req.only === void 0 ? {} : { only: req.only },
1152
+ ...req.keepGoing === true ? { keepGoing: true } : {}
1153
+ });
1154
+ return runner.run(req.scenario);
1155
+ },
526
1156
  async collect(req) {
527
1157
  const sceneDir = resolve(req.out);
528
- const device = await collectDevice();
1158
+ const device = await collectDevice(req.target);
529
1159
  const session = await device.collect({
530
1160
  app: req.app,
531
1161
  durationMs: req.durationMs,
@@ -536,8 +1166,11 @@ function realDeps(version = packageVersion(), overrides = {}) {
536
1166
  hiprofiler: req.hiprofiler.plugins === void 0 ? {} : { plugins: req.hiprofiler.plugins }
537
1167
  },
538
1168
  ...req.hiperf === void 0 ? {} : { hiperf: req.hiperf },
1169
+ ...req.soDir === void 0 ? {} : { soDir: req.soDir },
539
1170
  ...req.hidumper === true ? { hidumper: true } : {},
540
- ...req.uitest === true ? { uitest: true } : {}
1171
+ ...req.uitest === true ? { uitest: true } : {},
1172
+ ...req.screenshot === true ? { screenshot: true } : {},
1173
+ ...req.hilog === true ? { hilog: true } : {}
541
1174
  });
542
1175
  const scene = await session.ingest();
543
1176
  try {
@@ -547,9 +1180,22 @@ function realDeps(version = packageVersion(), overrides = {}) {
547
1180
  sceneDir,
548
1181
  device: { id: device.id, kind: device.kind },
549
1182
  collectors: meta?.capture?.collectors ?? [],
550
- ...meta?.capture?.hiperf === void 0 ? {} : { hiperf: { samples: meta.capture.hiperf.samples } },
1183
+ ...meta?.capture?.hiperf === void 0 ? {} : {
1184
+ hiperf: {
1185
+ samples: meta.capture.hiperf.samples,
1186
+ ...meta.capture.hiperf.symbolized === void 0 ? {} : { symbolized: meta.capture.hiperf.symbolized }
1187
+ }
1188
+ },
1189
+ ...req.soDir === void 0 ? {} : { soDir: resolve(req.soDir) },
551
1190
  ...meta?.capture?.hidumper === void 0 ? {} : { hidumper: { frames: meta.capture.hidumper.frames } },
552
- ...meta?.capture?.uitest === void 0 ? {} : { ui: { nodes: meta.capture.uitest.nodes } }
1191
+ ...meta?.capture?.uitest === void 0 ? {} : { ui: { nodes: meta.capture.uitest.nodes } },
1192
+ ...meta?.capture?.screenshot === void 0 ? {} : {
1193
+ screenshot: {
1194
+ width: meta.capture.screenshot.width,
1195
+ height: meta.capture.screenshot.height
1196
+ }
1197
+ },
1198
+ ...meta?.capture?.hilog === void 0 ? {} : { hilog: { lines: meta.capture.hilog.lines } }
553
1199
  };
554
1200
  } finally {
555
1201
  scene.close();
@@ -564,14 +1210,14 @@ import { Command } from "commander";
564
1210
  // src/collect.ts
565
1211
  import {
566
1212
  HIPROFILER_PLUGIN_NAMES,
567
- OhosPerfError as OhosPerfError2
1213
+ OhosPerfError as OhosPerfError4
568
1214
  } from "@ohos-perf/core";
569
1215
  var MAX_TIMEOUT_MS = 2147483647;
570
1216
  function parseDurationSeconds(raw) {
571
1217
  const text = raw.trim();
572
1218
  const match = /^(\d+(?:\.\d+)?|\.\d+)s?$/.exec(text);
573
1219
  const seconds = match === null ? Number.NaN : Number(match[1]);
574
- const bad = (why) => new OhosPerfError2(
1220
+ const bad = (why) => new OhosPerfError4(
575
1221
  `invalid --duration ${JSON.stringify(raw)}: ${why} (expected a positive whole number of milliseconds, e.g. 10 or 10s)`,
576
1222
  { code: "COLLECT_BAD_DURATION" }
577
1223
  );
@@ -594,7 +1240,7 @@ function parseDurationSeconds(raw) {
594
1240
  function parsePluginList(raw) {
595
1241
  const names = raw.split(",").map((name) => name.trim());
596
1242
  if (names.length === 0 || names.some((name) => name === "")) {
597
- throw new OhosPerfError2(
1243
+ throw new OhosPerfError4(
598
1244
  `invalid --plugins ${JSON.stringify(raw)}: expected a comma-separated list of ` + HIPROFILER_PLUGIN_NAMES.join(", "),
599
1245
  { code: "COLLECT_BAD_PLUGIN" }
600
1246
  );
@@ -602,7 +1248,7 @@ function parsePluginList(raw) {
602
1248
  const plugins = [];
603
1249
  for (const name of names) {
604
1250
  if (!HIPROFILER_PLUGIN_NAMES.includes(name)) {
605
- throw new OhosPerfError2(
1251
+ throw new OhosPerfError4(
606
1252
  `unknown hiprofiler plugin ${JSON.stringify(name)}; expected one of ${HIPROFILER_PLUGIN_NAMES.join(", ")}`,
607
1253
  { code: "COLLECT_BAD_PLUGIN" }
608
1254
  );
@@ -614,23 +1260,64 @@ function parsePluginList(raw) {
614
1260
  return plugins;
615
1261
  }
616
1262
 
1263
+ // src/gesture.ts
1264
+ var COORDINATE = /^\d+$/;
1265
+ var CONTROL_CHARS = /[\u0000-\u001f\u007f]/;
1266
+ function parseCoordinate(raw, label) {
1267
+ const value = Number(raw);
1268
+ if (!COORDINATE.test(raw) || !Number.isSafeInteger(value)) {
1269
+ throw new Error(
1270
+ `invalid ${label}: expected a non-negative whole number, got ${JSON.stringify(raw)}`
1271
+ );
1272
+ }
1273
+ return value;
1274
+ }
1275
+ function parseVelocity(raw) {
1276
+ const value = Number(raw);
1277
+ if (!COORDINATE.test(raw) || !Number.isSafeInteger(value) || value < 200 || value > 4e4) {
1278
+ throw new Error(
1279
+ `invalid --velocity: expected a whole number from 200 to 40000, got ${JSON.stringify(raw)}`
1280
+ );
1281
+ }
1282
+ return value;
1283
+ }
1284
+ function parseKey(raw) {
1285
+ if (raw === "Back" || raw === "Home" || raw === "Power") return raw;
1286
+ const value = Number(raw);
1287
+ if (/^[1-9]\d*$/.test(raw) && Number.isSafeInteger(value)) return value;
1288
+ throw new Error(
1289
+ `invalid <key>: expected Back, Home, Power or a positive key code, got ${JSON.stringify(raw)}`
1290
+ );
1291
+ }
1292
+ function parseText(raw) {
1293
+ if (raw === "") {
1294
+ throw new Error("invalid <text>: expected a non-empty string");
1295
+ }
1296
+ if (CONTROL_CHARS.test(raw)) {
1297
+ throw new Error(
1298
+ `invalid <text>: expected no control characters, got ${JSON.stringify(raw)}`
1299
+ );
1300
+ }
1301
+ return raw;
1302
+ }
1303
+
617
1304
  // src/query.ts
618
- import { MAX_QUERY_LIMIT, OhosPerfError as OhosPerfError3, resolveQueryLimit as resolveQueryLimit2 } from "@ohos-perf/core";
1305
+ import { MAX_QUERY_LIMIT, OhosPerfError as OhosPerfError5, resolveQueryLimit as resolveQueryLimit2 } from "@ohos-perf/core";
619
1306
  function parseQueryArgs(raw) {
620
1307
  let value;
621
1308
  try {
622
1309
  value = JSON.parse(raw);
623
1310
  } catch {
624
- throw new OhosPerfError3("invalid --args: not valid JSON", { code: "QUERY_BAD_ARGS" });
1311
+ throw new OhosPerfError5("invalid --args: not valid JSON", { code: "QUERY_BAD_ARGS" });
625
1312
  }
626
1313
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
627
- throw new OhosPerfError3("invalid --args: expected a JSON object", { code: "QUERY_BAD_ARGS" });
1314
+ throw new OhosPerfError5("invalid --args: expected a JSON object", { code: "QUERY_BAD_ARGS" });
628
1315
  }
629
1316
  return value;
630
1317
  }
631
1318
  function parseLimit(raw) {
632
1319
  const text = raw.trim();
633
- const bad = () => new OhosPerfError3(
1320
+ const bad = () => new OhosPerfError5(
634
1321
  `limit must be an integer between 1 and ${MAX_QUERY_LIMIT}, got ${JSON.stringify(raw)}`,
635
1322
  { code: "QUERY_BAD_LIMIT" }
636
1323
  );
@@ -642,7 +1329,25 @@ function parseLimit(raw) {
642
1329
  }
643
1330
  }
644
1331
 
1332
+ // src/run.ts
1333
+ function parseOnly(raw) {
1334
+ const ids = raw.split(",").map((id) => id.trim());
1335
+ if (ids.some((id) => id === "")) {
1336
+ throw new Error(
1337
+ `invalid --only ${JSON.stringify(raw)}: an empty step id names no step; expected a comma-separated list of ids`
1338
+ );
1339
+ }
1340
+ return ids;
1341
+ }
1342
+
645
1343
  // src/program.ts
1344
+ function targetOptionsOf(opts) {
1345
+ return {
1346
+ ...opts.instancePath === void 0 ? {} : { instancePath: opts.instancePath },
1347
+ ...opts.imageRoot === void 0 ? {} : { imageRoot: opts.imageRoot },
1348
+ ...opts.emulator === void 0 ? {} : { emulatorPath: opts.emulator }
1349
+ };
1350
+ }
646
1351
  function buildProgram(deps2, io, opts = {}) {
647
1352
  const program2 = new Command();
648
1353
  program2.configureOutput({
@@ -651,10 +1356,10 @@ function buildProgram(deps2, io, opts = {}) {
651
1356
  });
652
1357
  if (opts.exitOverride) program2.exitOverride();
653
1358
  program2.name("ohos-perf").description("Performance analysis for OpenHarmony devices and captured traces").version(deps2.version);
654
- program2.command("doctor").description("check the hdc/trace_streamer toolchain and the attached device").option("--json", "print the report as JSON").action(async (opts2) => {
1359
+ program2.command("doctor").description("check the hdc/trace_streamer toolchain and the attached device").option("--target <id>", "probe this hdc target instead of the first connected one").option("--json", "print the report as JSON").action(async (opts2) => {
655
1360
  io.emit(await runDoctor(deps2, opts2));
656
1361
  });
657
- program2.command("caps").description("print the capability matrix of the attached device").option("--json", "print the capabilities as JSON").action(async (opts2) => {
1362
+ program2.command("caps").description("print the capability matrix of the attached device").option("--target <id>", "probe this hdc target instead of the first connected one").option("--json", "print the capabilities as JSON").action(async (opts2) => {
658
1363
  io.emit(await runCaps(deps2, opts2));
659
1364
  });
660
1365
  program2.command("analyze").description("analyze a captured scene directory (trace.db or trace.htrace)").argument("<scene-dir>", "directory containing trace.db / trace.htrace").option("--app <packageName>", "app package name, for evidence wording").option("--json", "print the analysis result as JSON").action(async (sceneDir, opts2) => {
@@ -666,12 +1371,15 @@ function buildProgram(deps2, io, opts = {}) {
666
1371
  ).requiredOption("--duration <seconds>", "capture duration in seconds (10 or 10s)").requiredOption("--out <dir>", "scene output directory").option("--procfs", "also sample /proc memory state for the app").option("--cold-start <ability>", "launch this ability before capturing").option("--hiprofiler", "capture through hiprofiler instead of hitrace").option(
667
1372
  "--plugins <list>",
668
1373
  "hiprofiler plugins, comma-separated: ftrace, gpu, xpower, nativehook, memory"
669
- ).option("--hiperf", "also capture a hiperf perf.data (debuggable app only)").option("--hidumper", "also sample the RenderService fps and hitch counters").option("--uitest", "also dump the on-screen UI tree").option("--json", "print the result as JSON").action(async (opts2) => {
1374
+ ).option("--hiperf", "also capture a hiperf perf.data (debuggable app only)").option(
1375
+ "--so-dir <dir>",
1376
+ "host directory of shared objects to symbolize the hiperf capture with"
1377
+ ).option("--hidumper", "also sample the RenderService fps and hitch counters").option("--uitest", "also dump the on-screen UI tree").option("--screenshot", "also capture the whole screen into screenshot.png").option("--hilog", "also stream the device log (hilog) for the capture window").option("--target <id>", "capture from this hdc target instead of the first connected one").option("--json", "print the result as JSON").action(async (opts2) => {
670
1378
  let durationMs;
671
1379
  try {
672
1380
  durationMs = parseDurationSeconds(opts2.duration);
673
1381
  } catch (err) {
674
- io.emit({ stdout: "", stderr: `${safeMessage(err)}
1382
+ io.emit({ stdout: "", stderr: `${failureLine(err)}
675
1383
  `, exitCode: 1 });
676
1384
  return;
677
1385
  }
@@ -683,12 +1391,20 @@ function buildProgram(deps2, io, opts = {}) {
683
1391
  });
684
1392
  return;
685
1393
  }
1394
+ if (opts2.soDir !== void 0 && opts2.hiperf !== true) {
1395
+ io.emit({
1396
+ stdout: "",
1397
+ stderr: "invalid --so-dir: --hiperf is required\n",
1398
+ exitCode: 1
1399
+ });
1400
+ return;
1401
+ }
686
1402
  let hiprofilerRequest;
687
1403
  if (opts2.hiprofiler === true) {
688
1404
  try {
689
1405
  hiprofilerRequest = opts2.plugins === void 0 ? {} : { plugins: parsePluginList(opts2.plugins) };
690
1406
  } catch (err) {
691
- io.emit({ stdout: "", stderr: `${safeMessage(err)}
1407
+ io.emit({ stdout: "", stderr: `${failureLine(err)}
692
1408
  `, exitCode: 1 });
693
1409
  return;
694
1410
  }
@@ -710,8 +1426,12 @@ function buildProgram(deps2, io, opts = {}) {
710
1426
  ...opts2.coldStart !== void 0 ? { coldStart: opts2.coldStart } : {},
711
1427
  ...hiprofilerRequest === void 0 ? {} : { hiprofiler: hiprofilerRequest },
712
1428
  ...opts2.hiperf === true ? { hiperf: {} } : {},
1429
+ ...opts2.soDir === void 0 ? {} : { soDir: opts2.soDir },
713
1430
  ...opts2.hidumper === true ? { hidumper: true } : {},
714
- ...opts2.uitest === true ? { uitest: true } : {}
1431
+ ...opts2.uitest === true ? { uitest: true } : {},
1432
+ ...opts2.screenshot === true ? { screenshot: true } : {},
1433
+ ...opts2.hilog === true ? { hilog: true } : {},
1434
+ ...opts2.target === void 0 ? {} : { target: opts2.target }
715
1435
  }, { json: opts2.json }));
716
1436
  });
717
1437
  program2.command("query").description("run one named drill-down query against a captured scene").argument("<scene-dir>", "directory containing trace.db / trace.htrace").argument("<name>", "named query; list them with `ohos-perf tools`").option("--app <packageName>", "app package name, overriding scene.json").option("--args <json>", "query arguments as a JSON object").option("--limit <n>", "maximum rows to return (default 100, max 1000)").option("--json", "print the result as JSON").action(async (sceneDir, name, opts2) => {
@@ -721,7 +1441,7 @@ function buildProgram(deps2, io, opts = {}) {
721
1441
  args = opts2.args === void 0 ? void 0 : parseQueryArgs(opts2.args);
722
1442
  limit = opts2.limit === void 0 ? void 0 : parseLimit(opts2.limit);
723
1443
  } catch (err) {
724
- io.emit({ stdout: "", stderr: `${safeMessage(err)}
1444
+ io.emit({ stdout: "", stderr: `${failureLine(err)}
725
1445
  `, exitCode: 1 });
726
1446
  return;
727
1447
  }
@@ -736,9 +1456,214 @@ function buildProgram(deps2, io, opts = {}) {
736
1456
  program2.command("compare").description("compare a current analysis against a baseline").argument("<baseline>", "scene directory or `analyze --json` file").argument("<current>", "scene directory or `analyze --json` file").option("--json", "print the comparison as JSON").action(async (baseline, current, opts2) => {
737
1457
  io.emit(await runCompare(deps2, { baseline, current }, { json: opts2.json }));
738
1458
  });
1459
+ program2.command("ui-compare").description("compare two captures by UI tree and screenshot").argument("<a>", "scene directory for side a").argument("<b>", "scene directory for side b").requiredOption("--out <dir>", "output directory for ui-diff.json/html and marked PNGs").option("--json", "print the comparison as JSON").action(async (a, b, opts2) => {
1460
+ io.emit(await runUiCompare(deps2, { a, b, outDir: opts2.out }, { json: opts2.json }));
1461
+ });
1462
+ program2.command("report").description("analyze a scene and write report.html, JSON, summary, CSV and XLSX").argument("<scene-dir>", "directory containing trace.db / trace.htrace").requiredOption("--out <dir>", "output directory for the report artifacts").option("--app <packageName>", "app package name, for evidence wording").option("--baseline <input>", "scene directory or `analyze --json` file to compare against").option("--json", "print the artifact manifest as JSON").action(
1463
+ async (sceneDir, opts2) => {
1464
+ io.emit(
1465
+ await runReport(
1466
+ deps2,
1467
+ {
1468
+ sceneDir,
1469
+ outDir: opts2.out,
1470
+ ...opts2.app === void 0 ? {} : { app: opts2.app },
1471
+ ...opts2.baseline === void 0 ? {} : { baseline: opts2.baseline }
1472
+ },
1473
+ { json: opts2.json }
1474
+ )
1475
+ );
1476
+ }
1477
+ );
1478
+ program2.command("hap").description("inspect a .hap/.hsp package offline: files, sizes, technologies, duplicates").argument("<package>", "path to a .hap, .hsp or .zip file").option("--out <dir>", "write hap.json and hap.html to this directory").option("--json", "print the analysis as JSON").action(async (packagePath, opts2) => {
1479
+ io.emit(
1480
+ await runHap(
1481
+ deps2,
1482
+ {
1483
+ packagePath,
1484
+ ...opts2.out === void 0 ? {} : { outDir: opts2.out }
1485
+ },
1486
+ { json: opts2.json }
1487
+ )
1488
+ );
1489
+ });
1490
+ program2.command("run").description("run a declarative scenario, capturing one scene per step").argument("[scenario]", "scenario JSON file (omit when using --cases)").requiredOption("--out <dir>", "run output directory (one scene per step)").option("--cases <dir>", "run every *.scenario.json in this directory as one suite").option("--filter <regex>", "anchored regex over case ids; only with --cases").option("--target <id>", "run against this hdc target instead of the first connected one").option("--rounds <n>", "repeat every step this many times (overrides the scenario)").option("--only <ids>", "comma-separated step ids to run, in scenario order").option("--keep-going", "continue after a failed step instead of stopping").option("--json", "print the run result as JSON").action(async (scenarioPath, opts2) => {
1491
+ let rounds;
1492
+ let only;
1493
+ try {
1494
+ if (opts2.rounds !== void 0) {
1495
+ if (!/^[1-9]\d*$/.test(opts2.rounds)) {
1496
+ throw new Error(
1497
+ `invalid --rounds ${JSON.stringify(opts2.rounds)}: expected a positive whole number`
1498
+ );
1499
+ }
1500
+ rounds = Number(opts2.rounds);
1501
+ }
1502
+ only = opts2.only === void 0 ? void 0 : parseOnly(opts2.only);
1503
+ } catch (err) {
1504
+ io.emit({ stdout: "", stderr: `${failureLine(err)}
1505
+ `, exitCode: 1 });
1506
+ return;
1507
+ }
1508
+ io.emit(await runScenarioCommand(deps2, {
1509
+ scenarioPath: scenarioPath ?? "",
1510
+ outDir: opts2.out,
1511
+ ...opts2.cases === void 0 ? {} : { casesDir: opts2.cases },
1512
+ ...opts2.filter === void 0 ? {} : { filter: opts2.filter },
1513
+ ...opts2.target === void 0 ? {} : { target: opts2.target },
1514
+ ...rounds === void 0 ? {} : { rounds },
1515
+ ...only === void 0 ? {} : { only },
1516
+ ...opts2.keepGoing === true ? { keepGoing: true } : {}
1517
+ }, { json: opts2.json }));
1518
+ });
739
1519
  program2.command("tools").description("list the named drill-down queries an agent can call").option("--json", "print the query definitions as JSON").action((opts2) => {
740
1520
  io.emit(runTools(deps2, opts2));
741
1521
  });
1522
+ const withEmulatorTargets = (cmd) => cmd.option("--instance-path <dir>", "emulator instance root (overrides discovery)").option("--image-root <dir>", "emulator image root (overrides discovery)").option("--emulator <path>", "path to the HarmonyOS Emulator executable");
1523
+ const emulator = program2.command("emulator").description("manage HarmonyOS emulator instances");
1524
+ withEmulatorTargets(
1525
+ emulator.command("list").description("list emulator instances and the target each one owns").option("--json", "print the instances as JSON")
1526
+ ).action(async (opts2) => {
1527
+ io.emit(await runEmulatorList(deps2, {
1528
+ ...targetOptionsOf(opts2),
1529
+ ...opts2.json === void 0 ? {} : { json: opts2.json }
1530
+ }));
1531
+ });
1532
+ withEmulatorTargets(
1533
+ emulator.command("start").description("start an emulator instance and wait until it has booted").argument("<name>", "emulator instance name").option("--timeout <seconds>", "how long to wait for the boot, in seconds").option("--json", "print the result as JSON")
1534
+ ).action(async (name, opts2) => {
1535
+ const { timeout, json: json2 } = opts2;
1536
+ let timeoutMs;
1537
+ if (timeout !== void 0) {
1538
+ try {
1539
+ timeoutMs = parseDurationSeconds(timeout);
1540
+ } catch (err) {
1541
+ const reason = safeMessage(err).replace(/^invalid --duration [^:]*: /, "");
1542
+ const message2 = reason.startsWith("expected a positive number of seconds") ? "--timeout must be greater than 0 (a positive number of seconds, e.g. 30)" : reason;
1543
+ io.emit({
1544
+ stdout: "",
1545
+ stderr: `invalid --timeout ${JSON.stringify(timeout)}: ${message2}
1546
+ `,
1547
+ exitCode: 1
1548
+ });
1549
+ return;
1550
+ }
1551
+ }
1552
+ io.emit(await runEmulatorStart(deps2, name, {
1553
+ ...targetOptionsOf(opts2),
1554
+ ...timeoutMs === void 0 ? {} : { timeoutMs },
1555
+ ...json2 === void 0 ? {} : { json: json2 }
1556
+ }));
1557
+ });
1558
+ withEmulatorTargets(
1559
+ emulator.command("stop").description("stop an emulator instance").argument("<name>", "emulator instance name").option("--json", "print the result as JSON")
1560
+ ).action(async (name, opts2) => {
1561
+ io.emit(await runEmulatorStop(deps2, name, {
1562
+ ...targetOptionsOf(opts2),
1563
+ ...opts2.json === void 0 ? {} : { json: opts2.json }
1564
+ }));
1565
+ });
1566
+ withEmulatorTargets(
1567
+ emulator.command("create").description("create an emulator instance from an already-downloaded image").argument("<name>", "instance name; it becomes a directory under the instance root").option("--device-type <type>", "image device type, e.g. phone or foldable").option("--os-version <version>", 'image OS version, e.g. "HarmonyOS 6.1.1(24)"').option("--screen-profile <model>", "screen profile name").option("--memory <GB>", "RAM size in GB").option("--storage <GB>", "data partition size in GB").option("--json", "print the created instance as JSON")
1568
+ ).action(async (name, opts2) => {
1569
+ if (opts2.deviceType === void 0 || opts2.osVersion === void 0) {
1570
+ io.emit({
1571
+ stdout: "",
1572
+ stderr: "--device-type and --os-version are required\n",
1573
+ exitCode: 1
1574
+ });
1575
+ return;
1576
+ }
1577
+ const number = (flag, raw) => {
1578
+ if (raw === void 0) return void 0;
1579
+ const value = Number(raw);
1580
+ if (!Number.isInteger(value)) {
1581
+ throw new Error(`invalid ${flag}: expected a whole number, got ${JSON.stringify(raw)}`);
1582
+ }
1583
+ return value;
1584
+ };
1585
+ let memoryGb;
1586
+ let storageGb;
1587
+ try {
1588
+ memoryGb = number("--memory", opts2.memory);
1589
+ storageGb = number("--storage", opts2.storage);
1590
+ } catch (err) {
1591
+ io.emit({ stdout: "", stderr: `${failureLine(err)}
1592
+ `, exitCode: 1 });
1593
+ return;
1594
+ }
1595
+ io.emit(await runEmulatorCreate(deps2, {
1596
+ name,
1597
+ deviceType: opts2.deviceType,
1598
+ osVersion: opts2.osVersion,
1599
+ ...opts2.screenProfile === void 0 ? {} : { screenProfile: opts2.screenProfile },
1600
+ ...memoryGb === void 0 ? {} : { memoryGb },
1601
+ ...storageGb === void 0 ? {} : { storageGb },
1602
+ ...targetOptionsOf(opts2)
1603
+ }, { json: opts2.json }));
1604
+ });
1605
+ const gestureGroup = program2.command("gesture").description("inject a UI gesture on the attached device");
1606
+ const withGestureTargets = (cmd) => cmd.option("--target <id>", "inject on this hdc target instead of the first connected one").option("--json", "print the result as JSON");
1607
+ const sendGesture = async (build, opts2) => {
1608
+ let gesture;
1609
+ try {
1610
+ gesture = build();
1611
+ } catch (err) {
1612
+ io.emit({ stdout: "", stderr: `${failureLine(err)}
1613
+ `, exitCode: 1 });
1614
+ return;
1615
+ }
1616
+ io.emit(await runGesture(deps2, {
1617
+ gesture,
1618
+ ...opts2.target === void 0 ? {} : { target: opts2.target }
1619
+ }, { json: opts2.json }));
1620
+ };
1621
+ withGestureTargets(
1622
+ gestureGroup.command("click").description("tap at <x>,<y>").argument("<x>").argument("<y>")
1623
+ ).action(async (x, y, opts2) => {
1624
+ await sendGesture(
1625
+ () => ({ action: "click", x: parseCoordinate(x, "<x>"), y: parseCoordinate(y, "<y>") }),
1626
+ opts2
1627
+ );
1628
+ });
1629
+ withGestureTargets(
1630
+ gestureGroup.command("swipe").description("swipe from <from-x>,<from-y> to <to-x>,<to-y>").argument("<from-x>").argument("<from-y>").argument("<to-x>").argument("<to-y>").option("--velocity <n>", "swipe velocity, 200 to 40000 (device default 600)")
1631
+ ).action(async (fromX, fromY, toX, toY, opts2) => {
1632
+ await sendGesture(
1633
+ () => ({
1634
+ action: "swipe",
1635
+ fromX: parseCoordinate(fromX, "<from-x>"),
1636
+ fromY: parseCoordinate(fromY, "<from-y>"),
1637
+ toX: parseCoordinate(toX, "<to-x>"),
1638
+ toY: parseCoordinate(toY, "<to-y>"),
1639
+ ...opts2.velocity === void 0 ? {} : { velocity: parseVelocity(opts2.velocity) }
1640
+ }),
1641
+ opts2
1642
+ );
1643
+ });
1644
+ withGestureTargets(
1645
+ gestureGroup.command("key").description("inject a key event").argument("<key>", "Back, Home, Power or a positive key code")
1646
+ ).action(async (key, opts2) => {
1647
+ await sendGesture(() => ({ action: "key", key: parseKey(key) }), opts2);
1648
+ });
1649
+ withGestureTargets(
1650
+ gestureGroup.command("input").description("type text at <x>,<y>").argument("<x>").argument("<y>").argument("<text>", "text to type; quote it when it contains spaces")
1651
+ ).action(async (x, y, text, opts2) => {
1652
+ await sendGesture(
1653
+ () => ({
1654
+ action: "inputText",
1655
+ x: parseCoordinate(x, "<x>"),
1656
+ y: parseCoordinate(y, "<y>"),
1657
+ text: parseText(text)
1658
+ }),
1659
+ opts2
1660
+ );
1661
+ });
1662
+ withGestureTargets(
1663
+ gestureGroup.command("text").description("type text at the focused field").argument("<text>", "text to type; quote it when it contains spaces")
1664
+ ).action(async (text, opts2) => {
1665
+ await sendGesture(() => ({ action: "text", text: parseText(text) }), opts2);
1666
+ });
742
1667
  return program2;
743
1668
  }
744
1669
 
@@ -756,7 +1681,7 @@ function emit(result) {
756
1681
  function ignoreEpipe(stream) {
757
1682
  stream.on("error", (err) => {
758
1683
  if (err.code === "EPIPE") return;
759
- process.stderr.write(`${safeMessage(err)}
1684
+ process.stderr.write(`${failureLine(err)}
760
1685
  `);
761
1686
  process.exitCode = 1;
762
1687
  });
@@ -769,7 +1694,7 @@ var program = buildProgram(deps, {
769
1694
  emit
770
1695
  });
771
1696
  program.parseAsync(process.argv).catch((err) => {
772
- process.stderr.write(`${safeMessage(err)}
1697
+ process.stderr.write(`${failureLine(err)}
773
1698
  `);
774
1699
  process.exitCode = 1;
775
1700
  });