@veolab/discoverylab 1.2.1 → 1.3.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 (160) hide show
  1. package/.mcp.json +2 -2
  2. package/README.md +182 -0
  3. package/dist/{chunk-TAODYZ52.js → chunk-3QRQEDWR.js} +510 -213
  4. package/dist/{chunk-L4SA5F5W.js → chunk-4L76GPRC.js} +1162 -58
  5. package/dist/chunk-6EGBXRDK.js +30 -0
  6. package/dist/{chunk-I6YD3QFM.js → chunk-FIL7IWEL.js} +5 -3
  7. package/dist/{chunk-4KLG6DDE.js → chunk-FNUN7EPB.js} +6 -6
  8. package/dist/chunk-GAKEFJ5T.js +481 -0
  9. package/dist/chunk-LB3RNE3O.js +109 -0
  10. package/dist/chunk-N6JJ2RGV.js +2680 -0
  11. package/dist/{chunk-XUKWS2CE.js → chunk-VRM42PML.js} +3546 -926
  12. package/dist/{chunk-TJ3H23LL.js → chunk-VVIOB362.js} +3 -1
  13. package/dist/{chunk-W3WJGYR6.js → chunk-XFVDP332.js} +8 -2
  14. package/dist/{chunk-QJXXHOV7.js → chunk-XKX6NBHF.js} +5 -1
  15. package/dist/cli.js +405 -11
  16. package/dist/{db-ADBEBNH6.js → db-6WLEVKUV.js} +3 -1
  17. package/dist/esvp-GSISVXLC.js +52 -0
  18. package/dist/esvp-mobile-GC7MAGMI.js +20 -0
  19. package/dist/index.d.ts +123 -1
  20. package/dist/index.html +11689 -8690
  21. package/dist/index.js +67 -11
  22. package/dist/{ocr-UTWC7537.js → ocr-QDYNCSPE.js} +1 -1
  23. package/dist/{playwright-R7Y5HREH.js → playwright-VZ7PXDC5.js} +2 -2
  24. package/dist/runtime/esvp-host-runtime/darwin-arm64/esvp-host-runtime +0 -0
  25. package/dist/runtime/esvp-host-runtime/manifest.json +10 -0
  26. package/dist/{server-3FBHBA7L.js → server-6N3KIEGP.js} +2 -1
  27. package/dist/server-FO3UVUZU.js +22 -0
  28. package/dist/{setup-27CQAX6K.js → setup-2SQC5UHJ.js} +4 -3
  29. package/dist/{tools-L6PKKQPY.js → tools-OCRMOQ4U.js} +63 -8
  30. package/package.json +36 -5
  31. package/dist/chunk-22OCFYHG.js +0 -6283
  32. package/dist/chunk-24VARQVO.js +0 -7818
  33. package/dist/chunk-2OGZX6C4.js +0 -588
  34. package/dist/chunk-2WCNIFRO.js +0 -6191
  35. package/dist/chunk-43U6UYV7.js +0 -590
  36. package/dist/chunk-4H2E3K2G.js +0 -7638
  37. package/dist/chunk-4MS6YW2B.js +0 -6490
  38. package/dist/chunk-4NNTRJOI.js +0 -7791
  39. package/dist/chunk-5F76VWME.js +0 -6397
  40. package/dist/chunk-5NEFN42O.js +0 -7791
  41. package/dist/chunk-63MEQ6UH.js +0 -7673
  42. package/dist/chunk-6H3NXFX3.js +0 -6861
  43. package/dist/chunk-7IDQLLBW.js +0 -311
  44. package/dist/chunk-7NP64TGJ.js +0 -6822
  45. package/dist/chunk-AATLY4KT.js +0 -6505
  46. package/dist/chunk-C7QUR7XX.js +0 -6397
  47. package/dist/chunk-CGKCE6MC.js +0 -6279
  48. package/dist/chunk-D25V6IWE.js +0 -6487
  49. package/dist/chunk-EQOZSXAT.js +0 -6822
  50. package/dist/chunk-FPHD7HSQ.js +0 -6812
  51. package/dist/chunk-GGJJUCFK.js +0 -7160
  52. package/dist/chunk-GLHOY3NN.js +0 -7805
  53. package/dist/chunk-GML5MKQA.js +0 -6398
  54. package/dist/chunk-GOL6FUJL.js +0 -6045
  55. package/dist/chunk-GSWHWEYC.js +0 -1346
  56. package/dist/chunk-HDKEQOF5.js +0 -7788
  57. package/dist/chunk-HZGSWVVS.js +0 -7111
  58. package/dist/chunk-IGZ5TICZ.js +0 -334
  59. package/dist/chunk-IRKQG33A.js +0 -7054
  60. package/dist/chunk-JFTBF4JR.js +0 -6040
  61. package/dist/chunk-JVLVBPUJ.js +0 -6180
  62. package/dist/chunk-JY3KC67R.js +0 -6504
  63. package/dist/chunk-KUFBCBNJ.js +0 -6815
  64. package/dist/chunk-KV7KDJ43.js +0 -7639
  65. package/dist/chunk-L5IJZV5F.js +0 -6822
  66. package/dist/chunk-MFFPQLU4.js +0 -7102
  67. package/dist/chunk-MJS2YKNR.js +0 -6397
  68. package/dist/chunk-MN6LCZHZ.js +0 -1320
  69. package/dist/chunk-NBAUZ7X2.js +0 -1336
  70. package/dist/chunk-NDBW6ELQ.js +0 -7638
  71. package/dist/chunk-O2HBSDI2.js +0 -6175
  72. package/dist/chunk-OFFIUYMG.js +0 -6341
  73. package/dist/chunk-OVCQGF2J.js +0 -1321
  74. package/dist/chunk-P4S7ZY6G.js +0 -7638
  75. package/dist/chunk-PBHUHSC3.js +0 -6002
  76. package/dist/chunk-PC4LR4ZI.js +0 -6359
  77. package/dist/chunk-PMTGGZ7R.js +0 -6397
  78. package/dist/chunk-PTXSB3UV.js +0 -497
  79. package/dist/chunk-PYUCY3U6.js +0 -1340
  80. package/dist/chunk-RDZDSOAL.js +0 -7750
  81. package/dist/chunk-RLW2OI2L.js +0 -6383
  82. package/dist/chunk-RUGHHO4K.js +0 -6395
  83. package/dist/chunk-SIOQVM2E.js +0 -6819
  84. package/dist/chunk-SR67SRIT.js +0 -1336
  85. package/dist/chunk-SSRXIO2V.js +0 -6822
  86. package/dist/chunk-SWSEKFON.js +0 -6487
  87. package/dist/chunk-TBG76CYG.js +0 -6395
  88. package/dist/chunk-V3CBINLD.js +0 -6812
  89. package/dist/chunk-VPYSLEGM.js +0 -6710
  90. package/dist/chunk-VY3BLXBW.js +0 -329
  91. package/dist/chunk-WTFOGVJQ.js +0 -6365
  92. package/dist/chunk-X64SFUT5.js +0 -6099
  93. package/dist/chunk-XIBF5LBD.js +0 -6395
  94. package/dist/chunk-Y5VDMSYC.js +0 -6701
  95. package/dist/chunk-YUBL36H4.js +0 -6605
  96. package/dist/chunk-YWVXFVSW.js +0 -6456
  97. package/dist/chunk-ZXZACOLD.js +0 -6822
  98. package/dist/db-IWIL65EX.js +0 -33
  99. package/dist/gridCompositor-ENKLFPWR.js +0 -409
  100. package/dist/playwright-A3OGSDRG.js +0 -38
  101. package/dist/playwright-ATDC4NYW.js +0 -38
  102. package/dist/playwright-E6EUFIJG.js +0 -38
  103. package/dist/server-2DXLKLFM.js +0 -13
  104. package/dist/server-2ICEWJVK.js +0 -13
  105. package/dist/server-2MQV3FNY.js +0 -13
  106. package/dist/server-2NGD7GE3.js +0 -13
  107. package/dist/server-2VKO76UK.js +0 -14
  108. package/dist/server-3BK2VFU7.js +0 -13
  109. package/dist/server-4LDOB3NX.js +0 -13
  110. package/dist/server-4YI44KDR.js +0 -13
  111. package/dist/server-64XMXA5P.js +0 -13
  112. package/dist/server-6IPHVUYT.js +0 -14
  113. package/dist/server-73ORHMJN.js +0 -13
  114. package/dist/server-73P7M3QB.js +0 -14
  115. package/dist/server-BPVRW5LJ.js +0 -14
  116. package/dist/server-BW4RKZIX.js +0 -13
  117. package/dist/server-CFS5SM5K.js +0 -13
  118. package/dist/server-DX7VYHHM.js +0 -13
  119. package/dist/server-F3YPX6ET.js +0 -13
  120. package/dist/server-FUXTR33I.js +0 -13
  121. package/dist/server-G2SY3DOS.js +0 -13
  122. package/dist/server-G32U7VOQ.js +0 -13
  123. package/dist/server-IOOZK4NP.js +0 -14
  124. package/dist/server-J52LMTBT.js +0 -13
  125. package/dist/server-JG7UKFGK.js +0 -14
  126. package/dist/server-JSCHEBOD.js +0 -13
  127. package/dist/server-K6KC4ZOM.js +0 -13
  128. package/dist/server-KJVRGWFE.js +0 -13
  129. package/dist/server-LCPB2L4U.js +0 -13
  130. package/dist/server-M7LDYKAJ.js +0 -13
  131. package/dist/server-MKVK6ZQQ.js +0 -13
  132. package/dist/server-MU52LCXT.js +0 -13
  133. package/dist/server-NM5CKDUU.js +0 -13
  134. package/dist/server-NPZN3FWO.js +0 -14
  135. package/dist/server-O5FIAHSY.js +0 -14
  136. package/dist/server-OESJUEYC.js +0 -13
  137. package/dist/server-ONSKQO4W.js +0 -13
  138. package/dist/server-P27BZXBL.js +0 -14
  139. package/dist/server-Q4FBWQUA.js +0 -13
  140. package/dist/server-RNQ7VUAL.js +0 -13
  141. package/dist/server-S6B5WUBT.js +0 -14
  142. package/dist/server-SRYNSGSP.js +0 -14
  143. package/dist/server-SUN3W2YK.js +0 -13
  144. package/dist/server-UA62LHZB.js +0 -13
  145. package/dist/server-UJB44EW5.js +0 -13
  146. package/dist/server-X3TLP6DX.js +0 -14
  147. package/dist/server-YT2UGEZK.js +0 -13
  148. package/dist/server-ZBPQ33V6.js +0 -14
  149. package/dist/setup-AQX4JQVR.js +0 -17
  150. package/dist/setup-EQTU7FI6.js +0 -17
  151. package/dist/tools-2KPB37GK.js +0 -178
  152. package/dist/tools-3H6IOWXV.js +0 -178
  153. package/dist/tools-3KYHPDCJ.js +0 -178
  154. package/dist/tools-75BAPCUM.js +0 -177
  155. package/dist/tools-BUVCUCRL.js +0 -178
  156. package/dist/tools-HDNODRS6.js +0 -178
  157. package/dist/tools-HP5MNY3D.js +0 -177
  158. package/dist/tools-N5N2IO7V.js +0 -178
  159. package/dist/tools-NFJEZ2FF.js +0 -177
  160. package/dist/tools-TLCKABUW.js +0 -178
@@ -1,1340 +0,0 @@
1
- import {
2
- PROJECTS_DIR
3
- } from "./chunk-TJ3H23LL.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
- const errLike = error;
308
- const stdout = typeof errLike?.stdout === "string" ? errLike.stdout : Buffer.isBuffer(errLike?.stdout) ? errLike.stdout.toString("utf8") : "";
309
- const stderr = typeof errLike?.stderr === "string" ? errLike.stderr : Buffer.isBuffer(errLike?.stderr) ? errLike.stderr.toString("utf8") : "";
310
- const detailedOutput = [stderr?.trim(), stdout?.trim(), message].filter(Boolean).join("\n\n").slice(-16e3);
311
- return {
312
- success: false,
313
- error: stderr?.trim() || message,
314
- duration,
315
- flowPath,
316
- output: detailedOutput || message
317
- };
318
- }
319
- }
320
- async function runMaestroWithCapture(options, onProgress) {
321
- const {
322
- flowPath,
323
- device,
324
- outputDir = path.join(PROJECTS_DIR, "maestro-output", Date.now().toString())
325
- } = options;
326
- await fs.promises.mkdir(outputDir, { recursive: true });
327
- const videoPath = path.join(outputDir, "recording.mp4");
328
- let recordingProcess = null;
329
- try {
330
- onProgress?.("Starting screen recording...");
331
- if (device) {
332
- const devices = await listMaestroDevices();
333
- const targetDevice = devices.find((d) => d.id === device || d.name === device);
334
- if (targetDevice?.platform === "ios") {
335
- recordingProcess = spawn("xcrun", ["simctl", "io", device, "recordVideo", videoPath]);
336
- } else if (targetDevice?.platform === "android") {
337
- recordingProcess = spawn("adb", ["-s", device, "shell", "screenrecord", "/sdcard/recording.mp4"]);
338
- }
339
- }
340
- onProgress?.("Running Maestro test...");
341
- const result = await runMaestroTest({ ...options, outputDir });
342
- onProgress?.("Stopping screen recording...");
343
- if (recordingProcess) {
344
- recordingProcess.kill("SIGINT");
345
- await new Promise((resolve) => setTimeout(resolve, 2e3));
346
- const devices = await listMaestroDevices();
347
- const targetDevice = devices.find((d) => d.id === device || d.name === device);
348
- if (targetDevice?.platform === "android") {
349
- await execAsync(`adb -s ${device} pull /sdcard/recording.mp4 "${videoPath}"`);
350
- await execAsync(`adb -s ${device} shell rm /sdcard/recording.mp4`);
351
- }
352
- }
353
- return {
354
- ...result,
355
- video: fs.existsSync(videoPath) ? videoPath : void 0
356
- };
357
- } catch (error) {
358
- if (recordingProcess) {
359
- recordingProcess.kill("SIGKILL");
360
- }
361
- return {
362
- success: false,
363
- error: error instanceof Error ? error.message : String(error),
364
- flowPath
365
- };
366
- }
367
- }
368
- async function startMaestroStudio(appId) {
369
- const installed = await isMaestroInstalled();
370
- if (!installed) {
371
- return {
372
- success: false,
373
- error: "Maestro CLI is not installed"
374
- };
375
- }
376
- try {
377
- const args = ["studio"];
378
- if (appId) {
379
- args.push(appId);
380
- }
381
- const maestroCmd = await resolveMaestroCommand();
382
- if (!maestroCmd) {
383
- return { success: false, error: "Maestro CLI is not installed or not runnable" };
384
- }
385
- spawn(maestroCmd, args, {
386
- detached: true,
387
- stdio: "ignore"
388
- }).unref();
389
- return { success: true };
390
- } catch (error) {
391
- return {
392
- success: false,
393
- error: error instanceof Error ? error.message : String(error)
394
- };
395
- }
396
- }
397
- function createLoginFlow(appId, usernameField, passwordField, loginButton, successIndicator) {
398
- return {
399
- appId,
400
- name: "Login Flow",
401
- steps: [
402
- MaestroActions.launchApp(appId),
403
- MaestroActions.waitForAnimationToEnd(),
404
- MaestroActions.tapOn(usernameField),
405
- MaestroActions.inputText("${USERNAME}"),
406
- MaestroActions.tapOn(passwordField),
407
- MaestroActions.inputText("${PASSWORD}"),
408
- MaestroActions.hideKeyboard(),
409
- MaestroActions.tapOn(loginButton),
410
- MaestroActions.waitForAnimationToEnd(5e3),
411
- MaestroActions.assertVisible(successIndicator)
412
- ]
413
- };
414
- }
415
- function createOnboardingFlow(appId, screens) {
416
- const steps = [
417
- MaestroActions.launchApp(appId),
418
- MaestroActions.waitForAnimationToEnd()
419
- ];
420
- for (const screen of screens) {
421
- if (screen.waitFor) {
422
- steps.push(MaestroActions.assertVisible(screen.waitFor));
423
- }
424
- steps.push(MaestroActions.tapOn(screen.nextButton));
425
- steps.push(MaestroActions.waitForAnimationToEnd());
426
- }
427
- return {
428
- appId,
429
- name: "Onboarding Flow",
430
- steps
431
- };
432
- }
433
- function createNavigationTestFlow(appId, tabs) {
434
- const steps = [
435
- MaestroActions.launchApp(appId),
436
- MaestroActions.waitForAnimationToEnd()
437
- ];
438
- for (const tab of tabs) {
439
- steps.push(MaestroActions.tapOn(tab));
440
- steps.push(MaestroActions.waitForAnimationToEnd());
441
- steps.push(MaestroActions.takeScreenshot(`${tab.replace(/\s+/g, "_")}.png`));
442
- }
443
- return {
444
- appId,
445
- name: "Navigation Test",
446
- steps
447
- };
448
- }
449
- var MaestroRecorder = class extends EventEmitter {
450
- session = null;
451
- adbProcess = null;
452
- videoProcess = null;
453
- maestroRecordProcess = null;
454
- // Native maestro record process
455
- actionCounter = 0;
456
- screenshotInterval = null;
457
- useNativeMaestroRecord = true;
458
- // Use native maestro record for better accuracy
459
- legacyCaptureStarted = false;
460
- lastMaestroRecordErrorLine = null;
461
- baseScreenshotIntervalMs = 2e3;
462
- maxScreenshotIntervalMs = 12e3;
463
- currentScreenshotIntervalMs = this.baseScreenshotIntervalMs;
464
- nextScreenshotAt = 0;
465
- lastScreenshotHash = null;
466
- unchangedScreenshotCount = 0;
467
- screenshotBackoffThreshold = 3;
468
- constructor() {
469
- super();
470
- this.loadPendingSession();
471
- }
472
- /**
473
- * Check if maestro is available in system PATH
474
- */
475
- isMaestroInPath() {
476
- try {
477
- execSync("which maestro", { encoding: "utf-8", timeout: 2e3 });
478
- return true;
479
- } catch {
480
- return false;
481
- }
482
- }
483
- canRunMaestro(cmd) {
484
- try {
485
- execSync(`"${cmd}" --version`, { encoding: "utf-8", timeout: 3e3 });
486
- return true;
487
- } catch {
488
- return false;
489
- }
490
- }
491
- startLegacyCapture(deviceId, platform) {
492
- if (platform === "android") {
493
- if (!this.adbProcess) {
494
- this.startAndroidEventCapture(deviceId);
495
- }
496
- } else {
497
- this.startIOSEventCapture(deviceId);
498
- }
499
- this.legacyCaptureStarted = true;
500
- }
501
- fallbackToLegacyCapture(reason) {
502
- if (!this.session || this.session.status !== "recording") return;
503
- if (this.legacyCaptureStarted) return;
504
- console.log(`[MaestroRecorder] Native record stopped (${reason}). Falling back to manual capture.`);
505
- this.session.captureMode = "manual";
506
- const stderrSuffix = this.lastMaestroRecordErrorLine ? ` | ${this.lastMaestroRecordErrorLine}` : "";
507
- this.session.captureModeReason = `maestro record falhou (${reason})${stderrSuffix}`;
508
- this.startLegacyCapture(this.session.deviceId, this.session.platform);
509
- }
510
- /**
511
- * Save session state to disk for recovery after server restart
512
- */
513
- savePendingSession() {
514
- if (!this.session) return;
515
- try {
516
- fs.writeFileSync(PENDING_SESSION_FILE, JSON.stringify(this.session, null, 2));
517
- } catch (error) {
518
- console.error("[MaestroRecorder] Failed to save pending session:", error);
519
- }
520
- }
521
- /**
522
- * Load pending session from disk (after server restart)
523
- */
524
- loadPendingSession() {
525
- try {
526
- if (fs.existsSync(PENDING_SESSION_FILE)) {
527
- const data = fs.readFileSync(PENDING_SESSION_FILE, "utf8");
528
- const savedSession = JSON.parse(data);
529
- if (savedSession.status === "recording") {
530
- console.log("[MaestroRecorder] Restoring pending session from disk:", savedSession.id);
531
- this.session = savedSession;
532
- this.actionCounter = savedSession.actions.length;
533
- }
534
- }
535
- } catch (error) {
536
- console.error("[MaestroRecorder] Failed to load pending session:", error);
537
- try {
538
- fs.unlinkSync(PENDING_SESSION_FILE);
539
- } catch {
540
- }
541
- }
542
- }
543
- /**
544
- * Clear pending session file (after successful stop)
545
- */
546
- clearPendingSession() {
547
- try {
548
- if (fs.existsSync(PENDING_SESSION_FILE)) {
549
- fs.unlinkSync(PENDING_SESSION_FILE);
550
- }
551
- } catch (error) {
552
- console.error("[MaestroRecorder] Failed to clear pending session:", error);
553
- }
554
- }
555
- /**
556
- * Persist session metadata to session.json (available during recording)
557
- */
558
- async writeSessionMetadata() {
559
- if (!this.session) return;
560
- try {
561
- const metadataPath = path.join(this.session.screenshotsDir, "..", "session.json");
562
- await fs.promises.writeFile(metadataPath, JSON.stringify(this.session, null, 2));
563
- } catch (error) {
564
- console.error("[MaestroRecorder] Failed to write session metadata:", error);
565
- }
566
- }
567
- /**
568
- * Start recording a mobile session
569
- */
570
- async startRecording(name, deviceId, deviceName, platform, appId, options = {}) {
571
- if (this.session?.status === "recording") {
572
- const hasActiveProcesses = !!(this.videoProcess || this.maestroRecordProcess || this.adbProcess);
573
- if (hasActiveProcesses) {
574
- throw new Error("Recording already in progress");
575
- }
576
- console.log("[MaestroRecorder] Stale recording session detected. Clearing before starting a new one.");
577
- this.session = null;
578
- if (this.screenshotInterval) {
579
- clearInterval(this.screenshotInterval);
580
- this.screenshotInterval = null;
581
- }
582
- this.clearPendingSession();
583
- }
584
- const sessionId = `maestro_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
585
- const baseDir = path.join(PROJECTS_DIR, "maestro-recordings", sessionId);
586
- const screenshotsDir = path.join(baseDir, "screenshots");
587
- await fs.promises.mkdir(screenshotsDir, { recursive: true });
588
- this.session = {
589
- id: sessionId,
590
- name,
591
- startedAt: Date.now(),
592
- appId,
593
- deviceId,
594
- deviceName,
595
- platform,
596
- actions: [],
597
- screenshotsDir,
598
- status: "recording"
599
- };
600
- this.actionCounter = 0;
601
- try {
602
- const flowPath = path.join(baseDir, "test.yaml");
603
- this.session.flowPath = flowPath;
604
- const videoPath = path.join(baseDir, "recording.mp4");
605
- this.session.videoPath = videoPath;
606
- const maestroHomePath = path.join(os.homedir(), ".maestro", "bin", "maestro");
607
- const maestroPath = fs.existsSync(maestroHomePath) ? maestroHomePath : "maestro";
608
- const maestroExists = fs.existsSync(maestroHomePath) || this.isMaestroInPath();
609
- const maestroRunnable = maestroExists && this.canRunMaestro(maestroPath);
610
- const preferNativeRecord = options.preferNativeRecord !== false;
611
- const useNativeRecord = preferNativeRecord && this.useNativeMaestroRecord && maestroRunnable;
612
- if (!maestroRunnable && this.useNativeMaestroRecord) {
613
- console.log("[MaestroRecorder] \u26A0\uFE0F Maestro CLI not available or not runnable. Falling back to screenshot-based capture.");
614
- console.log('[MaestroRecorder] Ensure Java is installed or reinstall Maestro: curl -Ls "https://get.maestro.mobile.dev" | bash');
615
- this.session.captureModeReason = "Maestro CLI indispon\xEDvel/n\xE3o execut\xE1vel (verifique Java e reinstale o Maestro).";
616
- }
617
- if (!preferNativeRecord) {
618
- console.log("[MaestroRecorder] Native record disabled for this session (manual capture mode).");
619
- this.session.captureModeReason = "Native Maestro record desabilitado para esta sess\xE3o.";
620
- }
621
- let nativeRecordStarted = false;
622
- this.legacyCaptureStarted = false;
623
- if (useNativeRecord) {
624
- console.log("[MaestroRecorder] Starting native maestro record...");
625
- this.lastMaestroRecordErrorLine = null;
626
- try {
627
- const recordArgs = ["record", flowPath, "--device", deviceId];
628
- this.maestroRecordProcess = spawn(maestroPath, recordArgs, {
629
- stdio: ["pipe", "pipe", "pipe"],
630
- env: { ...process.env }
631
- });
632
- nativeRecordStarted = true;
633
- this.maestroRecordProcess.stdout?.on("data", (data) => {
634
- console.log("[MaestroRecord]", data.toString().trim());
635
- });
636
- this.maestroRecordProcess.stderr?.on("data", (data) => {
637
- const text = data.toString().trim();
638
- console.log("[MaestroRecord ERROR]", text);
639
- const lastLine = text.split("\n").map((line) => line.trim()).filter(Boolean).pop();
640
- if (lastLine) {
641
- this.lastMaestroRecordErrorLine = lastLine;
642
- }
643
- });
644
- this.maestroRecordProcess.on("error", (err) => {
645
- console.log("[MaestroRecord] Spawn error:", err.message);
646
- this.fallbackToLegacyCapture("spawn error");
647
- this.maestroRecordProcess = null;
648
- });
649
- this.maestroRecordProcess.on("close", (code) => {
650
- console.log(`[MaestroRecord] Process exited with code ${code}`);
651
- this.fallbackToLegacyCapture(`exit code ${code}`);
652
- this.maestroRecordProcess = null;
653
- });
654
- } catch (err) {
655
- console.log("[MaestroRecorder] Failed to start native record, using legacy capture");
656
- this.maestroRecordProcess = null;
657
- nativeRecordStarted = false;
658
- this.session.captureModeReason = err instanceof Error ? `Falha ao iniciar maestro record: ${err.message}` : "Falha ao iniciar maestro record";
659
- }
660
- }
661
- this.session.captureMode = nativeRecordStarted ? "native" : "manual";
662
- if (nativeRecordStarted) {
663
- this.session.captureModeReason = void 0;
664
- }
665
- if (!nativeRecordStarted && this.session.flowPath) {
666
- try {
667
- const initialYaml = this.generateFlowYaml();
668
- await fs.promises.writeFile(this.session.flowPath, initialYaml);
669
- } catch (error) {
670
- console.error("[MaestroRecorder] Failed to write initial flow YAML:", error);
671
- }
672
- }
673
- await this.writeSessionMetadata();
674
- if (nativeRecordStarted) {
675
- if (platform === "ios") {
676
- this.videoProcess = spawn("xcrun", ["simctl", "io", deviceId, "recordVideo", videoPath]);
677
- } else {
678
- const tempVideoPath = "/sdcard/maestro-recording.mp4";
679
- this.videoProcess = spawn("adb", ["-s", deviceId, "shell", "screenrecord", "--time-limit", "180", tempVideoPath]);
680
- }
681
- } else {
682
- if (useNativeRecord) {
683
- console.log("[MaestroRecorder] Native record failed to start, using legacy capture");
684
- }
685
- if (platform === "android") {
686
- const tempVideoPath = "/sdcard/maestro-recording.mp4";
687
- this.videoProcess = spawn("adb", ["-s", deviceId, "shell", "screenrecord", "--time-limit", "180", tempVideoPath]);
688
- this.startLegacyCapture(deviceId, platform);
689
- } else {
690
- this.videoProcess = spawn("xcrun", ["simctl", "io", deviceId, "recordVideo", videoPath]);
691
- this.startLegacyCapture(deviceId, platform);
692
- }
693
- }
694
- this.currentScreenshotIntervalMs = this.baseScreenshotIntervalMs;
695
- this.nextScreenshotAt = 0;
696
- this.lastScreenshotHash = null;
697
- this.unchangedScreenshotCount = 0;
698
- this.screenshotInterval = setInterval(() => {
699
- this.captureScreenshot(void 0, { reason: "periodic" });
700
- }, 2e3);
701
- this.savePendingSession();
702
- this.emit("status", "recording");
703
- return this.session;
704
- } catch (error) {
705
- this.session.status = "error";
706
- this.clearPendingSession();
707
- this.emit("error", error);
708
- throw error;
709
- }
710
- }
711
- /**
712
- * Capture Android touch events via ADB
713
- */
714
- startAndroidEventCapture(deviceId) {
715
- exec(`adb -s ${deviceId} shell wm size`, (err, stdout) => {
716
- if (err) return;
717
- const match = stdout.match(/(\d+)x(\d+)/);
718
- const screenWidth = match ? parseInt(match[1]) : 1080;
719
- const screenHeight = match ? parseInt(match[2]) : 1920;
720
- this.adbProcess = spawn("adb", ["-s", deviceId, "shell", "getevent", "-lt"]);
721
- let touchStartTime = 0;
722
- let touchStartX = 0;
723
- let touchStartY = 0;
724
- let currentX = 0;
725
- let currentY = 0;
726
- let isTracking = false;
727
- this.adbProcess.stdout?.on("data", (data) => {
728
- const lines = data.toString().split("\n");
729
- for (const line of lines) {
730
- if (line.includes("ABS_MT_POSITION_X")) {
731
- const match2 = line.match(/ABS_MT_POSITION_X\s+([0-9a-f]+)/i);
732
- if (match2) {
733
- currentX = Math.round(parseInt(match2[1], 16) / 32767 * screenWidth);
734
- }
735
- }
736
- if (line.includes("ABS_MT_POSITION_Y")) {
737
- const match2 = line.match(/ABS_MT_POSITION_Y\s+([0-9a-f]+)/i);
738
- if (match2) {
739
- currentY = Math.round(parseInt(match2[1], 16) / 32767 * screenHeight);
740
- }
741
- }
742
- if (line.includes("BTN_TOUCH") && line.includes("DOWN")) {
743
- touchStartTime = Date.now();
744
- touchStartX = currentX;
745
- touchStartY = currentY;
746
- isTracking = true;
747
- }
748
- if (line.includes("BTN_TOUCH") && line.includes("UP") && isTracking) {
749
- const duration = Date.now() - touchStartTime;
750
- const deltaX = Math.abs(currentX - touchStartX);
751
- const deltaY = Math.abs(currentY - touchStartY);
752
- if (deltaX > 50 || deltaY > 50) {
753
- this.recordAction({
754
- type: "swipe",
755
- x: touchStartX,
756
- y: touchStartY,
757
- endX: currentX,
758
- endY: currentY,
759
- duration,
760
- description: `Swipe from (${touchStartX}, ${touchStartY}) to (${currentX}, ${currentY})`
761
- });
762
- } else if (duration > 500) {
763
- this.recordAction({
764
- type: "longPress",
765
- x: touchStartX,
766
- y: touchStartY,
767
- duration,
768
- description: `Long press at (${touchStartX}, ${touchStartY})`
769
- });
770
- } else {
771
- this.recordAction({
772
- type: "tap",
773
- x: touchStartX,
774
- y: touchStartY,
775
- description: `Tap at (${touchStartX}, ${touchStartY})`
776
- });
777
- }
778
- isTracking = false;
779
- }
780
- if (line.includes("KEY_BACK") && line.includes("DOWN")) {
781
- this.recordAction({
782
- type: "back",
783
- description: "Press back button"
784
- });
785
- }
786
- if (line.includes("KEY_HOME") && line.includes("DOWN")) {
787
- this.recordAction({
788
- type: "home",
789
- description: "Press home button"
790
- });
791
- }
792
- }
793
- });
794
- });
795
- }
796
- /**
797
- * Capture iOS events (limited - mainly screenshots)
798
- */
799
- startIOSEventCapture(deviceId) {
800
- console.log("[MaestroRecorder] iOS event capture started (screenshot-based)");
801
- }
802
- /**
803
- * Record an action
804
- */
805
- async recordAction(actionData) {
806
- if (!this.session || this.session.status !== "recording") return;
807
- this.actionCounter++;
808
- const actionId = `action_${this.actionCounter.toString().padStart(3, "0")}`;
809
- const screenshotPath = await this.captureScreenshot(actionId, { force: true, reason: "action" });
810
- const action = {
811
- id: actionId,
812
- type: actionData.type || "tap",
813
- timestamp: Date.now(),
814
- x: actionData.x,
815
- y: actionData.y,
816
- endX: actionData.endX,
817
- endY: actionData.endY,
818
- text: actionData.text,
819
- direction: actionData.direction,
820
- seconds: actionData.seconds,
821
- appId: actionData.appId,
822
- duration: actionData.duration,
823
- description: actionData.description || actionData.type || "Action",
824
- screenshotPath
825
- };
826
- this.session.actions.push(action);
827
- this.emit("action", action);
828
- console.log("[MaestroRecorder] Action captured:", action.type, action.description);
829
- if (action.type === "launch") {
830
- const launchAppId = action.appId || action.text;
831
- if (launchAppId && !this.session.appId) {
832
- this.session.appId = launchAppId;
833
- }
834
- }
835
- const shouldWriteFlow = this.session.captureMode !== "native" || !this.maestroRecordProcess;
836
- if (shouldWriteFlow && this.session.flowPath) {
837
- try {
838
- const flowYaml = this.generateFlowYaml();
839
- await fs.promises.writeFile(this.session.flowPath, flowYaml);
840
- } catch (error) {
841
- console.error("[MaestroRecorder] Failed to update flow YAML during recording:", error);
842
- }
843
- }
844
- await this.writeSessionMetadata();
845
- this.savePendingSession();
846
- }
847
- /**
848
- * Capture a screenshot
849
- */
850
- async captureScreenshot(name, options = {}) {
851
- if (!this.session) return void 0;
852
- const now = Date.now();
853
- if (!options.force && now < this.nextScreenshotAt) {
854
- return void 0;
855
- }
856
- const screenshotName = name ? `${name}.png` : `screenshot_${Date.now()}.png`;
857
- const screenshotPath = path.join(this.session.screenshotsDir, screenshotName);
858
- try {
859
- if (this.session.platform === "android") {
860
- await execAsync(`adb -s ${this.session.deviceId} exec-out screencap -p > "${screenshotPath}"`);
861
- } else {
862
- await execAsync(`xcrun simctl io ${this.session.deviceId} screenshot "${screenshotPath}"`);
863
- }
864
- const screenshotBuffer = await fs.promises.readFile(screenshotPath);
865
- const screenshotHash = createHash("sha1").update(screenshotBuffer).digest("hex");
866
- if (!options.force && this.lastScreenshotHash === screenshotHash) {
867
- this.unchangedScreenshotCount += 1;
868
- await fs.promises.unlink(screenshotPath);
869
- if (this.unchangedScreenshotCount >= this.screenshotBackoffThreshold) {
870
- this.currentScreenshotIntervalMs = Math.min(
871
- this.currentScreenshotIntervalMs * 2,
872
- this.maxScreenshotIntervalMs
873
- );
874
- }
875
- this.nextScreenshotAt = now + this.currentScreenshotIntervalMs;
876
- return void 0;
877
- }
878
- this.lastScreenshotHash = screenshotHash;
879
- this.unchangedScreenshotCount = 0;
880
- this.currentScreenshotIntervalMs = this.baseScreenshotIntervalMs;
881
- this.nextScreenshotAt = now + this.currentScreenshotIntervalMs;
882
- this.emit("screenshot", screenshotPath);
883
- return screenshotPath;
884
- } catch (error) {
885
- console.error("Screenshot failed:", error);
886
- return void 0;
887
- }
888
- }
889
- /**
890
- * Add a manual action (for iOS or user-initiated)
891
- */
892
- addManualAction(type, description, params) {
893
- return this.recordAction({
894
- type,
895
- description,
896
- ...params
897
- });
898
- }
899
- /**
900
- * Stop recording and generate outputs
901
- */
902
- async stopRecording() {
903
- if (!this.session) throw new Error("No recording session");
904
- this.session.status = "stopped";
905
- this.session.endedAt = Date.now();
906
- await killZombieMaestroProcesses();
907
- if (this.adbProcess) {
908
- this.adbProcess.kill();
909
- this.adbProcess = null;
910
- }
911
- if (this.screenshotInterval) {
912
- clearInterval(this.screenshotInterval);
913
- this.screenshotInterval = null;
914
- }
915
- if (this.maestroRecordProcess) {
916
- console.log("[MaestroRecorder] Stopping native maestro record...");
917
- this.maestroRecordProcess.kill("SIGINT");
918
- await new Promise((resolve) => {
919
- const timeout = setTimeout(() => {
920
- console.log("[MaestroRecorder] Timeout waiting for maestro record, forcing kill");
921
- this.maestroRecordProcess?.kill("SIGKILL");
922
- resolve();
923
- }, 5e3);
924
- this.maestroRecordProcess?.on("close", () => {
925
- clearTimeout(timeout);
926
- resolve();
927
- });
928
- });
929
- this.maestroRecordProcess = null;
930
- await new Promise((resolve) => setTimeout(resolve, 1e3));
931
- const recordedActions = this.session.actions;
932
- let parsedActions = [];
933
- if (this.session.flowPath && fs.existsSync(this.session.flowPath)) {
934
- console.log("[MaestroRecorder] Reading generated YAML from:", this.session.flowPath);
935
- try {
936
- const yamlContent = await fs.promises.readFile(this.session.flowPath, "utf-8");
937
- parsedActions = this.parseActionsFromYaml(yamlContent);
938
- console.log(`[MaestroRecorder] Parsed ${parsedActions.length} actions from YAML`);
939
- this.session.actions = this.mergeParsedActionsWithRecorded(parsedActions, recordedActions);
940
- } catch (e) {
941
- console.error("[MaestroRecorder] Failed to read/parse YAML:", e);
942
- }
943
- } else {
944
- console.log("[MaestroRecorder] No YAML file found at:", this.session.flowPath);
945
- }
946
- const flowPath = this.session.flowPath || path.join(this.session.screenshotsDir, "..", "test.yaml");
947
- if ((parsedActions.length === 0 || !fs.existsSync(flowPath)) && recordedActions.length > 0) {
948
- const flowYaml = this.generateFlowYaml();
949
- await fs.promises.writeFile(flowPath, flowYaml);
950
- this.session.flowPath = flowPath;
951
- this.session.actions = recordedActions;
952
- console.log("[MaestroRecorder] Fallback YAML generated from recorded actions");
953
- }
954
- }
955
- if (this.videoProcess) {
956
- this.videoProcess.kill("SIGINT");
957
- await new Promise((resolve) => setTimeout(resolve, 2e3));
958
- if (this.session.platform === "android" && this.session.videoPath) {
959
- try {
960
- await execAsync(`adb -s ${this.session.deviceId} pull /sdcard/maestro-recording.mp4 "${this.session.videoPath}"`);
961
- await execAsync(`adb -s ${this.session.deviceId} shell rm /sdcard/maestro-recording.mp4`);
962
- } catch (e) {
963
- console.error("Failed to pull video:", e);
964
- }
965
- }
966
- this.videoProcess = null;
967
- }
968
- if (!this.session.flowPath || !fs.existsSync(this.session.flowPath)) {
969
- if (this.session.actions.length > 0) {
970
- const flowYaml = this.generateFlowYaml();
971
- const fallbackFlowPath = path.join(this.session.screenshotsDir, "..", "test.yaml");
972
- await fs.promises.writeFile(fallbackFlowPath, flowYaml);
973
- this.session.flowPath = fallbackFlowPath;
974
- console.log("[MaestroRecorder] Generated flow YAML from recorded actions");
975
- }
976
- }
977
- const metadataPath = path.join(this.session.screenshotsDir, "..", "session.json");
978
- await fs.promises.writeFile(metadataPath, JSON.stringify(this.session, null, 2));
979
- this.clearPendingSession();
980
- this.emit("status", "stopped");
981
- this.emit("stopped", this.session);
982
- const result = this.session;
983
- this.session = null;
984
- return result;
985
- }
986
- /**
987
- * Parse actions from Maestro YAML content
988
- */
989
- parseActionsFromYaml(yamlContent) {
990
- const actions = [];
991
- const lines = yamlContent.split("\n");
992
- let currentAction = null;
993
- let actionIndex = 0;
994
- const nextId = () => `action_${String(++actionIndex).padStart(3, "0")}`;
995
- const cleanValue = (value) => value.trim().replace(/^["']|["']$/g, "");
996
- const pushAction = (action) => {
997
- actions.push({
998
- id: action.id || nextId(),
999
- type: action.type || "tap",
1000
- timestamp: action.timestamp || Date.now(),
1001
- description: action.description || action.type || "Action",
1002
- x: action.x,
1003
- y: action.y,
1004
- endX: action.endX,
1005
- endY: action.endY,
1006
- text: action.text,
1007
- direction: action.direction,
1008
- seconds: action.seconds,
1009
- appId: action.appId,
1010
- duration: action.duration,
1011
- screenshotPath: action.screenshotPath
1012
- });
1013
- };
1014
- for (const line of lines) {
1015
- const trimmed = line.trim();
1016
- if (trimmed.startsWith("#") || trimmed === "" || trimmed === "---") {
1017
- continue;
1018
- }
1019
- if (trimmed.startsWith("appId:")) {
1020
- const parsedAppId = cleanValue(trimmed.replace("appId:", ""));
1021
- if (this.session && parsedAppId && !this.session.appId) {
1022
- this.session.appId = parsedAppId;
1023
- }
1024
- continue;
1025
- }
1026
- if (trimmed.startsWith("- tapOn:")) {
1027
- const inlineValue = cleanValue(trimmed.replace("- tapOn:", ""));
1028
- if (inlineValue) {
1029
- pushAction({
1030
- type: "tap",
1031
- description: `Tap on "${inlineValue}"`,
1032
- text: inlineValue
1033
- });
1034
- continue;
1035
- }
1036
- currentAction = { type: "tap", description: "Tap" };
1037
- } else if (trimmed.startsWith("- tap:")) {
1038
- currentAction = { type: "tap", description: "Tap" };
1039
- } else if (trimmed.startsWith("- swipe:")) {
1040
- currentAction = { type: "swipe", description: "Swipe" };
1041
- } else if (trimmed.startsWith("- scroll:")) {
1042
- currentAction = { type: "scroll", description: "Scroll" };
1043
- } else if (trimmed.startsWith("- scrollUntilVisible:")) {
1044
- currentAction = { type: "scroll", description: "Scroll" };
1045
- } else if (trimmed.startsWith("- inputText:")) {
1046
- const text = cleanValue(trimmed.replace("- inputText:", ""));
1047
- pushAction({
1048
- type: "input",
1049
- description: `Input: ${text.slice(0, 20)}${text.length > 20 ? "..." : ""}`,
1050
- text
1051
- });
1052
- continue;
1053
- } else if (trimmed.startsWith("- launchApp:")) {
1054
- const appId = cleanValue(trimmed.replace("- launchApp:", ""));
1055
- pushAction({
1056
- type: "launch",
1057
- description: `Launch: ${appId}`,
1058
- text: appId,
1059
- appId
1060
- });
1061
- continue;
1062
- } else if (trimmed === "- launchApp") {
1063
- pushAction({
1064
- type: "launch",
1065
- description: "Launch app"
1066
- });
1067
- continue;
1068
- } else if (trimmed.startsWith("- assertVisible:")) {
1069
- const inlineValue = cleanValue(trimmed.replace("- assertVisible:", ""));
1070
- if (inlineValue) {
1071
- pushAction({
1072
- type: "assert",
1073
- description: `Assert visible "${inlineValue}"`,
1074
- text: inlineValue
1075
- });
1076
- continue;
1077
- }
1078
- currentAction = { type: "assert", description: "Assert visible" };
1079
- } else if (trimmed.startsWith("- extendedWaitUntil:")) {
1080
- currentAction = { type: "wait", description: "Wait" };
1081
- } else if (trimmed.startsWith("- pressKey:")) {
1082
- const key = cleanValue(trimmed.replace("- pressKey:", "")).toLowerCase();
1083
- if (key === "back") {
1084
- pushAction({ type: "back", description: "Back button" });
1085
- } else if (key === "home") {
1086
- pushAction({ type: "home", description: "Home button" });
1087
- } else {
1088
- pushAction({
1089
- type: "pressKey",
1090
- description: `Press: ${key}`,
1091
- text: key
1092
- });
1093
- }
1094
- continue;
1095
- } else if (trimmed.startsWith("- back")) {
1096
- pushAction({ type: "back", description: "Back button" });
1097
- continue;
1098
- }
1099
- if (currentAction && trimmed.startsWith("point:")) {
1100
- const point = cleanValue(trimmed.replace("point:", ""));
1101
- const [x, y] = point.split(",").map((n) => parseInt(n.trim()));
1102
- if (!isNaN(x) && !isNaN(y)) {
1103
- currentAction.x = x;
1104
- currentAction.y = y;
1105
- currentAction.description = `Tap at (${x}, ${y})`;
1106
- pushAction(currentAction);
1107
- currentAction = null;
1108
- continue;
1109
- }
1110
- }
1111
- if (currentAction && trimmed.startsWith("text:")) {
1112
- const text = cleanValue(trimmed.replace("text:", ""));
1113
- currentAction.text = text;
1114
- if (currentAction.type === "assert") {
1115
- currentAction.description = `Assert visible "${text}"`;
1116
- } else {
1117
- currentAction.description = `Tap on "${text}"`;
1118
- }
1119
- pushAction(currentAction);
1120
- currentAction = null;
1121
- continue;
1122
- }
1123
- if (currentAction && trimmed.startsWith("id:")) {
1124
- const id = cleanValue(trimmed.replace("id:", ""));
1125
- currentAction.text = id;
1126
- currentAction.description = `Tap on id: ${id}`;
1127
- pushAction(currentAction);
1128
- currentAction = null;
1129
- continue;
1130
- }
1131
- if (currentAction && (currentAction.type === "swipe" || currentAction.type === "scroll") && trimmed.startsWith("direction:")) {
1132
- const direction = cleanValue(trimmed.replace("direction:", "")).toLowerCase();
1133
- currentAction.direction = direction;
1134
- currentAction.description = currentAction.type === "swipe" ? `Swipe ${direction}` : `Scroll ${direction}`;
1135
- pushAction(currentAction);
1136
- currentAction = null;
1137
- continue;
1138
- }
1139
- if (currentAction && currentAction.type === "wait" && trimmed.startsWith("timeout:")) {
1140
- const timeoutMs = parseInt(cleanValue(trimmed.replace("timeout:", "")), 10);
1141
- const seconds = Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.max(1, Math.round(timeoutMs / 1e3)) : 3;
1142
- currentAction.seconds = seconds;
1143
- currentAction.description = `Wait ${seconds}s`;
1144
- pushAction(currentAction);
1145
- currentAction = null;
1146
- continue;
1147
- }
1148
- if (currentAction && currentAction.type === "swipe") {
1149
- if (trimmed.startsWith("start:")) {
1150
- const point = cleanValue(trimmed.replace("start:", ""));
1151
- const [x, y] = point.split(",").map((n) => parseInt(n.trim()));
1152
- if (!isNaN(x) && !isNaN(y)) {
1153
- currentAction.x = x;
1154
- currentAction.y = y;
1155
- }
1156
- } else if (trimmed.startsWith("end:")) {
1157
- const point = cleanValue(trimmed.replace("end:", ""));
1158
- const [x, y] = point.split(",").map((n) => parseInt(n.trim()));
1159
- if (!isNaN(x) && !isNaN(y)) {
1160
- currentAction.endX = x;
1161
- currentAction.endY = y;
1162
- currentAction.description = `Swipe from (${currentAction.x}, ${currentAction.y}) to (${x}, ${y})`;
1163
- pushAction(currentAction);
1164
- currentAction = null;
1165
- }
1166
- }
1167
- }
1168
- }
1169
- return actions;
1170
- }
1171
- mergeParsedActionsWithRecorded(parsedActions, recordedActions) {
1172
- if (parsedActions.length === 0) return recordedActions;
1173
- if (recordedActions.length === 0) return parsedActions;
1174
- const recordedWithScreens = recordedActions.filter((action) => action.screenshotPath);
1175
- if (recordedWithScreens.length === 0) return parsedActions;
1176
- 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";
1177
- let recordedIndex = 0;
1178
- return parsedActions.map((action) => {
1179
- if (!shouldMapScreenshot(action) || recordedIndex >= recordedWithScreens.length) {
1180
- return action;
1181
- }
1182
- const recorded = recordedWithScreens[recordedIndex++];
1183
- return {
1184
- ...recorded,
1185
- ...action,
1186
- id: recorded.id || action.id,
1187
- screenshotPath: recorded.screenshotPath,
1188
- x: action.x ?? recorded.x,
1189
- y: action.y ?? recorded.y,
1190
- endX: action.endX ?? recorded.endX,
1191
- endY: action.endY ?? recorded.endY,
1192
- text: action.text ?? recorded.text,
1193
- direction: action.direction ?? recorded.direction,
1194
- seconds: action.seconds ?? recorded.seconds,
1195
- appId: action.appId ?? recorded.appId,
1196
- duration: action.duration ?? recorded.duration,
1197
- timestamp: recorded.timestamp || action.timestamp,
1198
- description: action.description || recorded.description,
1199
- type: action.type
1200
- };
1201
- });
1202
- }
1203
- /**
1204
- * Generate Maestro YAML from recorded actions
1205
- */
1206
- generateFlowYaml() {
1207
- if (!this.session) return "";
1208
- const escapeYaml = (value) => value.replace(/"/g, '\\"');
1209
- const lines = [
1210
- `# Maestro Flow: ${this.session.name}`,
1211
- `# Recorded: ${new Date(this.session.startedAt).toISOString()}`,
1212
- `# Generated by DiscoveryLab`,
1213
- ``
1214
- ];
1215
- if (this.session.appId) {
1216
- lines.push(`appId: ${this.session.appId}`);
1217
- lines.push(``);
1218
- }
1219
- lines.push(`---`);
1220
- lines.push(``);
1221
- for (const action of this.session.actions) {
1222
- lines.push(`# ${action.description}`);
1223
- switch (action.type) {
1224
- case "tap":
1225
- if (action.text) {
1226
- lines.push(`- tapOn:`);
1227
- lines.push(` text: "${escapeYaml(action.text)}"`);
1228
- } else if (action.x !== void 0 && action.y !== void 0) {
1229
- lines.push(`- tapOn:`);
1230
- lines.push(` point: "${action.x},${action.y}"`);
1231
- }
1232
- break;
1233
- case "swipe":
1234
- if (action.x !== void 0 && action.y !== void 0 && action.endX !== void 0 && action.endY !== void 0) {
1235
- lines.push(`- swipe:`);
1236
- lines.push(` start: "${action.x},${action.y}"`);
1237
- lines.push(` end: "${action.endX},${action.endY}"`);
1238
- if (action.duration) {
1239
- lines.push(` duration: ${action.duration}`);
1240
- }
1241
- } else if (action.direction) {
1242
- lines.push(`- swipe:`);
1243
- lines.push(` direction: "${action.direction.toUpperCase()}"`);
1244
- }
1245
- break;
1246
- case "longPress":
1247
- if (action.x !== void 0 && action.y !== void 0) {
1248
- lines.push(`- longPressOn:`);
1249
- lines.push(` point: "${action.x},${action.y}"`);
1250
- }
1251
- break;
1252
- case "input":
1253
- if (action.text) {
1254
- lines.push(`- inputText: "${escapeYaml(action.text)}"`);
1255
- }
1256
- break;
1257
- case "back":
1258
- lines.push(`- pressKey: back`);
1259
- break;
1260
- case "home":
1261
- lines.push(`- pressKey: home`);
1262
- break;
1263
- case "scroll":
1264
- if (action.direction && action.direction.toLowerCase() === "down") {
1265
- lines.push(`- scrollUntilVisible:`);
1266
- lines.push(` element: ".*"`);
1267
- lines.push(` direction: "DOWN"`);
1268
- } else {
1269
- lines.push(`- scroll`);
1270
- }
1271
- break;
1272
- case "launch": {
1273
- const launchAppId = action.appId || action.text;
1274
- if (launchAppId) {
1275
- lines.push(`- launchApp: "${escapeYaml(launchAppId)}"`);
1276
- if (!this.session.appId) {
1277
- this.session.appId = launchAppId;
1278
- }
1279
- } else {
1280
- lines.push(`- launchApp`);
1281
- }
1282
- break;
1283
- }
1284
- case "assert":
1285
- if (action.text) {
1286
- lines.push(`- assertVisible:`);
1287
- lines.push(` text: "${escapeYaml(action.text)}"`);
1288
- }
1289
- break;
1290
- case "wait": {
1291
- const seconds = action.seconds && action.seconds > 0 ? Math.round(action.seconds) : 3;
1292
- lines.push(`- extendedWaitUntil:`);
1293
- lines.push(` visible: ".*"`);
1294
- lines.push(` timeout: ${seconds * 1e3}`);
1295
- break;
1296
- }
1297
- default:
1298
- lines.push(`# Unknown action: ${action.type}`);
1299
- }
1300
- lines.push(``);
1301
- }
1302
- return lines.join("\n");
1303
- }
1304
- /**
1305
- * Get current session
1306
- */
1307
- getSession() {
1308
- return this.session;
1309
- }
1310
- /**
1311
- * Check if recording is active
1312
- */
1313
- isRecording() {
1314
- return this.session?.status === "recording";
1315
- }
1316
- };
1317
- var maestroRecorderInstance = null;
1318
- function getMaestroRecorder() {
1319
- if (!maestroRecorderInstance) {
1320
- maestroRecorderInstance = new MaestroRecorder();
1321
- }
1322
- return maestroRecorderInstance;
1323
- }
1324
-
1325
- export {
1326
- isMaestroInstalled,
1327
- isIdbInstalled,
1328
- tapViaIdb,
1329
- killZombieMaestroProcesses,
1330
- getMaestroVersion,
1331
- listMaestroDevices,
1332
- generateMaestroFlow,
1333
- runMaestroTest,
1334
- runMaestroWithCapture,
1335
- startMaestroStudio,
1336
- createLoginFlow,
1337
- createOnboardingFlow,
1338
- createNavigationTestFlow,
1339
- getMaestroRecorder
1340
- };