@veolab/discoverylab 0.1.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 (47) hide show
  1. package/.claude-plugin/marketplace.json +15 -0
  2. package/.claude-plugin/plugin.json +12 -0
  3. package/.mcp.json +6 -0
  4. package/README.md +214 -0
  5. package/assets/applab-discovery.jpeg +0 -0
  6. package/assets/backgrounds/abstract-colorful-gradient-orange-background.jpg +0 -0
  7. package/assets/backgrounds/blurred-colorful-luxury-gradient-rainbow-abstract.jpg +0 -0
  8. package/assets/backgrounds/glowing-neon-moving-continuously-looking-bright.jpg +0 -0
  9. package/assets/backgrounds/glowing-neon-moving-continuously-looking-bright2.jpg +0 -0
  10. package/assets/backgrounds/macos-big-sur-apple-layers-fluidic-colorful-wwdc-stock-4096x2304-1455.jpg +0 -0
  11. package/assets/backgrounds/macos-sierra-mountain-peak-sunset-evening-stock-5k-5120x3684-3987.jpg +0 -0
  12. package/assets/backgrounds/macos-tahoe-26-5120x2880-22674.jpg +0 -0
  13. package/assets/backgrounds/macos-tahoe-26-5120x2880-22675.jpg +0 -0
  14. package/assets/backgrounds/view-of-the-sea-from-the-window-of-an-airplane-2024-10-21-11-25-30-utc.jpg +0 -0
  15. package/assets/cursor/cursor-blue.png +0 -0
  16. package/assets/icons/android-head_3D.png +0 -0
  17. package/assets/icons/apple-logo.png +0 -0
  18. package/assets/icons/apple-logo.svg +4 -0
  19. package/assets/icons/claude-ai-icon.svg +1 -0
  20. package/assets/icons/icons8-apple-intelligence-48.png +0 -0
  21. package/assets/icons/icons8-apple-intelligence-96.png +0 -0
  22. package/dist/chunk-7IDQLLBW.js +311 -0
  23. package/dist/chunk-MLKGABMK.js +9 -0
  24. package/dist/chunk-MN6LCZHZ.js +1320 -0
  25. package/dist/chunk-PBHUHSC3.js +6002 -0
  26. package/dist/chunk-QJXXHOV7.js +205 -0
  27. package/dist/chunk-SSRXIO2V.js +6822 -0
  28. package/dist/chunk-VY3BLXBW.js +329 -0
  29. package/dist/chunk-W3WJGYR6.js +354 -0
  30. package/dist/cli.d.ts +1 -0
  31. package/dist/cli.js +120 -0
  32. package/dist/db-IWIL65EX.js +33 -0
  33. package/dist/gridCompositor-ENKLFPWR.js +409 -0
  34. package/dist/index.d.ts +1648 -0
  35. package/dist/index.js +869 -0
  36. package/dist/ocr-UTWC7537.js +21 -0
  37. package/dist/server-3FBHBA7L.js +15 -0
  38. package/dist/server-NM5CKDUU.js +13 -0
  39. package/dist/setup-27CQAX6K.js +17 -0
  40. package/dist/tools-75BAPCUM.js +177 -0
  41. package/package.json +84 -0
  42. package/skills/generate-assets/SKILL.md +44 -0
  43. package/skills/mobile-test/SKILL.md +33 -0
  44. package/skills/open-ui/SKILL.md +24 -0
  45. package/skills/quick-capture/SKILL.md +28 -0
  46. package/skills/task-hub/SKILL.md +44 -0
  47. package/skills/web-test/SKILL.md +41 -0
@@ -0,0 +1,1320 @@
1
+ import {
2
+ PROJECTS_DIR
3
+ } from "./chunk-VY3BLXBW.js";
4
+
5
+ // src/core/testing/maestro.ts
6
+ import { exec, execSync, spawn } from "child_process";
7
+ import { promisify } from "util";
8
+ import * as fs from "fs";
9
+ import * as path from "path";
10
+ import * as os from "os";
11
+ import { createHash } from "crypto";
12
+ import { EventEmitter } from "events";
13
+ var execAsync = promisify(exec);
14
+ function quoteCommand(cmd) {
15
+ return cmd.includes(" ") ? `"${cmd}"` : cmd;
16
+ }
17
+ function getMaestroCommandCandidates() {
18
+ const candidates = [];
19
+ const maestroHomePath = path.join(os.homedir(), ".maestro", "bin", "maestro");
20
+ if (fs.existsSync(maestroHomePath)) {
21
+ candidates.push(maestroHomePath);
22
+ }
23
+ const brewPaths = ["/opt/homebrew/bin/maestro", "/usr/local/bin/maestro"];
24
+ for (const brewPath of brewPaths) {
25
+ if (fs.existsSync(brewPath)) {
26
+ candidates.push(brewPath);
27
+ }
28
+ }
29
+ candidates.push("maestro");
30
+ return candidates;
31
+ }
32
+ async function resolveMaestroCommand() {
33
+ for (const candidate of getMaestroCommandCandidates()) {
34
+ try {
35
+ const cmd = quoteCommand(candidate);
36
+ await execAsync(`${cmd} --version`);
37
+ return candidate;
38
+ } catch {
39
+ }
40
+ }
41
+ return null;
42
+ }
43
+ var PENDING_SESSION_FILE = path.join(PROJECTS_DIR, ".maestro-pending-session.json");
44
+ async function isMaestroInstalled() {
45
+ try {
46
+ return !!await resolveMaestroCommand();
47
+ } catch {
48
+ return false;
49
+ }
50
+ }
51
+ async function isIdbInstalled() {
52
+ try {
53
+ await execAsync("idb --version", { timeout: 3e3 });
54
+ return true;
55
+ } catch {
56
+ return false;
57
+ }
58
+ }
59
+ async function tapViaIdb(deviceId, x, y) {
60
+ try {
61
+ await execAsync(`idb ui tap ${Math.round(x)} ${Math.round(y)} --udid ${deviceId}`, {
62
+ timeout: 5e3
63
+ });
64
+ return true;
65
+ } catch (error) {
66
+ console.error("[idb tap failed]", error instanceof Error ? error.message : error);
67
+ return false;
68
+ }
69
+ }
70
+ async function killZombieMaestroProcesses() {
71
+ try {
72
+ await execAsync('pkill -f "maestro test" || true', { timeout: 3e3 });
73
+ await execAsync('pkill -f "maestro record" || true', { timeout: 3e3 });
74
+ console.log("[MaestroCleanup] Killed zombie maestro processes");
75
+ } catch {
76
+ }
77
+ }
78
+ async function getMaestroVersion() {
79
+ try {
80
+ const command = await resolveMaestroCommand();
81
+ if (!command) return null;
82
+ const cmd = quoteCommand(command);
83
+ const { stdout } = await execAsync(`${cmd} --version`);
84
+ return stdout.trim();
85
+ } catch {
86
+ return null;
87
+ }
88
+ }
89
+ async function listMaestroDevices() {
90
+ const devices = [];
91
+ try {
92
+ const { stdout: iosOutput } = await execAsync("xcrun simctl list devices -j");
93
+ const iosData = JSON.parse(iosOutput);
94
+ for (const [runtime, deviceList] of Object.entries(iosData.devices || {})) {
95
+ if (!Array.isArray(deviceList)) continue;
96
+ for (const device of deviceList) {
97
+ if (device.state === "Booted") {
98
+ devices.push({
99
+ id: device.udid,
100
+ name: device.name,
101
+ platform: "ios",
102
+ status: "connected"
103
+ });
104
+ }
105
+ }
106
+ }
107
+ } catch {
108
+ }
109
+ try {
110
+ const { stdout: androidOutput } = await execAsync("adb devices -l");
111
+ const lines = androidOutput.split("\n").slice(1);
112
+ for (const line of lines) {
113
+ const match = line.match(/^(\S+)\s+device\s+(.*)$/);
114
+ if (match) {
115
+ const [, id, info] = match;
116
+ const modelMatch = info.match(/model:(\S+)/);
117
+ devices.push({
118
+ id,
119
+ name: modelMatch ? modelMatch[1] : id,
120
+ platform: "android",
121
+ status: "connected"
122
+ });
123
+ }
124
+ }
125
+ } catch {
126
+ }
127
+ return devices;
128
+ }
129
+ function generateMaestroFlow(flow) {
130
+ const lines = [];
131
+ lines.push(`appId: ${flow.appId}`);
132
+ lines.push("");
133
+ if (flow.name) {
134
+ lines.push(`name: ${flow.name}`);
135
+ lines.push("");
136
+ }
137
+ if (flow.env && Object.keys(flow.env).length > 0) {
138
+ lines.push("env:");
139
+ for (const [key, value] of Object.entries(flow.env)) {
140
+ lines.push(` ${key}: "${value}"`);
141
+ }
142
+ lines.push("");
143
+ }
144
+ if (flow.onFlowStart && flow.onFlowStart.length > 0) {
145
+ lines.push("onFlowStart:");
146
+ for (const step of flow.onFlowStart) {
147
+ lines.push(formatFlowStep(step, 2));
148
+ }
149
+ lines.push("");
150
+ }
151
+ if (flow.onFlowComplete && flow.onFlowComplete.length > 0) {
152
+ lines.push("onFlowComplete:");
153
+ for (const step of flow.onFlowComplete) {
154
+ lines.push(formatFlowStep(step, 2));
155
+ }
156
+ lines.push("");
157
+ }
158
+ lines.push("---");
159
+ for (const step of flow.steps) {
160
+ lines.push(formatFlowStep(step, 0));
161
+ }
162
+ return lines.join("\n");
163
+ }
164
+ function formatFlowStep(step, indent) {
165
+ const prefix = " ".repeat(indent);
166
+ const { action, params } = step;
167
+ if (!params || Object.keys(params).length === 0) {
168
+ return `${prefix}- ${action}`;
169
+ }
170
+ if (Object.keys(params).length === 1) {
171
+ const [key, value] = Object.entries(params)[0];
172
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
173
+ return `${prefix}- ${action}:
174
+ ${prefix} ${key}: ${formatValue(value)}`;
175
+ }
176
+ }
177
+ const lines = [`${prefix}- ${action}:`];
178
+ for (const [key, value] of Object.entries(params)) {
179
+ lines.push(`${prefix} ${key}: ${formatValue(value)}`);
180
+ }
181
+ return lines.join("\n");
182
+ }
183
+ function formatValue(value) {
184
+ if (typeof value === "string") {
185
+ return value.includes("\n") || value.includes(":") ? `"${value}"` : value;
186
+ }
187
+ return String(value);
188
+ }
189
+ var MaestroActions = {
190
+ // App lifecycle
191
+ launchApp: (appId) => ({ action: "launchApp", params: appId ? { appId } : void 0 }),
192
+ stopApp: (appId) => ({ action: "stopApp", params: appId ? { appId } : void 0 }),
193
+ clearState: (appId) => ({ action: "clearState", params: appId ? { appId } : void 0 }),
194
+ clearKeychain: () => ({ action: "clearKeychain" }),
195
+ // Navigation
196
+ tapOn: (text) => ({ action: "tapOn", params: { text } }),
197
+ tapOnId: (id) => ({ action: "tapOn", params: { id } }),
198
+ tapOnPoint: (x, y) => ({ action: "tapOn", params: { point: `${x},${y}` } }),
199
+ doubleTapOn: (text) => ({ action: "doubleTapOn", params: { text } }),
200
+ longPressOn: (text) => ({ action: "longPressOn", params: { text } }),
201
+ // Input
202
+ inputText: (text) => ({ action: "inputText", params: { text } }),
203
+ inputRandomText: () => ({ action: "inputRandomText" }),
204
+ inputRandomNumber: () => ({ action: "inputRandomNumber" }),
205
+ inputRandomEmail: () => ({ action: "inputRandomEmail" }),
206
+ eraseText: (chars) => ({ action: "eraseText", params: chars ? { charactersToErase: chars } : void 0 }),
207
+ // Gestures
208
+ scroll: () => ({ action: "scroll" }),
209
+ scrollDown: () => ({ action: "scrollUntilVisible", params: { direction: "DOWN" } }),
210
+ scrollUp: () => ({ action: "scrollUntilVisible", params: { direction: "UP" } }),
211
+ swipeLeft: () => ({ action: "swipe", params: { direction: "LEFT" } }),
212
+ swipeRight: () => ({ action: "swipe", params: { direction: "RIGHT" } }),
213
+ swipeDown: () => ({ action: "swipe", params: { direction: "DOWN" } }),
214
+ swipeUp: () => ({ action: "swipe", params: { direction: "UP" } }),
215
+ // Assertions
216
+ assertVisible: (text) => ({ action: "assertVisible", params: { text } }),
217
+ assertNotVisible: (text) => ({ action: "assertNotVisible", params: { text } }),
218
+ assertTrue: (condition) => ({ action: "assertTrue", params: { condition } }),
219
+ // Wait
220
+ waitForAnimationToEnd: (timeout) => ({
221
+ action: "waitForAnimationToEnd",
222
+ params: timeout ? { timeout } : void 0
223
+ }),
224
+ wait: (ms) => ({ action: "extendedWaitUntil", params: { timeout: ms } }),
225
+ // Screenshots
226
+ takeScreenshot: (path2) => ({ action: "takeScreenshot", params: { path: path2 } }),
227
+ // Keyboard
228
+ hideKeyboard: () => ({ action: "hideKeyboard" }),
229
+ pressKey: (key) => ({ action: "pressKey", params: { key } }),
230
+ back: () => ({ action: "back" }),
231
+ // Conditional
232
+ runFlow: (flowPath) => ({ action: "runFlow", params: { file: flowPath } }),
233
+ runScript: (script) => ({ action: "runScript", params: { script } }),
234
+ // Device
235
+ openLink: (url) => ({ action: "openLink", params: { link: url } }),
236
+ setLocation: (lat, lon) => ({ action: "setLocation", params: { latitude: lat, longitude: lon } }),
237
+ travel: (steps) => ({ action: "travel", params: { points: steps } })
238
+ };
239
+ async function runMaestroTest(options) {
240
+ const installed = await isMaestroInstalled();
241
+ if (!installed) {
242
+ return {
243
+ success: false,
244
+ error: 'Maestro CLI is not installed. Install with: curl -Ls "https://get.maestro.mobile.dev" | bash'
245
+ };
246
+ }
247
+ const {
248
+ flowPath,
249
+ appId,
250
+ device,
251
+ env = {},
252
+ timeout = 3e5,
253
+ // 5 minutes default
254
+ captureVideo = false,
255
+ captureScreenshots = false,
256
+ outputDir = path.join(PROJECTS_DIR, "maestro-output", Date.now().toString())
257
+ } = options;
258
+ const command = await resolveMaestroCommand();
259
+ if (!command) {
260
+ return {
261
+ success: false,
262
+ error: 'Maestro CLI is not installed or not runnable. Install with: curl -Ls "https://get.maestro.mobile.dev" | bash'
263
+ };
264
+ }
265
+ if (!fs.existsSync(flowPath)) {
266
+ return { success: false, error: `Flow file not found: ${flowPath}` };
267
+ }
268
+ await fs.promises.mkdir(outputDir, { recursive: true });
269
+ const startTime = Date.now();
270
+ const args = ["test", flowPath];
271
+ const maestroCmd = quoteCommand(command);
272
+ if (device) {
273
+ args.push("--device", device);
274
+ }
275
+ for (const [key, value] of Object.entries(env)) {
276
+ args.push("-e", `${key}=${value}`);
277
+ }
278
+ args.push("--format", "junit");
279
+ args.push("--output", path.join(outputDir, "report.xml"));
280
+ try {
281
+ const { stdout, stderr } = await execAsync(`${maestroCmd} ${args.join(" ")}`, {
282
+ timeout,
283
+ env: { ...process.env, ...env }
284
+ });
285
+ const duration = Date.now() - startTime;
286
+ const screenshots = [];
287
+ const videoPath = captureVideo ? path.join(outputDir, "recording.mp4") : void 0;
288
+ if (captureScreenshots) {
289
+ const files = await fs.promises.readdir(outputDir);
290
+ for (const file of files) {
291
+ if (file.endsWith(".png")) {
292
+ screenshots.push(path.join(outputDir, file));
293
+ }
294
+ }
295
+ }
296
+ return {
297
+ success: true,
298
+ duration,
299
+ flowPath,
300
+ output: stdout + stderr,
301
+ screenshots,
302
+ video: videoPath
303
+ };
304
+ } catch (error) {
305
+ const duration = Date.now() - startTime;
306
+ const message = error instanceof Error ? error.message : String(error);
307
+ return {
308
+ success: false,
309
+ error: message,
310
+ duration,
311
+ flowPath,
312
+ output: message
313
+ };
314
+ }
315
+ }
316
+ async function runMaestroWithCapture(options, onProgress) {
317
+ const {
318
+ flowPath,
319
+ device,
320
+ outputDir = path.join(PROJECTS_DIR, "maestro-output", Date.now().toString())
321
+ } = options;
322
+ await fs.promises.mkdir(outputDir, { recursive: true });
323
+ const videoPath = path.join(outputDir, "recording.mp4");
324
+ let recordingProcess = null;
325
+ try {
326
+ onProgress?.("Starting screen recording...");
327
+ if (device) {
328
+ const devices = await listMaestroDevices();
329
+ const targetDevice = devices.find((d) => d.id === device || d.name === device);
330
+ if (targetDevice?.platform === "ios") {
331
+ recordingProcess = spawn("xcrun", ["simctl", "io", device, "recordVideo", videoPath]);
332
+ } else if (targetDevice?.platform === "android") {
333
+ recordingProcess = spawn("adb", ["-s", device, "shell", "screenrecord", "/sdcard/recording.mp4"]);
334
+ }
335
+ }
336
+ onProgress?.("Running Maestro test...");
337
+ const result = await runMaestroTest({ ...options, outputDir });
338
+ onProgress?.("Stopping screen recording...");
339
+ if (recordingProcess) {
340
+ recordingProcess.kill("SIGINT");
341
+ await new Promise((resolve) => setTimeout(resolve, 2e3));
342
+ const devices = await listMaestroDevices();
343
+ const targetDevice = devices.find((d) => d.id === device || d.name === device);
344
+ if (targetDevice?.platform === "android") {
345
+ await execAsync(`adb -s ${device} pull /sdcard/recording.mp4 "${videoPath}"`);
346
+ await execAsync(`adb -s ${device} shell rm /sdcard/recording.mp4`);
347
+ }
348
+ }
349
+ return {
350
+ ...result,
351
+ video: fs.existsSync(videoPath) ? videoPath : void 0
352
+ };
353
+ } catch (error) {
354
+ if (recordingProcess) {
355
+ recordingProcess.kill("SIGKILL");
356
+ }
357
+ return {
358
+ success: false,
359
+ error: error instanceof Error ? error.message : String(error),
360
+ flowPath
361
+ };
362
+ }
363
+ }
364
+ async function startMaestroStudio(appId) {
365
+ const installed = await isMaestroInstalled();
366
+ if (!installed) {
367
+ return {
368
+ success: false,
369
+ error: "Maestro CLI is not installed"
370
+ };
371
+ }
372
+ try {
373
+ const args = ["studio"];
374
+ if (appId) {
375
+ args.push(appId);
376
+ }
377
+ const maestroCmd = await resolveMaestroCommand();
378
+ if (!maestroCmd) {
379
+ return { success: false, error: "Maestro CLI is not installed or not runnable" };
380
+ }
381
+ spawn(maestroCmd, args, {
382
+ detached: true,
383
+ stdio: "ignore"
384
+ }).unref();
385
+ return { success: true };
386
+ } catch (error) {
387
+ return {
388
+ success: false,
389
+ error: error instanceof Error ? error.message : String(error)
390
+ };
391
+ }
392
+ }
393
+ function createLoginFlow(appId, usernameField, passwordField, loginButton, successIndicator) {
394
+ return {
395
+ appId,
396
+ name: "Login Flow",
397
+ steps: [
398
+ MaestroActions.launchApp(appId),
399
+ MaestroActions.waitForAnimationToEnd(),
400
+ MaestroActions.tapOn(usernameField),
401
+ MaestroActions.inputText("${USERNAME}"),
402
+ MaestroActions.tapOn(passwordField),
403
+ MaestroActions.inputText("${PASSWORD}"),
404
+ MaestroActions.hideKeyboard(),
405
+ MaestroActions.tapOn(loginButton),
406
+ MaestroActions.waitForAnimationToEnd(5e3),
407
+ MaestroActions.assertVisible(successIndicator)
408
+ ]
409
+ };
410
+ }
411
+ function createOnboardingFlow(appId, screens) {
412
+ const steps = [
413
+ MaestroActions.launchApp(appId),
414
+ MaestroActions.waitForAnimationToEnd()
415
+ ];
416
+ for (const screen of screens) {
417
+ if (screen.waitFor) {
418
+ steps.push(MaestroActions.assertVisible(screen.waitFor));
419
+ }
420
+ steps.push(MaestroActions.tapOn(screen.nextButton));
421
+ steps.push(MaestroActions.waitForAnimationToEnd());
422
+ }
423
+ return {
424
+ appId,
425
+ name: "Onboarding Flow",
426
+ steps
427
+ };
428
+ }
429
+ function createNavigationTestFlow(appId, tabs) {
430
+ const steps = [
431
+ MaestroActions.launchApp(appId),
432
+ MaestroActions.waitForAnimationToEnd()
433
+ ];
434
+ for (const tab of tabs) {
435
+ steps.push(MaestroActions.tapOn(tab));
436
+ steps.push(MaestroActions.waitForAnimationToEnd());
437
+ steps.push(MaestroActions.takeScreenshot(`${tab.replace(/\s+/g, "_")}.png`));
438
+ }
439
+ return {
440
+ appId,
441
+ name: "Navigation Test",
442
+ steps
443
+ };
444
+ }
445
+ var MaestroRecorder = class extends EventEmitter {
446
+ session = null;
447
+ adbProcess = null;
448
+ videoProcess = null;
449
+ maestroRecordProcess = null;
450
+ // Native maestro record process
451
+ actionCounter = 0;
452
+ screenshotInterval = null;
453
+ useNativeMaestroRecord = true;
454
+ // Use native maestro record for better accuracy
455
+ legacyCaptureStarted = false;
456
+ baseScreenshotIntervalMs = 2e3;
457
+ maxScreenshotIntervalMs = 12e3;
458
+ currentScreenshotIntervalMs = this.baseScreenshotIntervalMs;
459
+ nextScreenshotAt = 0;
460
+ lastScreenshotHash = null;
461
+ unchangedScreenshotCount = 0;
462
+ screenshotBackoffThreshold = 3;
463
+ constructor() {
464
+ super();
465
+ this.loadPendingSession();
466
+ }
467
+ /**
468
+ * Check if maestro is available in system PATH
469
+ */
470
+ isMaestroInPath() {
471
+ try {
472
+ execSync("which maestro", { encoding: "utf-8", timeout: 2e3 });
473
+ return true;
474
+ } catch {
475
+ return false;
476
+ }
477
+ }
478
+ canRunMaestro(cmd) {
479
+ try {
480
+ execSync(`"${cmd}" --version`, { encoding: "utf-8", timeout: 3e3 });
481
+ return true;
482
+ } catch {
483
+ return false;
484
+ }
485
+ }
486
+ startLegacyCapture(deviceId, platform) {
487
+ if (platform === "android") {
488
+ if (!this.adbProcess) {
489
+ this.startAndroidEventCapture(deviceId);
490
+ }
491
+ } else {
492
+ this.startIOSEventCapture(deviceId);
493
+ }
494
+ this.legacyCaptureStarted = true;
495
+ }
496
+ fallbackToLegacyCapture(reason) {
497
+ if (!this.session || this.session.status !== "recording") return;
498
+ if (this.legacyCaptureStarted) return;
499
+ console.log(`[MaestroRecorder] Native record stopped (${reason}). Falling back to manual capture.`);
500
+ this.session.captureMode = "manual";
501
+ this.startLegacyCapture(this.session.deviceId, this.session.platform);
502
+ }
503
+ /**
504
+ * Save session state to disk for recovery after server restart
505
+ */
506
+ savePendingSession() {
507
+ if (!this.session) return;
508
+ try {
509
+ fs.writeFileSync(PENDING_SESSION_FILE, JSON.stringify(this.session, null, 2));
510
+ } catch (error) {
511
+ console.error("[MaestroRecorder] Failed to save pending session:", error);
512
+ }
513
+ }
514
+ /**
515
+ * Load pending session from disk (after server restart)
516
+ */
517
+ loadPendingSession() {
518
+ try {
519
+ if (fs.existsSync(PENDING_SESSION_FILE)) {
520
+ const data = fs.readFileSync(PENDING_SESSION_FILE, "utf8");
521
+ const savedSession = JSON.parse(data);
522
+ if (savedSession.status === "recording") {
523
+ console.log("[MaestroRecorder] Restoring pending session from disk:", savedSession.id);
524
+ this.session = savedSession;
525
+ this.actionCounter = savedSession.actions.length;
526
+ }
527
+ }
528
+ } catch (error) {
529
+ console.error("[MaestroRecorder] Failed to load pending session:", error);
530
+ try {
531
+ fs.unlinkSync(PENDING_SESSION_FILE);
532
+ } catch {
533
+ }
534
+ }
535
+ }
536
+ /**
537
+ * Clear pending session file (after successful stop)
538
+ */
539
+ clearPendingSession() {
540
+ try {
541
+ if (fs.existsSync(PENDING_SESSION_FILE)) {
542
+ fs.unlinkSync(PENDING_SESSION_FILE);
543
+ }
544
+ } catch (error) {
545
+ console.error("[MaestroRecorder] Failed to clear pending session:", error);
546
+ }
547
+ }
548
+ /**
549
+ * Persist session metadata to session.json (available during recording)
550
+ */
551
+ async writeSessionMetadata() {
552
+ if (!this.session) return;
553
+ try {
554
+ const metadataPath = path.join(this.session.screenshotsDir, "..", "session.json");
555
+ await fs.promises.writeFile(metadataPath, JSON.stringify(this.session, null, 2));
556
+ } catch (error) {
557
+ console.error("[MaestroRecorder] Failed to write session metadata:", error);
558
+ }
559
+ }
560
+ /**
561
+ * Start recording a mobile session
562
+ */
563
+ async startRecording(name, deviceId, deviceName, platform, appId, options = {}) {
564
+ if (this.session?.status === "recording") {
565
+ const hasActiveProcesses = !!(this.videoProcess || this.maestroRecordProcess || this.adbProcess);
566
+ if (hasActiveProcesses) {
567
+ throw new Error("Recording already in progress");
568
+ }
569
+ console.log("[MaestroRecorder] Stale recording session detected. Clearing before starting a new one.");
570
+ this.session = null;
571
+ if (this.screenshotInterval) {
572
+ clearInterval(this.screenshotInterval);
573
+ this.screenshotInterval = null;
574
+ }
575
+ this.clearPendingSession();
576
+ }
577
+ const sessionId = `maestro_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
578
+ const baseDir = path.join(PROJECTS_DIR, "maestro-recordings", sessionId);
579
+ const screenshotsDir = path.join(baseDir, "screenshots");
580
+ await fs.promises.mkdir(screenshotsDir, { recursive: true });
581
+ this.session = {
582
+ id: sessionId,
583
+ name,
584
+ startedAt: Date.now(),
585
+ appId,
586
+ deviceId,
587
+ deviceName,
588
+ platform,
589
+ actions: [],
590
+ screenshotsDir,
591
+ status: "recording"
592
+ };
593
+ this.actionCounter = 0;
594
+ try {
595
+ const flowPath = path.join(baseDir, "test.yaml");
596
+ this.session.flowPath = flowPath;
597
+ const videoPath = path.join(baseDir, "recording.mp4");
598
+ this.session.videoPath = videoPath;
599
+ const maestroHomePath = path.join(os.homedir(), ".maestro", "bin", "maestro");
600
+ const maestroPath = fs.existsSync(maestroHomePath) ? maestroHomePath : "maestro";
601
+ const maestroExists = fs.existsSync(maestroHomePath) || this.isMaestroInPath();
602
+ const maestroRunnable = maestroExists && this.canRunMaestro(maestroPath);
603
+ const preferNativeRecord = options.preferNativeRecord !== false;
604
+ const useNativeRecord = preferNativeRecord && this.useNativeMaestroRecord && maestroRunnable;
605
+ if (!maestroRunnable && this.useNativeMaestroRecord) {
606
+ console.log("[MaestroRecorder] \u26A0\uFE0F Maestro CLI not available or not runnable. Falling back to screenshot-based capture.");
607
+ console.log('[MaestroRecorder] Ensure Java is installed or reinstall Maestro: curl -Ls "https://get.maestro.mobile.dev" | bash');
608
+ }
609
+ if (!preferNativeRecord) {
610
+ console.log("[MaestroRecorder] Native record disabled for this session (manual capture mode).");
611
+ }
612
+ let nativeRecordStarted = false;
613
+ this.legacyCaptureStarted = false;
614
+ if (useNativeRecord) {
615
+ console.log("[MaestroRecorder] Starting native maestro record...");
616
+ try {
617
+ this.maestroRecordProcess = spawn(maestroPath, ["record", flowPath], {
618
+ stdio: ["pipe", "pipe", "pipe"],
619
+ env: { ...process.env }
620
+ });
621
+ nativeRecordStarted = true;
622
+ this.maestroRecordProcess.stdout?.on("data", (data) => {
623
+ console.log("[MaestroRecord]", data.toString().trim());
624
+ });
625
+ this.maestroRecordProcess.stderr?.on("data", (data) => {
626
+ console.log("[MaestroRecord ERROR]", data.toString().trim());
627
+ });
628
+ this.maestroRecordProcess.on("error", (err) => {
629
+ console.log("[MaestroRecord] Spawn error:", err.message);
630
+ this.fallbackToLegacyCapture("spawn error");
631
+ this.maestroRecordProcess = null;
632
+ });
633
+ this.maestroRecordProcess.on("close", (code) => {
634
+ console.log(`[MaestroRecord] Process exited with code ${code}`);
635
+ this.fallbackToLegacyCapture(`exit code ${code}`);
636
+ this.maestroRecordProcess = null;
637
+ });
638
+ } catch (err) {
639
+ console.log("[MaestroRecorder] Failed to start native record, using legacy capture");
640
+ this.maestroRecordProcess = null;
641
+ nativeRecordStarted = false;
642
+ }
643
+ }
644
+ this.session.captureMode = nativeRecordStarted ? "native" : "manual";
645
+ if (!nativeRecordStarted && this.session.flowPath) {
646
+ try {
647
+ const initialYaml = this.generateFlowYaml();
648
+ await fs.promises.writeFile(this.session.flowPath, initialYaml);
649
+ } catch (error) {
650
+ console.error("[MaestroRecorder] Failed to write initial flow YAML:", error);
651
+ }
652
+ }
653
+ await this.writeSessionMetadata();
654
+ if (nativeRecordStarted) {
655
+ if (platform === "ios") {
656
+ this.videoProcess = spawn("xcrun", ["simctl", "io", deviceId, "recordVideo", videoPath]);
657
+ } else {
658
+ const tempVideoPath = "/sdcard/maestro-recording.mp4";
659
+ this.videoProcess = spawn("adb", ["-s", deviceId, "shell", "screenrecord", "--time-limit", "180", tempVideoPath]);
660
+ }
661
+ } else {
662
+ if (useNativeRecord) {
663
+ console.log("[MaestroRecorder] Native record failed to start, using legacy capture");
664
+ }
665
+ if (platform === "android") {
666
+ const tempVideoPath = "/sdcard/maestro-recording.mp4";
667
+ this.videoProcess = spawn("adb", ["-s", deviceId, "shell", "screenrecord", "--time-limit", "180", tempVideoPath]);
668
+ this.startLegacyCapture(deviceId, platform);
669
+ } else {
670
+ this.videoProcess = spawn("xcrun", ["simctl", "io", deviceId, "recordVideo", videoPath]);
671
+ this.startLegacyCapture(deviceId, platform);
672
+ }
673
+ }
674
+ this.currentScreenshotIntervalMs = this.baseScreenshotIntervalMs;
675
+ this.nextScreenshotAt = 0;
676
+ this.lastScreenshotHash = null;
677
+ this.unchangedScreenshotCount = 0;
678
+ this.screenshotInterval = setInterval(() => {
679
+ this.captureScreenshot(void 0, { reason: "periodic" });
680
+ }, 2e3);
681
+ this.savePendingSession();
682
+ this.emit("status", "recording");
683
+ return this.session;
684
+ } catch (error) {
685
+ this.session.status = "error";
686
+ this.clearPendingSession();
687
+ this.emit("error", error);
688
+ throw error;
689
+ }
690
+ }
691
+ /**
692
+ * Capture Android touch events via ADB
693
+ */
694
+ startAndroidEventCapture(deviceId) {
695
+ exec(`adb -s ${deviceId} shell wm size`, (err, stdout) => {
696
+ if (err) return;
697
+ const match = stdout.match(/(\d+)x(\d+)/);
698
+ const screenWidth = match ? parseInt(match[1]) : 1080;
699
+ const screenHeight = match ? parseInt(match[2]) : 1920;
700
+ this.adbProcess = spawn("adb", ["-s", deviceId, "shell", "getevent", "-lt"]);
701
+ let touchStartTime = 0;
702
+ let touchStartX = 0;
703
+ let touchStartY = 0;
704
+ let currentX = 0;
705
+ let currentY = 0;
706
+ let isTracking = false;
707
+ this.adbProcess.stdout?.on("data", (data) => {
708
+ const lines = data.toString().split("\n");
709
+ for (const line of lines) {
710
+ if (line.includes("ABS_MT_POSITION_X")) {
711
+ const match2 = line.match(/ABS_MT_POSITION_X\s+([0-9a-f]+)/i);
712
+ if (match2) {
713
+ currentX = Math.round(parseInt(match2[1], 16) / 32767 * screenWidth);
714
+ }
715
+ }
716
+ if (line.includes("ABS_MT_POSITION_Y")) {
717
+ const match2 = line.match(/ABS_MT_POSITION_Y\s+([0-9a-f]+)/i);
718
+ if (match2) {
719
+ currentY = Math.round(parseInt(match2[1], 16) / 32767 * screenHeight);
720
+ }
721
+ }
722
+ if (line.includes("BTN_TOUCH") && line.includes("DOWN")) {
723
+ touchStartTime = Date.now();
724
+ touchStartX = currentX;
725
+ touchStartY = currentY;
726
+ isTracking = true;
727
+ }
728
+ if (line.includes("BTN_TOUCH") && line.includes("UP") && isTracking) {
729
+ const duration = Date.now() - touchStartTime;
730
+ const deltaX = Math.abs(currentX - touchStartX);
731
+ const deltaY = Math.abs(currentY - touchStartY);
732
+ if (deltaX > 50 || deltaY > 50) {
733
+ this.recordAction({
734
+ type: "swipe",
735
+ x: touchStartX,
736
+ y: touchStartY,
737
+ endX: currentX,
738
+ endY: currentY,
739
+ duration,
740
+ description: `Swipe from (${touchStartX}, ${touchStartY}) to (${currentX}, ${currentY})`
741
+ });
742
+ } else if (duration > 500) {
743
+ this.recordAction({
744
+ type: "longPress",
745
+ x: touchStartX,
746
+ y: touchStartY,
747
+ duration,
748
+ description: `Long press at (${touchStartX}, ${touchStartY})`
749
+ });
750
+ } else {
751
+ this.recordAction({
752
+ type: "tap",
753
+ x: touchStartX,
754
+ y: touchStartY,
755
+ description: `Tap at (${touchStartX}, ${touchStartY})`
756
+ });
757
+ }
758
+ isTracking = false;
759
+ }
760
+ if (line.includes("KEY_BACK") && line.includes("DOWN")) {
761
+ this.recordAction({
762
+ type: "back",
763
+ description: "Press back button"
764
+ });
765
+ }
766
+ if (line.includes("KEY_HOME") && line.includes("DOWN")) {
767
+ this.recordAction({
768
+ type: "home",
769
+ description: "Press home button"
770
+ });
771
+ }
772
+ }
773
+ });
774
+ });
775
+ }
776
+ /**
777
+ * Capture iOS events (limited - mainly screenshots)
778
+ */
779
+ startIOSEventCapture(deviceId) {
780
+ console.log("[MaestroRecorder] iOS event capture started (screenshot-based)");
781
+ }
782
+ /**
783
+ * Record an action
784
+ */
785
+ async recordAction(actionData) {
786
+ if (!this.session || this.session.status !== "recording") return;
787
+ this.actionCounter++;
788
+ const actionId = `action_${this.actionCounter.toString().padStart(3, "0")}`;
789
+ const screenshotPath = await this.captureScreenshot(actionId, { force: true, reason: "action" });
790
+ const action = {
791
+ id: actionId,
792
+ type: actionData.type || "tap",
793
+ timestamp: Date.now(),
794
+ x: actionData.x,
795
+ y: actionData.y,
796
+ endX: actionData.endX,
797
+ endY: actionData.endY,
798
+ text: actionData.text,
799
+ direction: actionData.direction,
800
+ seconds: actionData.seconds,
801
+ appId: actionData.appId,
802
+ duration: actionData.duration,
803
+ description: actionData.description || actionData.type || "Action",
804
+ screenshotPath
805
+ };
806
+ this.session.actions.push(action);
807
+ this.emit("action", action);
808
+ console.log("[MaestroRecorder] Action captured:", action.type, action.description);
809
+ if (action.type === "launch") {
810
+ const launchAppId = action.appId || action.text;
811
+ if (launchAppId && !this.session.appId) {
812
+ this.session.appId = launchAppId;
813
+ }
814
+ }
815
+ const shouldWriteFlow = this.session.captureMode !== "native" || !this.maestroRecordProcess;
816
+ if (shouldWriteFlow && this.session.flowPath) {
817
+ try {
818
+ const flowYaml = this.generateFlowYaml();
819
+ await fs.promises.writeFile(this.session.flowPath, flowYaml);
820
+ } catch (error) {
821
+ console.error("[MaestroRecorder] Failed to update flow YAML during recording:", error);
822
+ }
823
+ }
824
+ await this.writeSessionMetadata();
825
+ this.savePendingSession();
826
+ }
827
+ /**
828
+ * Capture a screenshot
829
+ */
830
+ async captureScreenshot(name, options = {}) {
831
+ if (!this.session) return void 0;
832
+ const now = Date.now();
833
+ if (!options.force && now < this.nextScreenshotAt) {
834
+ return void 0;
835
+ }
836
+ const screenshotName = name ? `${name}.png` : `screenshot_${Date.now()}.png`;
837
+ const screenshotPath = path.join(this.session.screenshotsDir, screenshotName);
838
+ try {
839
+ if (this.session.platform === "android") {
840
+ await execAsync(`adb -s ${this.session.deviceId} exec-out screencap -p > "${screenshotPath}"`);
841
+ } else {
842
+ await execAsync(`xcrun simctl io ${this.session.deviceId} screenshot "${screenshotPath}"`);
843
+ }
844
+ const screenshotBuffer = await fs.promises.readFile(screenshotPath);
845
+ const screenshotHash = createHash("sha1").update(screenshotBuffer).digest("hex");
846
+ if (!options.force && this.lastScreenshotHash === screenshotHash) {
847
+ this.unchangedScreenshotCount += 1;
848
+ await fs.promises.unlink(screenshotPath);
849
+ if (this.unchangedScreenshotCount >= this.screenshotBackoffThreshold) {
850
+ this.currentScreenshotIntervalMs = Math.min(
851
+ this.currentScreenshotIntervalMs * 2,
852
+ this.maxScreenshotIntervalMs
853
+ );
854
+ }
855
+ this.nextScreenshotAt = now + this.currentScreenshotIntervalMs;
856
+ return void 0;
857
+ }
858
+ this.lastScreenshotHash = screenshotHash;
859
+ this.unchangedScreenshotCount = 0;
860
+ this.currentScreenshotIntervalMs = this.baseScreenshotIntervalMs;
861
+ this.nextScreenshotAt = now + this.currentScreenshotIntervalMs;
862
+ this.emit("screenshot", screenshotPath);
863
+ return screenshotPath;
864
+ } catch (error) {
865
+ console.error("Screenshot failed:", error);
866
+ return void 0;
867
+ }
868
+ }
869
+ /**
870
+ * Add a manual action (for iOS or user-initiated)
871
+ */
872
+ addManualAction(type, description, params) {
873
+ return this.recordAction({
874
+ type,
875
+ description,
876
+ ...params
877
+ });
878
+ }
879
+ /**
880
+ * Stop recording and generate outputs
881
+ */
882
+ async stopRecording() {
883
+ if (!this.session) throw new Error("No recording session");
884
+ this.session.status = "stopped";
885
+ this.session.endedAt = Date.now();
886
+ await killZombieMaestroProcesses();
887
+ if (this.adbProcess) {
888
+ this.adbProcess.kill();
889
+ this.adbProcess = null;
890
+ }
891
+ if (this.screenshotInterval) {
892
+ clearInterval(this.screenshotInterval);
893
+ this.screenshotInterval = null;
894
+ }
895
+ if (this.maestroRecordProcess) {
896
+ console.log("[MaestroRecorder] Stopping native maestro record...");
897
+ this.maestroRecordProcess.kill("SIGINT");
898
+ await new Promise((resolve) => {
899
+ const timeout = setTimeout(() => {
900
+ console.log("[MaestroRecorder] Timeout waiting for maestro record, forcing kill");
901
+ this.maestroRecordProcess?.kill("SIGKILL");
902
+ resolve();
903
+ }, 5e3);
904
+ this.maestroRecordProcess?.on("close", () => {
905
+ clearTimeout(timeout);
906
+ resolve();
907
+ });
908
+ });
909
+ this.maestroRecordProcess = null;
910
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
911
+ const recordedActions = this.session.actions;
912
+ let parsedActions = [];
913
+ if (this.session.flowPath && fs.existsSync(this.session.flowPath)) {
914
+ console.log("[MaestroRecorder] Reading generated YAML from:", this.session.flowPath);
915
+ try {
916
+ const yamlContent = await fs.promises.readFile(this.session.flowPath, "utf-8");
917
+ parsedActions = this.parseActionsFromYaml(yamlContent);
918
+ console.log(`[MaestroRecorder] Parsed ${parsedActions.length} actions from YAML`);
919
+ this.session.actions = this.mergeParsedActionsWithRecorded(parsedActions, recordedActions);
920
+ } catch (e) {
921
+ console.error("[MaestroRecorder] Failed to read/parse YAML:", e);
922
+ }
923
+ } else {
924
+ console.log("[MaestroRecorder] No YAML file found at:", this.session.flowPath);
925
+ }
926
+ const flowPath = this.session.flowPath || path.join(this.session.screenshotsDir, "..", "test.yaml");
927
+ if ((parsedActions.length === 0 || !fs.existsSync(flowPath)) && recordedActions.length > 0) {
928
+ const flowYaml = this.generateFlowYaml();
929
+ await fs.promises.writeFile(flowPath, flowYaml);
930
+ this.session.flowPath = flowPath;
931
+ this.session.actions = recordedActions;
932
+ console.log("[MaestroRecorder] Fallback YAML generated from recorded actions");
933
+ }
934
+ }
935
+ if (this.videoProcess) {
936
+ this.videoProcess.kill("SIGINT");
937
+ await new Promise((resolve) => setTimeout(resolve, 2e3));
938
+ if (this.session.platform === "android" && this.session.videoPath) {
939
+ try {
940
+ await execAsync(`adb -s ${this.session.deviceId} pull /sdcard/maestro-recording.mp4 "${this.session.videoPath}"`);
941
+ await execAsync(`adb -s ${this.session.deviceId} shell rm /sdcard/maestro-recording.mp4`);
942
+ } catch (e) {
943
+ console.error("Failed to pull video:", e);
944
+ }
945
+ }
946
+ this.videoProcess = null;
947
+ }
948
+ if (!this.session.flowPath || !fs.existsSync(this.session.flowPath)) {
949
+ if (this.session.actions.length > 0) {
950
+ const flowYaml = this.generateFlowYaml();
951
+ const fallbackFlowPath = path.join(this.session.screenshotsDir, "..", "test.yaml");
952
+ await fs.promises.writeFile(fallbackFlowPath, flowYaml);
953
+ this.session.flowPath = fallbackFlowPath;
954
+ console.log("[MaestroRecorder] Generated flow YAML from recorded actions");
955
+ }
956
+ }
957
+ const metadataPath = path.join(this.session.screenshotsDir, "..", "session.json");
958
+ await fs.promises.writeFile(metadataPath, JSON.stringify(this.session, null, 2));
959
+ this.clearPendingSession();
960
+ this.emit("status", "stopped");
961
+ this.emit("stopped", this.session);
962
+ const result = this.session;
963
+ this.session = null;
964
+ return result;
965
+ }
966
+ /**
967
+ * Parse actions from Maestro YAML content
968
+ */
969
+ parseActionsFromYaml(yamlContent) {
970
+ const actions = [];
971
+ const lines = yamlContent.split("\n");
972
+ let currentAction = null;
973
+ let actionIndex = 0;
974
+ const nextId = () => `action_${String(++actionIndex).padStart(3, "0")}`;
975
+ const cleanValue = (value) => value.trim().replace(/^["']|["']$/g, "");
976
+ const pushAction = (action) => {
977
+ actions.push({
978
+ id: action.id || nextId(),
979
+ type: action.type || "tap",
980
+ timestamp: action.timestamp || Date.now(),
981
+ description: action.description || action.type || "Action",
982
+ x: action.x,
983
+ y: action.y,
984
+ endX: action.endX,
985
+ endY: action.endY,
986
+ text: action.text,
987
+ direction: action.direction,
988
+ seconds: action.seconds,
989
+ appId: action.appId,
990
+ duration: action.duration,
991
+ screenshotPath: action.screenshotPath
992
+ });
993
+ };
994
+ for (const line of lines) {
995
+ const trimmed = line.trim();
996
+ if (trimmed.startsWith("#") || trimmed === "" || trimmed === "---") {
997
+ continue;
998
+ }
999
+ if (trimmed.startsWith("appId:")) {
1000
+ const parsedAppId = cleanValue(trimmed.replace("appId:", ""));
1001
+ if (this.session && parsedAppId && !this.session.appId) {
1002
+ this.session.appId = parsedAppId;
1003
+ }
1004
+ continue;
1005
+ }
1006
+ if (trimmed.startsWith("- tapOn:")) {
1007
+ const inlineValue = cleanValue(trimmed.replace("- tapOn:", ""));
1008
+ if (inlineValue) {
1009
+ pushAction({
1010
+ type: "tap",
1011
+ description: `Tap on "${inlineValue}"`,
1012
+ text: inlineValue
1013
+ });
1014
+ continue;
1015
+ }
1016
+ currentAction = { type: "tap", description: "Tap" };
1017
+ } else if (trimmed.startsWith("- tap:")) {
1018
+ currentAction = { type: "tap", description: "Tap" };
1019
+ } else if (trimmed.startsWith("- swipe:")) {
1020
+ currentAction = { type: "swipe", description: "Swipe" };
1021
+ } else if (trimmed.startsWith("- scroll:")) {
1022
+ currentAction = { type: "scroll", description: "Scroll" };
1023
+ } else if (trimmed.startsWith("- scrollUntilVisible:")) {
1024
+ currentAction = { type: "scroll", description: "Scroll" };
1025
+ } else if (trimmed.startsWith("- inputText:")) {
1026
+ const text = cleanValue(trimmed.replace("- inputText:", ""));
1027
+ pushAction({
1028
+ type: "input",
1029
+ description: `Input: ${text.slice(0, 20)}${text.length > 20 ? "..." : ""}`,
1030
+ text
1031
+ });
1032
+ continue;
1033
+ } else if (trimmed.startsWith("- launchApp:")) {
1034
+ const appId = cleanValue(trimmed.replace("- launchApp:", ""));
1035
+ pushAction({
1036
+ type: "launch",
1037
+ description: `Launch: ${appId}`,
1038
+ text: appId,
1039
+ appId
1040
+ });
1041
+ continue;
1042
+ } else if (trimmed === "- launchApp") {
1043
+ pushAction({
1044
+ type: "launch",
1045
+ description: "Launch app"
1046
+ });
1047
+ continue;
1048
+ } else if (trimmed.startsWith("- assertVisible:")) {
1049
+ const inlineValue = cleanValue(trimmed.replace("- assertVisible:", ""));
1050
+ if (inlineValue) {
1051
+ pushAction({
1052
+ type: "assert",
1053
+ description: `Assert visible "${inlineValue}"`,
1054
+ text: inlineValue
1055
+ });
1056
+ continue;
1057
+ }
1058
+ currentAction = { type: "assert", description: "Assert visible" };
1059
+ } else if (trimmed.startsWith("- extendedWaitUntil:")) {
1060
+ currentAction = { type: "wait", description: "Wait" };
1061
+ } else if (trimmed.startsWith("- pressKey:")) {
1062
+ const key = cleanValue(trimmed.replace("- pressKey:", "")).toLowerCase();
1063
+ if (key === "back") {
1064
+ pushAction({ type: "back", description: "Back button" });
1065
+ } else if (key === "home") {
1066
+ pushAction({ type: "home", description: "Home button" });
1067
+ } else {
1068
+ pushAction({
1069
+ type: "pressKey",
1070
+ description: `Press: ${key}`,
1071
+ text: key
1072
+ });
1073
+ }
1074
+ continue;
1075
+ } else if (trimmed.startsWith("- back")) {
1076
+ pushAction({ type: "back", description: "Back button" });
1077
+ continue;
1078
+ }
1079
+ if (currentAction && trimmed.startsWith("point:")) {
1080
+ const point = cleanValue(trimmed.replace("point:", ""));
1081
+ const [x, y] = point.split(",").map((n) => parseInt(n.trim()));
1082
+ if (!isNaN(x) && !isNaN(y)) {
1083
+ currentAction.x = x;
1084
+ currentAction.y = y;
1085
+ currentAction.description = `Tap at (${x}, ${y})`;
1086
+ pushAction(currentAction);
1087
+ currentAction = null;
1088
+ continue;
1089
+ }
1090
+ }
1091
+ if (currentAction && trimmed.startsWith("text:")) {
1092
+ const text = cleanValue(trimmed.replace("text:", ""));
1093
+ currentAction.text = text;
1094
+ if (currentAction.type === "assert") {
1095
+ currentAction.description = `Assert visible "${text}"`;
1096
+ } else {
1097
+ currentAction.description = `Tap on "${text}"`;
1098
+ }
1099
+ pushAction(currentAction);
1100
+ currentAction = null;
1101
+ continue;
1102
+ }
1103
+ if (currentAction && trimmed.startsWith("id:")) {
1104
+ const id = cleanValue(trimmed.replace("id:", ""));
1105
+ currentAction.text = id;
1106
+ currentAction.description = `Tap on id: ${id}`;
1107
+ pushAction(currentAction);
1108
+ currentAction = null;
1109
+ continue;
1110
+ }
1111
+ if (currentAction && (currentAction.type === "swipe" || currentAction.type === "scroll") && trimmed.startsWith("direction:")) {
1112
+ const direction = cleanValue(trimmed.replace("direction:", "")).toLowerCase();
1113
+ currentAction.direction = direction;
1114
+ currentAction.description = currentAction.type === "swipe" ? `Swipe ${direction}` : `Scroll ${direction}`;
1115
+ pushAction(currentAction);
1116
+ currentAction = null;
1117
+ continue;
1118
+ }
1119
+ if (currentAction && currentAction.type === "wait" && trimmed.startsWith("timeout:")) {
1120
+ const timeoutMs = parseInt(cleanValue(trimmed.replace("timeout:", "")), 10);
1121
+ const seconds = Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.max(1, Math.round(timeoutMs / 1e3)) : 3;
1122
+ currentAction.seconds = seconds;
1123
+ currentAction.description = `Wait ${seconds}s`;
1124
+ pushAction(currentAction);
1125
+ currentAction = null;
1126
+ continue;
1127
+ }
1128
+ if (currentAction && currentAction.type === "swipe") {
1129
+ if (trimmed.startsWith("start:")) {
1130
+ const point = cleanValue(trimmed.replace("start:", ""));
1131
+ const [x, y] = point.split(",").map((n) => parseInt(n.trim()));
1132
+ if (!isNaN(x) && !isNaN(y)) {
1133
+ currentAction.x = x;
1134
+ currentAction.y = y;
1135
+ }
1136
+ } else if (trimmed.startsWith("end:")) {
1137
+ const point = cleanValue(trimmed.replace("end:", ""));
1138
+ const [x, y] = point.split(",").map((n) => parseInt(n.trim()));
1139
+ if (!isNaN(x) && !isNaN(y)) {
1140
+ currentAction.endX = x;
1141
+ currentAction.endY = y;
1142
+ currentAction.description = `Swipe from (${currentAction.x}, ${currentAction.y}) to (${x}, ${y})`;
1143
+ pushAction(currentAction);
1144
+ currentAction = null;
1145
+ }
1146
+ }
1147
+ }
1148
+ }
1149
+ return actions;
1150
+ }
1151
+ mergeParsedActionsWithRecorded(parsedActions, recordedActions) {
1152
+ if (parsedActions.length === 0) return recordedActions;
1153
+ if (recordedActions.length === 0) return parsedActions;
1154
+ const recordedWithScreens = recordedActions.filter((action) => action.screenshotPath);
1155
+ if (recordedWithScreens.length === 0) return parsedActions;
1156
+ const shouldMapScreenshot = (action) => action.type === "tap" || action.type === "swipe" || action.type === "scroll" || action.type === "longPress" || action.type === "back" || action.type === "home" || action.type === "assert" || action.type === "wait";
1157
+ let recordedIndex = 0;
1158
+ return parsedActions.map((action) => {
1159
+ if (!shouldMapScreenshot(action) || recordedIndex >= recordedWithScreens.length) {
1160
+ return action;
1161
+ }
1162
+ const recorded = recordedWithScreens[recordedIndex++];
1163
+ return {
1164
+ ...recorded,
1165
+ ...action,
1166
+ id: recorded.id || action.id,
1167
+ screenshotPath: recorded.screenshotPath,
1168
+ x: action.x ?? recorded.x,
1169
+ y: action.y ?? recorded.y,
1170
+ endX: action.endX ?? recorded.endX,
1171
+ endY: action.endY ?? recorded.endY,
1172
+ text: action.text ?? recorded.text,
1173
+ direction: action.direction ?? recorded.direction,
1174
+ seconds: action.seconds ?? recorded.seconds,
1175
+ appId: action.appId ?? recorded.appId,
1176
+ duration: action.duration ?? recorded.duration,
1177
+ timestamp: recorded.timestamp || action.timestamp,
1178
+ description: action.description || recorded.description,
1179
+ type: action.type
1180
+ };
1181
+ });
1182
+ }
1183
+ /**
1184
+ * Generate Maestro YAML from recorded actions
1185
+ */
1186
+ generateFlowYaml() {
1187
+ if (!this.session) return "";
1188
+ const escapeYaml = (value) => value.replace(/"/g, '\\"');
1189
+ const lines = [
1190
+ `# Maestro Flow: ${this.session.name}`,
1191
+ `# Recorded: ${new Date(this.session.startedAt).toISOString()}`,
1192
+ `# Generated by DiscoveryLab`,
1193
+ ``
1194
+ ];
1195
+ if (this.session.appId) {
1196
+ lines.push(`appId: ${this.session.appId}`);
1197
+ lines.push(``);
1198
+ }
1199
+ lines.push(`---`);
1200
+ lines.push(``);
1201
+ for (const action of this.session.actions) {
1202
+ lines.push(`# ${action.description}`);
1203
+ switch (action.type) {
1204
+ case "tap":
1205
+ if (action.text) {
1206
+ lines.push(`- tapOn:`);
1207
+ lines.push(` text: "${escapeYaml(action.text)}"`);
1208
+ } else if (action.x !== void 0 && action.y !== void 0) {
1209
+ lines.push(`- tapOn:`);
1210
+ lines.push(` point: "${action.x},${action.y}"`);
1211
+ }
1212
+ break;
1213
+ case "swipe":
1214
+ if (action.x !== void 0 && action.y !== void 0 && action.endX !== void 0 && action.endY !== void 0) {
1215
+ lines.push(`- swipe:`);
1216
+ lines.push(` start: "${action.x},${action.y}"`);
1217
+ lines.push(` end: "${action.endX},${action.endY}"`);
1218
+ if (action.duration) {
1219
+ lines.push(` duration: ${action.duration}`);
1220
+ }
1221
+ } else if (action.direction) {
1222
+ lines.push(`- swipe:`);
1223
+ lines.push(` direction: "${action.direction.toUpperCase()}"`);
1224
+ }
1225
+ break;
1226
+ case "longPress":
1227
+ if (action.x !== void 0 && action.y !== void 0) {
1228
+ lines.push(`- longPressOn:`);
1229
+ lines.push(` point: "${action.x},${action.y}"`);
1230
+ }
1231
+ break;
1232
+ case "input":
1233
+ if (action.text) {
1234
+ lines.push(`- inputText: "${escapeYaml(action.text)}"`);
1235
+ }
1236
+ break;
1237
+ case "back":
1238
+ lines.push(`- pressKey: back`);
1239
+ break;
1240
+ case "home":
1241
+ lines.push(`- pressKey: home`);
1242
+ break;
1243
+ case "scroll":
1244
+ if (action.direction && action.direction.toLowerCase() === "down") {
1245
+ lines.push(`- scrollUntilVisible:`);
1246
+ lines.push(` element: ".*"`);
1247
+ lines.push(` direction: "DOWN"`);
1248
+ } else {
1249
+ lines.push(`- scroll`);
1250
+ }
1251
+ break;
1252
+ case "launch": {
1253
+ const launchAppId = action.appId || action.text;
1254
+ if (launchAppId) {
1255
+ lines.push(`- launchApp: "${escapeYaml(launchAppId)}"`);
1256
+ if (!this.session.appId) {
1257
+ this.session.appId = launchAppId;
1258
+ }
1259
+ } else {
1260
+ lines.push(`- launchApp`);
1261
+ }
1262
+ break;
1263
+ }
1264
+ case "assert":
1265
+ if (action.text) {
1266
+ lines.push(`- assertVisible:`);
1267
+ lines.push(` text: "${escapeYaml(action.text)}"`);
1268
+ }
1269
+ break;
1270
+ case "wait": {
1271
+ const seconds = action.seconds && action.seconds > 0 ? Math.round(action.seconds) : 3;
1272
+ lines.push(`- extendedWaitUntil:`);
1273
+ lines.push(` visible: ".*"`);
1274
+ lines.push(` timeout: ${seconds * 1e3}`);
1275
+ break;
1276
+ }
1277
+ default:
1278
+ lines.push(`# Unknown action: ${action.type}`);
1279
+ }
1280
+ lines.push(``);
1281
+ }
1282
+ return lines.join("\n");
1283
+ }
1284
+ /**
1285
+ * Get current session
1286
+ */
1287
+ getSession() {
1288
+ return this.session;
1289
+ }
1290
+ /**
1291
+ * Check if recording is active
1292
+ */
1293
+ isRecording() {
1294
+ return this.session?.status === "recording";
1295
+ }
1296
+ };
1297
+ var maestroRecorderInstance = null;
1298
+ function getMaestroRecorder() {
1299
+ if (!maestroRecorderInstance) {
1300
+ maestroRecorderInstance = new MaestroRecorder();
1301
+ }
1302
+ return maestroRecorderInstance;
1303
+ }
1304
+
1305
+ export {
1306
+ isMaestroInstalled,
1307
+ isIdbInstalled,
1308
+ tapViaIdb,
1309
+ killZombieMaestroProcesses,
1310
+ getMaestroVersion,
1311
+ listMaestroDevices,
1312
+ generateMaestroFlow,
1313
+ runMaestroTest,
1314
+ runMaestroWithCapture,
1315
+ startMaestroStudio,
1316
+ createLoginFlow,
1317
+ createOnboardingFlow,
1318
+ createNavigationTestFlow,
1319
+ getMaestroRecorder
1320
+ };