@testrelic/maestro-analytics 1.0.0-next.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs ADDED
@@ -0,0 +1,4078 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ // src/config.ts
5
+ var import_core2 = require("@testrelic/core");
6
+
7
+ // src/cloud-config.ts
8
+ var import_node_fs = require("fs");
9
+ var import_node_path = require("path");
10
+ var import_core = require("@testrelic/core");
11
+ var CONFIG_DIR = ".testrelic";
12
+ var CONFIG_FILENAME = "testrelic-config.json";
13
+ var LEGACY_CONFIG_FILENAME = ".testrelic";
14
+ var MAX_WALK_UP_LEVELS = 5;
15
+ var DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
16
+ var DEFAULT_CLOUD_CONFIG = Object.freeze({
17
+ apiKey: null,
18
+ endpoint: "https://platform.testrelic.ai/api/v1",
19
+ uploadStrategy: "batch",
20
+ timeout: 3e4,
21
+ projectName: null,
22
+ queueMaxAge: 6048e5,
23
+ queueDirectory: `${CONFIG_DIR}/queue`,
24
+ uploadArtifacts: true,
25
+ artifactMaxSizeMb: 50
26
+ });
27
+ var DURATION_UNITS = {
28
+ s: 1e3,
29
+ m: 60 * 1e3,
30
+ h: 60 * 60 * 1e3,
31
+ d: 24 * 60 * 60 * 1e3
32
+ };
33
+ function discoverConfigFile(startDir) {
34
+ let currentDir = (0, import_node_path.resolve)(startDir);
35
+ for (let i = 0; i <= MAX_WALK_UP_LEVELS; i++) {
36
+ const candidate = (0, import_node_path.join)(currentDir, CONFIG_DIR, CONFIG_FILENAME);
37
+ if ((0, import_node_fs.existsSync)(candidate)) {
38
+ try {
39
+ if ((0, import_node_fs.statSync)(candidate).isFile()) return candidate;
40
+ } catch {
41
+ }
42
+ }
43
+ const legacyCandidate = (0, import_node_path.join)(currentDir, LEGACY_CONFIG_FILENAME);
44
+ if ((0, import_node_fs.existsSync)(legacyCandidate)) {
45
+ try {
46
+ if ((0, import_node_fs.statSync)(legacyCandidate).isFile()) {
47
+ process.stderr.write(
48
+ '[testrelic] Deprecation: config file ".testrelic" has moved to ".testrelic/testrelic-config.json". Please migrate your config file to the new location.\n'
49
+ );
50
+ return legacyCandidate;
51
+ }
52
+ } catch {
53
+ }
54
+ }
55
+ const parentDir = (0, import_node_path.dirname)(currentDir);
56
+ if (parentDir === currentDir) break;
57
+ currentDir = parentDir;
58
+ }
59
+ return null;
60
+ }
61
+ function parseConfigFile(filePath) {
62
+ try {
63
+ const content = (0, import_node_fs.readFileSync)(filePath, "utf-8");
64
+ const parsed = JSON.parse(content);
65
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
66
+ return null;
67
+ }
68
+ if (!isSafeObject(parsed)) {
69
+ return null;
70
+ }
71
+ return parsed;
72
+ } catch {
73
+ return null;
74
+ }
75
+ }
76
+ function isSafeObject(obj) {
77
+ for (const key of Object.keys(obj)) {
78
+ if (DANGEROUS_KEYS.has(key)) return false;
79
+ const val = obj[key];
80
+ if (typeof val === "object" && val !== null && !Array.isArray(val)) {
81
+ if (!isSafeObject(val)) return false;
82
+ }
83
+ }
84
+ return true;
85
+ }
86
+ function resolveEnvVar(value) {
87
+ const bracketMatch = /^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(value);
88
+ if (bracketMatch) {
89
+ return process.env[bracketMatch[1]] ?? null;
90
+ }
91
+ const dollarMatch = /^\$([A-Za-z_][A-Za-z0-9_]*)$/.exec(value);
92
+ if (dollarMatch) {
93
+ return process.env[dollarMatch[1]] ?? null;
94
+ }
95
+ return value;
96
+ }
97
+ function resolveEnvVars(obj) {
98
+ const result = /* @__PURE__ */ Object.create(null);
99
+ for (const key of Object.keys(obj)) {
100
+ const val = obj[key];
101
+ if (typeof val === "string" && val.startsWith("$")) {
102
+ result[key] = resolveEnvVar(val);
103
+ } else if (typeof val === "object" && val !== null && !Array.isArray(val)) {
104
+ result[key] = resolveEnvVars(val);
105
+ } else {
106
+ result[key] = val;
107
+ }
108
+ }
109
+ return result;
110
+ }
111
+ function parseDuration(value) {
112
+ const match = /^(\d+)\s*([smhd])$/.exec(value.trim());
113
+ if (!match) return null;
114
+ const amount = parseInt(match[1], 10);
115
+ const unit = match[2];
116
+ const multiplier = DURATION_UNITS[unit];
117
+ if (!multiplier || amount <= 0) return null;
118
+ return amount * multiplier;
119
+ }
120
+ function mergeCloudConfig(fileConfig, reporterOptions) {
121
+ const target = /* @__PURE__ */ Object.create(null);
122
+ Object.assign(target, DEFAULT_CLOUD_CONFIG);
123
+ if (fileConfig) {
124
+ const cloud = fileConfig.cloud;
125
+ if (cloud && typeof cloud === "object") {
126
+ if (typeof cloud.endpoint === "string") target.endpoint = cloud.endpoint;
127
+ if (typeof cloud.upload === "string") target.uploadStrategy = cloud.upload;
128
+ if (typeof cloud.timeout === "number") target.timeout = cloud.timeout;
129
+ if (typeof cloud.apiKey === "string" && cloud.apiKey.length > 0) {
130
+ target.apiKey = cloud.apiKey;
131
+ }
132
+ }
133
+ const repoSection = fileConfig["testrelic-repo"] ?? fileConfig.project;
134
+ if (repoSection && typeof repoSection === "object") {
135
+ if (typeof repoSection.name === "string") target.projectName = repoSection.name;
136
+ }
137
+ const queue = fileConfig.queue;
138
+ if (queue && typeof queue === "object") {
139
+ if (typeof queue.maxAge === "string") {
140
+ const ms = parseDuration(queue.maxAge);
141
+ if (ms !== null) target.queueMaxAge = ms;
142
+ }
143
+ if (typeof queue.directory === "string") target.queueDirectory = queue.directory;
144
+ }
145
+ }
146
+ if (reporterOptions) {
147
+ if (typeof reporterOptions.apiKey === "string" && reporterOptions.apiKey.length > 0) {
148
+ const resolved = reporterOptions.apiKey.startsWith("$") ? resolveEnvVar(reporterOptions.apiKey) : reporterOptions.apiKey;
149
+ if (resolved) target.apiKey = resolved;
150
+ }
151
+ if (typeof reporterOptions.endpoint === "string") {
152
+ const resolved = reporterOptions.endpoint.startsWith("$") ? resolveEnvVar(reporterOptions.endpoint) : reporterOptions.endpoint;
153
+ if (resolved) target.endpoint = resolved;
154
+ }
155
+ if (typeof reporterOptions.upload === "string") target.uploadStrategy = reporterOptions.upload;
156
+ if (typeof reporterOptions.timeout === "number") target.timeout = reporterOptions.timeout;
157
+ if (typeof reporterOptions.projectName === "string") target.projectName = reporterOptions.projectName;
158
+ if (typeof reporterOptions.queueMaxAge === "string") {
159
+ const ms = parseDuration(reporterOptions.queueMaxAge);
160
+ if (ms !== null) target.queueMaxAge = ms;
161
+ }
162
+ if (typeof reporterOptions.queueDirectory === "string") target.queueDirectory = reporterOptions.queueDirectory;
163
+ if (typeof reporterOptions.uploadArtifacts === "boolean") target.uploadArtifacts = reporterOptions.uploadArtifacts;
164
+ if (typeof reporterOptions.artifactMaxSizeMb === "number") target.artifactMaxSizeMb = reporterOptions.artifactMaxSizeMb;
165
+ }
166
+ const envApiKey = process.env.TESTRELIC_API_KEY;
167
+ if (envApiKey && envApiKey.length > 0) {
168
+ target.apiKey = envApiKey;
169
+ }
170
+ const envEndpoint = process.env.TESTRELIC_CLOUD_ENDPOINT;
171
+ if (envEndpoint && (0, import_core.isValidEndpointUrl)(envEndpoint)) {
172
+ target.endpoint = envEndpoint;
173
+ }
174
+ const envUpload = process.env.TESTRELIC_UPLOAD_STRATEGY;
175
+ if (envUpload && ["batch", "realtime", "both"].includes(envUpload)) {
176
+ target.uploadStrategy = envUpload;
177
+ }
178
+ const envTimeout = process.env.TESTRELIC_CLOUD_TIMEOUT;
179
+ if (envTimeout) {
180
+ const parsed = parseInt(envTimeout, 10);
181
+ if (!isNaN(parsed) && parsed >= 1e3 && parsed <= 12e4) {
182
+ target.timeout = parsed;
183
+ }
184
+ }
185
+ const config = Object.freeze(target);
186
+ if (!(0, import_core.isValidCloudConfig)(config)) {
187
+ return DEFAULT_CLOUD_CONFIG;
188
+ }
189
+ return config;
190
+ }
191
+
192
+ // src/config.ts
193
+ var DANGEROUS_KEYS2 = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
194
+ function hasPrototypePollution(obj) {
195
+ if (typeof obj !== "object" || obj === null) return false;
196
+ for (const key of Object.keys(obj)) {
197
+ if (DANGEROUS_KEYS2.has(key)) return true;
198
+ }
199
+ return false;
200
+ }
201
+ function isValidMaestroConfig(input) {
202
+ if (typeof input !== "object" || input === null) return false;
203
+ if (hasPrototypePollution(input)) return false;
204
+ const obj = input;
205
+ if (obj.outputPath !== void 0 && typeof obj.outputPath !== "string") return false;
206
+ if (obj.htmlReportPath !== void 0 && typeof obj.htmlReportPath !== "string") return false;
207
+ if (obj.openReport !== void 0 && typeof obj.openReport !== "boolean") return false;
208
+ if (obj.includeScreenshots !== void 0 && typeof obj.includeScreenshots !== "boolean") return false;
209
+ if (obj.includeVideo !== void 0 && typeof obj.includeVideo !== "boolean") return false;
210
+ if (obj.includeAiAnalysis !== void 0 && typeof obj.includeAiAnalysis !== "boolean") return false;
211
+ if (obj.includeLogs !== void 0 && typeof obj.includeLogs !== "boolean") return false;
212
+ if (obj.includeFlowMetadata !== void 0 && typeof obj.includeFlowMetadata !== "boolean") return false;
213
+ if (obj.quiet !== void 0 && typeof obj.quiet !== "boolean") return false;
214
+ if (obj.metadata !== void 0 && obj.metadata !== null) {
215
+ if (typeof obj.metadata !== "object") return false;
216
+ if (hasPrototypePollution(obj.metadata)) return false;
217
+ }
218
+ return true;
219
+ }
220
+ function resolveConfig(options) {
221
+ if (options !== void 0 && !isValidMaestroConfig(options)) {
222
+ throw (0, import_core2.createError)(import_core2.ErrorCode.CONFIG_INVALID, "Invalid Maestro reporter configuration");
223
+ }
224
+ const target = /* @__PURE__ */ Object.create(null);
225
+ const outputPath = options?.outputPath ?? "./test-results/testrelic-maestro.json";
226
+ target.outputPath = outputPath;
227
+ target.htmlReportPath = options?.htmlReportPath ?? outputPath.replace(/\.json$/, ".html");
228
+ target.openReport = options?.openReport ?? true;
229
+ target.includeScreenshots = options?.includeScreenshots ?? true;
230
+ target.includeVideo = options?.includeVideo ?? true;
231
+ target.includeAiAnalysis = options?.includeAiAnalysis ?? true;
232
+ target.includeLogs = options?.includeLogs ?? true;
233
+ target.includeFlowMetadata = options?.includeFlowMetadata ?? true;
234
+ target.flowsDir = options?.flowsDir ?? null;
235
+ target.testRunId = options?.testRunId ?? null;
236
+ target.metadata = options?.metadata ?? null;
237
+ target.quiet = options?.quiet ?? false;
238
+ target.reportMode = options?.reportMode ?? "batch";
239
+ target.cloud = resolveCloudFromMerge(options?.cloud ?? null);
240
+ return Object.freeze(target);
241
+ }
242
+ function resolveCloudFromMerge(reporterOptions) {
243
+ const configPath = discoverConfigFile(process.cwd());
244
+ const fileConfig = configPath ? parseConfigFile(configPath) : null;
245
+ const resolvedFile = fileConfig ? resolveEnvVars(fileConfig) : null;
246
+ const merged = mergeCloudConfig(
247
+ resolvedFile,
248
+ reporterOptions ?? void 0
249
+ );
250
+ return merged.apiKey ? merged : null;
251
+ }
252
+
253
+ // src/maestro-runner.ts
254
+ var import_node_child_process = require("child_process");
255
+ var import_node_fs2 = require("fs");
256
+ var import_node_path2 = require("path");
257
+ var import_node_os = require("os");
258
+ var import_node_crypto = require("crypto");
259
+ function generateTempDir() {
260
+ const id = (0, import_node_crypto.randomBytes)(8).toString("hex");
261
+ return (0, import_node_path2.join)((0, import_node_os.tmpdir)(), `testrelic-maestro-${id}`);
262
+ }
263
+ function buildMaestroArgs(options, tempDir) {
264
+ const args = [];
265
+ if (options.platform) {
266
+ args.push("--platform", options.platform);
267
+ }
268
+ if (options.device) {
269
+ args.push("--device", options.device);
270
+ }
271
+ args.push("test");
272
+ const junitPath = (0, import_node_path2.join)(tempDir, "report.xml");
273
+ const testOutputDir = (0, import_node_path2.join)(tempDir, "artifacts");
274
+ const debugOutputDir = (0, import_node_path2.join)(tempDir, "debug");
275
+ args.push("--format", "junit");
276
+ args.push("--output", junitPath);
277
+ args.push("--test-output-dir", testOutputDir);
278
+ args.push("--debug-output", debugOutputDir);
279
+ if (options.analyze) {
280
+ args.push("--analyze");
281
+ }
282
+ if (options.includeTags) {
283
+ args.push("--include-tags", options.includeTags);
284
+ }
285
+ if (options.excludeTags) {
286
+ args.push("--exclude-tags", options.excludeTags);
287
+ }
288
+ if (options.shards && options.shards > 1) {
289
+ args.push("--shards", String(options.shards));
290
+ }
291
+ if (options.config) {
292
+ args.push("--config", options.config);
293
+ }
294
+ if (options.env) {
295
+ for (const [key, value] of Object.entries(options.env)) {
296
+ args.push("-e", `${key}=${value}`);
297
+ }
298
+ }
299
+ if (options.maestroArgs) {
300
+ args.push(...options.maestroArgs);
301
+ }
302
+ args.push(...options.flowPaths);
303
+ return args;
304
+ }
305
+ async function runMaestro(options) {
306
+ const tempDir = options.outputDir ? (0, import_node_path2.resolve)(options.outputDir) : generateTempDir();
307
+ (0, import_node_fs2.mkdirSync)((0, import_node_path2.join)(tempDir, "artifacts"), { recursive: true });
308
+ (0, import_node_fs2.mkdirSync)((0, import_node_path2.join)(tempDir, "debug"), { recursive: true });
309
+ const args = buildMaestroArgs(options, tempDir);
310
+ const junitPath = (0, import_node_path2.join)(tempDir, "report.xml");
311
+ const testOutputDir = (0, import_node_path2.join)(tempDir, "artifacts");
312
+ const debugOutputDir = (0, import_node_path2.join)(tempDir, "debug");
313
+ return new Promise((resolvePromise) => {
314
+ const stdoutChunks = [];
315
+ const stderrChunks = [];
316
+ const proc = (0, import_node_child_process.spawn)("maestro", args, {
317
+ stdio: ["inherit", "pipe", "pipe"],
318
+ shell: true
319
+ });
320
+ proc.stdout.on("data", (chunk) => {
321
+ stdoutChunks.push(chunk);
322
+ if (!options.quiet) process.stdout.write(chunk);
323
+ });
324
+ proc.stderr.on("data", (chunk) => {
325
+ stderrChunks.push(chunk);
326
+ if (!options.quiet) process.stderr.write(chunk);
327
+ });
328
+ proc.on("close", (code) => {
329
+ resolvePromise({
330
+ exitCode: code ?? 1,
331
+ junitPath,
332
+ testOutputDir,
333
+ debugOutputDir,
334
+ stdout: Buffer.concat(stdoutChunks).toString("utf-8"),
335
+ stderr: Buffer.concat(stderrChunks).toString("utf-8")
336
+ });
337
+ });
338
+ proc.on("error", (err) => {
339
+ resolvePromise({
340
+ exitCode: 127,
341
+ junitPath,
342
+ testOutputDir,
343
+ debugOutputDir,
344
+ stdout: "",
345
+ stderr: `Failed to start maestro CLI: ${err.message}`
346
+ });
347
+ });
348
+ });
349
+ }
350
+
351
+ // src/report-orchestrator.ts
352
+ var import_node_fs15 = require("fs");
353
+ var import_node_path13 = require("path");
354
+ var import_node_crypto3 = require("crypto");
355
+
356
+ // src/parsers/junit-parser.ts
357
+ var import_fast_xml_parser = require("fast-xml-parser");
358
+ var import_node_fs3 = require("fs");
359
+ var parser = new import_fast_xml_parser.XMLParser({
360
+ ignoreAttributes: false,
361
+ attributeNamePrefix: "@_",
362
+ allowBooleanAttributes: true,
363
+ parseAttributeValue: true,
364
+ trimValues: true
365
+ });
366
+ function toArray(value) {
367
+ if (value === void 0 || value === null) return [];
368
+ return Array.isArray(value) ? value : [value];
369
+ }
370
+ function parseProperties(raw) {
371
+ if (!raw || typeof raw !== "object") return [];
372
+ const container = raw;
373
+ const props = toArray(container.property);
374
+ return props.map((p) => ({
375
+ name: String(p["@_name"] ?? ""),
376
+ value: String(p["@_value"] ?? "")
377
+ }));
378
+ }
379
+ function parseTestCase(raw) {
380
+ const name = String(raw["@_name"] ?? "unnamed");
381
+ const classname = String(raw["@_classname"] ?? name);
382
+ const time = Number(raw["@_time"] ?? 0);
383
+ const id = raw["@_id"] != null ? String(raw["@_id"]) : null;
384
+ const rawStatus = String(raw["@_status"] ?? "").toUpperCase();
385
+ const failure = raw.failure;
386
+ const error = raw.error;
387
+ const skipped = raw.skipped !== void 0;
388
+ let status = "SUCCESS";
389
+ if (failure) status = "FAILURE";
390
+ else if (error) status = "ERROR";
391
+ else if (skipped) status = "SKIPPED";
392
+ else if (rawStatus === "FAILURE" || rawStatus === "FAILED") status = "FAILURE";
393
+ else if (rawStatus === "ERROR") status = "ERROR";
394
+ else if (rawStatus === "SKIPPED") status = "SKIPPED";
395
+ return {
396
+ id,
397
+ name,
398
+ classname,
399
+ time,
400
+ status,
401
+ failureMessage: failure ? String(failure["@_message"] ?? failure["#text"] ?? "") : null,
402
+ failureType: failure ? String(failure["@_type"] ?? "") : null,
403
+ errorMessage: error ? String(error["@_message"] ?? error["#text"] ?? "") : null,
404
+ errorType: error ? String(error["@_type"] ?? "") : null,
405
+ properties: parseProperties(raw.properties)
406
+ };
407
+ }
408
+ function parseTestSuite(raw) {
409
+ const name = String(raw["@_name"] ?? "Test Suite");
410
+ const device = raw["@_device"] != null ? String(raw["@_device"]) : null;
411
+ const tests = Number(raw["@_tests"] ?? 0);
412
+ const failures = Number(raw["@_failures"] ?? 0);
413
+ const errors = Number(raw["@_errors"] ?? 0);
414
+ const skipped = Number(raw["@_skipped"] ?? 0);
415
+ const time = Number(raw["@_time"] ?? 0);
416
+ const rawCases = toArray(raw.testcase);
417
+ const testCases = rawCases.map(parseTestCase);
418
+ return {
419
+ name,
420
+ device,
421
+ tests,
422
+ failures,
423
+ errors,
424
+ skipped,
425
+ time,
426
+ testCases,
427
+ properties: parseProperties(raw.properties)
428
+ };
429
+ }
430
+ function parseJUnitXml(xmlContent) {
431
+ const parsed = parser.parse(xmlContent);
432
+ let suites = [];
433
+ if (parsed.testsuites) {
434
+ const container = parsed.testsuites;
435
+ const rawSuites = toArray(container.testsuite);
436
+ suites = rawSuites.map(parseTestSuite);
437
+ } else if (parsed.testsuite) {
438
+ const rawSuites = toArray(parsed.testsuite);
439
+ suites = rawSuites.map(parseTestSuite);
440
+ }
441
+ let totalTests = 0;
442
+ let totalFailures = 0;
443
+ let totalErrors = 0;
444
+ let totalSkipped = 0;
445
+ let totalTime = 0;
446
+ for (const suite of suites) {
447
+ totalTests += suite.tests;
448
+ totalFailures += suite.failures;
449
+ totalErrors += suite.errors;
450
+ totalSkipped += suite.skipped;
451
+ totalTime += suite.time;
452
+ }
453
+ return { testSuites: suites, totalTests, totalFailures, totalErrors, totalSkipped, totalTime };
454
+ }
455
+ function parseJUnitFile(filePath) {
456
+ const content = (0, import_node_fs3.readFileSync)(filePath, "utf-8");
457
+ return parseJUnitXml(content);
458
+ }
459
+
460
+ // src/parsers/command-parser.ts
461
+ var import_node_fs4 = require("fs");
462
+ var import_node_path3 = require("path");
463
+ var INTERACTION_COMMANDS = /* @__PURE__ */ new Set([
464
+ "tapOn",
465
+ "doubleTapOn",
466
+ "longPressOn",
467
+ "inputText",
468
+ "eraseText",
469
+ "pasteText",
470
+ "swipe",
471
+ "scroll",
472
+ "scrollUntilVisible",
473
+ "hideKeyboard",
474
+ "pressKey",
475
+ "setClipboard",
476
+ "copyTextFrom"
477
+ ]);
478
+ var ASSERTION_COMMANDS = /* @__PURE__ */ new Set([
479
+ "assertVisible",
480
+ "assertNotVisible",
481
+ "assertTrue",
482
+ "assertScreenshot",
483
+ "assertNoDefectsWithAI",
484
+ "assertWithAI",
485
+ // Maestro internal command name used for assertVisible/assertNotVisible
486
+ "assertCondition"
487
+ ]);
488
+ var NAVIGATION_COMMANDS = /* @__PURE__ */ new Set([
489
+ "launchApp",
490
+ "killApp",
491
+ "stopApp",
492
+ "clearState",
493
+ "openLink",
494
+ "back",
495
+ "clearKeychain"
496
+ ]);
497
+ var DEVICE_COMMANDS = /* @__PURE__ */ new Set([
498
+ "setAirplaneMode",
499
+ "toggleAirplaneMode",
500
+ "setLocation",
501
+ "setOrientation",
502
+ "setPermissions",
503
+ "addMedia",
504
+ "travel"
505
+ ]);
506
+ var MEDIA_COMMANDS = /* @__PURE__ */ new Set([
507
+ "takeScreenshot",
508
+ "startRecording",
509
+ "stopRecording"
510
+ ]);
511
+ var SCRIPT_COMMANDS = /* @__PURE__ */ new Set([
512
+ "runScript",
513
+ "evalScript"
514
+ ]);
515
+ var FLOW_CONTROL_COMMANDS = /* @__PURE__ */ new Set([
516
+ "runFlow",
517
+ "repeat",
518
+ "retry",
519
+ "waitForAnimationToEnd",
520
+ "extendedWaitUntil"
521
+ ]);
522
+ var AI_COMMANDS = /* @__PURE__ */ new Set([
523
+ "assertWithAI",
524
+ "assertNoDefectsWithAI",
525
+ "extractTextWithAI"
526
+ ]);
527
+ function categorizeCommand(command) {
528
+ if (AI_COMMANDS.has(command)) return "ai";
529
+ if (ASSERTION_COMMANDS.has(command)) return "assertion";
530
+ if (INTERACTION_COMMANDS.has(command)) return "interaction";
531
+ if (NAVIGATION_COMMANDS.has(command)) return "navigation";
532
+ if (DEVICE_COMMANDS.has(command)) return "device";
533
+ if (MEDIA_COMMANDS.has(command)) return "media";
534
+ if (SCRIPT_COMMANDS.has(command)) return "script";
535
+ if (FLOW_CONTROL_COMMANDS.has(command)) return "flow_control";
536
+ return "other";
537
+ }
538
+ var MAESTRO_COMMAND_NAME_MAP = {
539
+ tapOnElement: "tapOn",
540
+ assertCondition: "assertVisible",
541
+ backPress: "back",
542
+ applyConfiguration: "applyConfiguration",
543
+ defineVariables: "defineVariables"
544
+ };
545
+ function normalizeMaestroCommandName(key) {
546
+ const withoutSuffix = key.replace(/Command$/, "");
547
+ return MAESTRO_COMMAND_NAME_MAP[withoutSuffix] ?? withoutSuffix;
548
+ }
549
+ function extractMaestroSelector(params) {
550
+ if (params.selector && typeof params.selector === "object") {
551
+ const sel = params.selector;
552
+ if (typeof sel.textRegex === "string") return sel.textRegex;
553
+ if (typeof sel.text === "string") return sel.text;
554
+ if (typeof sel.id === "string") return `#${sel.id}`;
555
+ }
556
+ if (params.condition && typeof params.condition === "object") {
557
+ const cond = params.condition;
558
+ const inner = cond.visible ?? cond.notVisible;
559
+ if (inner) {
560
+ if (typeof inner.textRegex === "string") return inner.textRegex;
561
+ if (typeof inner.text === "string") return inner.text;
562
+ }
563
+ }
564
+ if (typeof params.path === "string") return params.path;
565
+ return void 0;
566
+ }
567
+ function parseRawCommand(raw, index, baseTimestamp) {
568
+ let command;
569
+ let selector;
570
+ if (typeof raw.command === "object" && raw.command !== null && !Array.isArray(raw.command)) {
571
+ const commandObj = raw.command;
572
+ const rawKey = Object.keys(commandObj)[0] ?? `step-${index}`;
573
+ command = normalizeMaestroCommandName(rawKey);
574
+ const params = commandObj[rawKey] ?? {};
575
+ selector = extractMaestroSelector(params);
576
+ } else {
577
+ command = raw.command ?? raw.commandName ?? raw.name ?? `step-${index}`;
578
+ selector = raw.selector ?? void 0;
579
+ }
580
+ const meta = raw.metadata ?? {};
581
+ const status = mapStatus(meta.status ?? raw.status);
582
+ const duration = meta.duration ?? raw.duration ?? raw.durationMs ?? 0;
583
+ let timestamp;
584
+ if (typeof meta.timestamp === "number") {
585
+ timestamp = new Date(meta.timestamp).toISOString();
586
+ } else {
587
+ timestamp = raw.timestamp ?? raw.time ?? baseTimestamp;
588
+ }
589
+ const error = raw.error ?? raw.errorMessage ?? void 0;
590
+ return {
591
+ command,
592
+ category: categorizeCommand(command),
593
+ status,
594
+ duration,
595
+ timestamp,
596
+ ...selector ? { selector } : {},
597
+ ...error ? { error } : {}
598
+ };
599
+ }
600
+ function mapStatus(status) {
601
+ if (!status) return "completed";
602
+ const lower = status.toLowerCase();
603
+ if (lower === "failed" || lower === "error") return "failed";
604
+ if (lower === "skipped") return "skipped";
605
+ return "completed";
606
+ }
607
+ function parseCommandsJson(jsonContent, baseTimestamp) {
608
+ const base = baseTimestamp ?? (/* @__PURE__ */ new Date()).toISOString();
609
+ try {
610
+ const parsed = JSON.parse(jsonContent);
611
+ if (Array.isArray(parsed)) {
612
+ return parsed.map((entry, i) => parseRawCommand(entry, i, base));
613
+ }
614
+ if (typeof parsed === "object" && parsed !== null) {
615
+ const obj = parsed;
616
+ const commands = obj.commands ?? obj.steps ?? obj.data;
617
+ if (Array.isArray(commands)) {
618
+ return commands.map((entry, i) => parseRawCommand(entry, i, base));
619
+ }
620
+ }
621
+ return [];
622
+ } catch {
623
+ return [];
624
+ }
625
+ }
626
+ function parseCommandsFile(filePath, baseTimestamp) {
627
+ try {
628
+ const content = (0, import_node_fs4.readFileSync)(filePath, "utf-8");
629
+ return parseCommandsJson(content, baseTimestamp);
630
+ } catch {
631
+ return [];
632
+ }
633
+ }
634
+ function discoverCommandFiles(artifactsDir) {
635
+ if (!(0, import_node_fs4.existsSync)(artifactsDir)) return [];
636
+ try {
637
+ return (0, import_node_fs4.readdirSync)(artifactsDir, { recursive: true }).map(String).filter((f) => (0, import_node_path3.basename)(f).startsWith("commands") && f.endsWith(".json")).map((f) => (0, import_node_path3.join)(artifactsDir, f));
638
+ } catch {
639
+ return [];
640
+ }
641
+ }
642
+
643
+ // src/parsers/flow-parser.ts
644
+ var import_node_fs5 = require("fs");
645
+ var import_node_path4 = require("path");
646
+ var import_yaml = require("yaml");
647
+ function extractSubflowRefs(body) {
648
+ const refs = [];
649
+ for (const item of body) {
650
+ if (typeof item === "object" && item !== null) {
651
+ const entry = item;
652
+ if (typeof entry.runFlow === "string") {
653
+ refs.push(entry.runFlow);
654
+ } else if (typeof entry.runFlow === "object" && entry.runFlow !== null) {
655
+ const flow = entry.runFlow;
656
+ if (typeof flow.file === "string") refs.push(flow.file);
657
+ }
658
+ }
659
+ }
660
+ return refs;
661
+ }
662
+ function extractHookRefs(hooks) {
663
+ if (!hooks) return [];
664
+ const refs = [];
665
+ const items = Array.isArray(hooks) ? hooks : [hooks];
666
+ for (const item of items) {
667
+ if (typeof item === "string") {
668
+ refs.push(item);
669
+ } else if (typeof item === "object" && item !== null) {
670
+ const entry = item;
671
+ if (typeof entry.runFlow === "string") refs.push(entry.runFlow);
672
+ else if (typeof entry.runFlow === "object" && entry.runFlow !== null) {
673
+ const flow = entry.runFlow;
674
+ if (typeof flow.file === "string") refs.push(flow.file);
675
+ }
676
+ if (typeof entry.runScript === "string") refs.push(entry.runScript);
677
+ }
678
+ }
679
+ return refs;
680
+ }
681
+ function parseFlowYaml(content, filePath) {
682
+ const parts = content.split(/^---\s*$/m, 2);
683
+ const headerContent = parts[0] ?? "";
684
+ const bodyContent = parts[1] ?? "";
685
+ let header = {};
686
+ try {
687
+ const doc = (0, import_yaml.parseDocument)(headerContent);
688
+ const parsed = doc.toJS();
689
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
690
+ header = parsed;
691
+ }
692
+ } catch {
693
+ }
694
+ let bodyCommands = [];
695
+ if (bodyContent.trim()) {
696
+ try {
697
+ const bodyDoc = (0, import_yaml.parseDocument)(bodyContent);
698
+ const parsed = bodyDoc.toJS();
699
+ if (Array.isArray(parsed)) bodyCommands = parsed;
700
+ } catch {
701
+ }
702
+ }
703
+ const appId = typeof header.appId === "string" ? header.appId : null;
704
+ const name = typeof header.name === "string" ? header.name : null;
705
+ const tags = [];
706
+ if (Array.isArray(header.tags)) {
707
+ for (const t of header.tags) {
708
+ if (typeof t === "string") tags.push(t);
709
+ }
710
+ }
711
+ const env = {};
712
+ if (typeof header.env === "object" && header.env !== null && !Array.isArray(header.env)) {
713
+ for (const [k, v] of Object.entries(header.env)) {
714
+ env[k] = String(v);
715
+ }
716
+ }
717
+ const properties = {};
718
+ if (typeof header.properties === "object" && header.properties !== null && !Array.isArray(header.properties)) {
719
+ for (const [k, v] of Object.entries(header.properties)) {
720
+ properties[k] = String(v);
721
+ }
722
+ }
723
+ const onFlowStart = extractHookRefs(header.onFlowStart);
724
+ const onFlowComplete = extractHookRefs(header.onFlowComplete);
725
+ const subflowRefs = extractSubflowRefs(bodyCommands);
726
+ return {
727
+ appId,
728
+ name,
729
+ tags,
730
+ env,
731
+ properties,
732
+ onFlowStart,
733
+ onFlowComplete,
734
+ subflowRefs,
735
+ filePath
736
+ };
737
+ }
738
+ function parseFlowFile(filePath) {
739
+ const content = (0, import_node_fs5.readFileSync)(filePath, "utf-8");
740
+ return parseFlowYaml(content, filePath);
741
+ }
742
+ function discoverFlowFiles(dir) {
743
+ if (!(0, import_node_fs5.existsSync)(dir)) return [];
744
+ const results = [];
745
+ function walk(currentDir) {
746
+ try {
747
+ const entries = (0, import_node_fs5.readdirSync)(currentDir, { withFileTypes: true });
748
+ for (const entry of entries) {
749
+ const fullPath = (0, import_node_path4.join)(currentDir, entry.name);
750
+ if (entry.isDirectory()) {
751
+ walk(fullPath);
752
+ } else if (entry.isFile()) {
753
+ const ext = (0, import_node_path4.extname)(entry.name).toLowerCase();
754
+ if (ext === ".yaml" || ext === ".yml") {
755
+ results.push(fullPath);
756
+ }
757
+ }
758
+ }
759
+ } catch {
760
+ }
761
+ }
762
+ walk(dir);
763
+ return results;
764
+ }
765
+
766
+ // src/parsers/log-parser.ts
767
+ var import_node_fs6 = require("fs");
768
+ var import_node_path5 = require("path");
769
+ var import_node_fs7 = require("fs");
770
+ var LOG_LINE_REGEX = /^(\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?)\s+(\w+)\s+(.+)$/;
771
+ var TIMESTAMP_ONLY_REGEX = /^\[?(\d{2}:\d{2}:\d{2}(?:\.\d+)?)\]?\s+(\w+)\s+(.+)$/;
772
+ function parseLevel(raw) {
773
+ const upper = raw.toUpperCase();
774
+ if (upper === "DEBUG" || upper === "TRACE" || upper === "VERBOSE") return "DEBUG";
775
+ if (upper === "INFO") return "INFO";
776
+ if (upper === "WARN" || upper === "WARNING") return "WARN";
777
+ if (upper === "ERROR" || upper === "FATAL" || upper === "SEVERE") return "ERROR";
778
+ return "INFO";
779
+ }
780
+ function parseLogContent(content) {
781
+ const entries = [];
782
+ const lines = content.split("\n");
783
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
784
+ for (const line2 of lines) {
785
+ const trimmed = line2.trim();
786
+ if (!trimmed) continue;
787
+ let match = LOG_LINE_REGEX.exec(trimmed);
788
+ if (match) {
789
+ entries.push({
790
+ timestamp: match[1],
791
+ level: parseLevel(match[2]),
792
+ message: match[3],
793
+ source: null
794
+ });
795
+ continue;
796
+ }
797
+ match = TIMESTAMP_ONLY_REGEX.exec(trimmed);
798
+ if (match) {
799
+ entries.push({
800
+ timestamp: `${today}T${match[1]}`,
801
+ level: parseLevel(match[2]),
802
+ message: match[3],
803
+ source: null
804
+ });
805
+ continue;
806
+ }
807
+ if (entries.length > 0) {
808
+ const last = entries[entries.length - 1];
809
+ entries[entries.length - 1] = {
810
+ ...last,
811
+ message: last.message + "\n" + trimmed
812
+ };
813
+ }
814
+ }
815
+ return entries;
816
+ }
817
+ function parseLogFile(filePath) {
818
+ try {
819
+ const content = (0, import_node_fs6.readFileSync)(filePath, "utf-8");
820
+ return parseLogContent(content);
821
+ } catch {
822
+ return [];
823
+ }
824
+ }
825
+ function detectPlatformFromLogs(entries) {
826
+ for (const entry of entries) {
827
+ const msg = entry.message.toLowerCase();
828
+ if (msg.includes("android") || msg.includes("adb") || msg.includes("uiautomator") || msg.includes("emulator")) {
829
+ return "android";
830
+ }
831
+ if (msg.includes("ios") || msg.includes("xcuitest") || msg.includes("simulator") || msg.includes("xctest")) {
832
+ return "ios";
833
+ }
834
+ if (msg.includes("web driver") || msg.includes("chrome") || msg.includes("chromium")) {
835
+ return "web";
836
+ }
837
+ }
838
+ return "unknown";
839
+ }
840
+ function discoverLogFiles(dir) {
841
+ if (!(0, import_node_fs6.existsSync)(dir)) return [];
842
+ try {
843
+ return (0, import_node_fs7.readdirSync)(dir, { recursive: true }).map(String).filter((f) => (0, import_node_path5.basename)(f) === "maestro.log" || f.endsWith(".log")).map((f) => (0, import_node_path5.join)(dir, f));
844
+ } catch {
845
+ return [];
846
+ }
847
+ }
848
+
849
+ // src/parsers/ai-report-parser.ts
850
+ var import_node_fs8 = require("fs");
851
+ var import_node_path6 = require("path");
852
+ var DEFECT_SECTION_REGEX = /(?:defect|issue|bug|error|warning|problem)/i;
853
+ var SEVERITY_CRITICAL_REGEX = /(?:critical|severe|major|blocker)/i;
854
+ var SEVERITY_WARNING_REGEX = /(?:warning|moderate|minor)/i;
855
+ var UI_DEFECT_REGEX = /(?:cut[\s-]?off|overlap|truncat|misalign|overflow|clip|obscur|hidden\s+text|broken\s+layout)/i;
856
+ var SPELLING_REGEX = /(?:spelling|typo|misspell|grammar)/i;
857
+ var I18N_REGEX = /(?:i18n|internationali[sz]ation|locali[sz]ation|untranslated|missing\s+translation)/i;
858
+ var LAYOUT_REGEX = /(?:layout|spacing|padding|margin|alignment|centering|position)/i;
859
+ var A11Y_REGEX = /(?:accessib|a11y|contrast|screen\s*reader|alt\s*text|aria)/i;
860
+ function classifyDefectType(text) {
861
+ if (SPELLING_REGEX.test(text)) return "spelling";
862
+ if (I18N_REGEX.test(text)) return "i18n";
863
+ if (A11Y_REGEX.test(text)) return "accessibility";
864
+ if (LAYOUT_REGEX.test(text)) return "layout";
865
+ return "ui";
866
+ }
867
+ function classifySeverity(text) {
868
+ if (SEVERITY_CRITICAL_REGEX.test(text)) return "critical";
869
+ if (SEVERITY_WARNING_REGEX.test(text)) return "warning";
870
+ return "info";
871
+ }
872
+ function stripHtmlTags(html) {
873
+ return html.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
874
+ }
875
+ function extractDefectsFromHtml(html) {
876
+ const defects = [];
877
+ const plainText = stripHtmlTags(html);
878
+ const listItemRegex = /<li[^>]*>([\s\S]*?)<\/li>/gi;
879
+ let match;
880
+ while ((match = listItemRegex.exec(html)) !== null) {
881
+ const itemHtml = match[1];
882
+ const itemText = stripHtmlTags(itemHtml);
883
+ if (!itemText || itemText.length < 5) continue;
884
+ if (DEFECT_SECTION_REGEX.test(itemText) || UI_DEFECT_REGEX.test(itemText) || SPELLING_REGEX.test(itemText) || I18N_REGEX.test(itemText)) {
885
+ defects.push({
886
+ type: classifyDefectType(itemText),
887
+ severity: classifySeverity(itemText),
888
+ description: itemText,
889
+ location: null,
890
+ screenshot: null
891
+ });
892
+ }
893
+ }
894
+ if (defects.length === 0) {
895
+ const paragraphRegex = /<p[^>]*>([\s\S]*?)<\/p>/gi;
896
+ while ((match = paragraphRegex.exec(html)) !== null) {
897
+ const pText = stripHtmlTags(match[1]);
898
+ if (!pText || pText.length < 10) continue;
899
+ if (UI_DEFECT_REGEX.test(pText) || SPELLING_REGEX.test(pText) || I18N_REGEX.test(pText) || LAYOUT_REGEX.test(pText) || A11Y_REGEX.test(pText)) {
900
+ defects.push({
901
+ type: classifyDefectType(pText),
902
+ severity: classifySeverity(pText),
903
+ description: pText,
904
+ location: null,
905
+ screenshot: null
906
+ });
907
+ }
908
+ }
909
+ }
910
+ if (defects.length === 0 && plainText.length > 20) {
911
+ const sentences = plainText.split(/[.!?]+/).filter((s) => s.trim().length > 10);
912
+ for (const sentence of sentences) {
913
+ const trimmed = sentence.trim();
914
+ if (UI_DEFECT_REGEX.test(trimmed) || SPELLING_REGEX.test(trimmed) || I18N_REGEX.test(trimmed) || LAYOUT_REGEX.test(trimmed) || A11Y_REGEX.test(trimmed)) {
915
+ defects.push({
916
+ type: classifyDefectType(trimmed),
917
+ severity: classifySeverity(trimmed),
918
+ description: trimmed,
919
+ location: null,
920
+ screenshot: null
921
+ });
922
+ }
923
+ }
924
+ }
925
+ return defects;
926
+ }
927
+ function parseAiReportHtml(htmlContent) {
928
+ const defects = extractDefectsFromHtml(htmlContent);
929
+ return {
930
+ defects,
931
+ totalDefects: defects.length,
932
+ hasIssues: defects.length > 0,
933
+ rawHtml: htmlContent
934
+ };
935
+ }
936
+ function parseAiReportFile(filePath) {
937
+ try {
938
+ const content = (0, import_node_fs8.readFileSync)(filePath, "utf-8");
939
+ return parseAiReportHtml(content);
940
+ } catch {
941
+ return { defects: [], totalDefects: 0, hasIssues: false, rawHtml: null };
942
+ }
943
+ }
944
+ function discoverAiReports(dir) {
945
+ if (!(0, import_node_fs8.existsSync)(dir)) return [];
946
+ try {
947
+ return (0, import_node_fs8.readdirSync)(dir, { recursive: true }).map(String).filter((f) => {
948
+ const name = (0, import_node_path6.basename)(f).toLowerCase();
949
+ const ext = (0, import_node_path6.extname)(f).toLowerCase();
950
+ return ext === ".html" && (name.includes("insight") || name.includes("ai") || name.includes("analysis"));
951
+ }).map((f) => (0, import_node_path6.join)(dir, f));
952
+ } catch {
953
+ return [];
954
+ }
955
+ }
956
+
957
+ // src/artifact-collector.ts
958
+ var import_node_fs9 = require("fs");
959
+ var import_node_path7 = require("path");
960
+ var IMAGE_EXTENSIONS = /* @__PURE__ */ new Set([".png", ".jpg", ".jpeg", ".webp"]);
961
+ var VIDEO_EXTENSIONS = /* @__PURE__ */ new Set([".mp4", ".webm", ".mov"]);
962
+ function walkDir(dir) {
963
+ const results = [];
964
+ if (!(0, import_node_fs9.existsSync)(dir)) return results;
965
+ function recurse(current) {
966
+ try {
967
+ const entries = (0, import_node_fs9.readdirSync)(current, { withFileTypes: true });
968
+ for (const entry of entries) {
969
+ const fullPath = (0, import_node_path7.join)(current, entry.name);
970
+ if (entry.isDirectory()) {
971
+ recurse(fullPath);
972
+ } else if (entry.isFile()) {
973
+ results.push(fullPath);
974
+ }
975
+ }
976
+ } catch {
977
+ }
978
+ }
979
+ recurse(dir);
980
+ return results;
981
+ }
982
+ function collectArtifacts(testOutputDir, debugOutputDir) {
983
+ const screenshotPaths = [];
984
+ const videoPaths = [];
985
+ const logPaths = [];
986
+ const commandJsonPaths = [];
987
+ const aiReportPaths = [];
988
+ let junitReportPath = null;
989
+ const allFiles = [];
990
+ if (testOutputDir) allFiles.push(...walkDir(testOutputDir));
991
+ if (debugOutputDir) allFiles.push(...walkDir(debugOutputDir));
992
+ const seen = /* @__PURE__ */ new Set();
993
+ for (const filePath of allFiles) {
994
+ if (seen.has(filePath)) continue;
995
+ seen.add(filePath);
996
+ const name = (0, import_node_path7.basename)(filePath).toLowerCase();
997
+ const ext = (0, import_node_path7.extname)(filePath).toLowerCase();
998
+ if (IMAGE_EXTENSIONS.has(ext)) {
999
+ screenshotPaths.push(filePath);
1000
+ continue;
1001
+ }
1002
+ if (VIDEO_EXTENSIONS.has(ext)) {
1003
+ videoPaths.push(filePath);
1004
+ continue;
1005
+ }
1006
+ if (name === "maestro.log" || ext === ".log" && name.includes("maestro")) {
1007
+ logPaths.push(filePath);
1008
+ continue;
1009
+ }
1010
+ if (name.startsWith("commands") && ext === ".json") {
1011
+ commandJsonPaths.push(filePath);
1012
+ continue;
1013
+ }
1014
+ if (ext === ".html" && (name.includes("insight") || name.includes("ai") || name.includes("analysis"))) {
1015
+ aiReportPaths.push(filePath);
1016
+ continue;
1017
+ }
1018
+ if (ext === ".xml" && (name.includes("report") || name.includes("junit"))) {
1019
+ if (!junitReportPath) junitReportPath = filePath;
1020
+ continue;
1021
+ }
1022
+ }
1023
+ return {
1024
+ screenshotPaths,
1025
+ videoPaths,
1026
+ logPaths,
1027
+ commandJsonPaths,
1028
+ aiReportPaths,
1029
+ junitReportPath
1030
+ };
1031
+ }
1032
+
1033
+ // src/timeline-builder.ts
1034
+ function mapCommandCategory(category) {
1035
+ switch (category) {
1036
+ case "interaction":
1037
+ return "ui_action";
1038
+ case "assertion":
1039
+ return "assertion";
1040
+ case "ai":
1041
+ return "assertion";
1042
+ case "navigation":
1043
+ return "custom_step";
1044
+ case "device":
1045
+ return "custom_step";
1046
+ case "media":
1047
+ return "custom_step";
1048
+ case "script":
1049
+ return "custom_step";
1050
+ case "flow_control":
1051
+ return "custom_step";
1052
+ case "recording":
1053
+ return "custom_step";
1054
+ default:
1055
+ return "custom_step";
1056
+ }
1057
+ }
1058
+ function commandToAction(cmd) {
1059
+ return {
1060
+ title: cmd.selector ? `${cmd.command} \u2192 ${cmd.selector}` : cmd.command,
1061
+ category: mapCommandCategory(cmd.category),
1062
+ status: cmd.status === "failed" ? "failed" : "passed",
1063
+ duration: cmd.duration,
1064
+ timestamp: cmd.timestamp,
1065
+ videoOffset: null,
1066
+ error: cmd.error ?? null,
1067
+ children: []
1068
+ };
1069
+ }
1070
+ function buildTestResult(flow) {
1071
+ const actions = [
1072
+ ...flow.commands.map(commandToAction),
1073
+ ...flow.assertions.map(commandToAction)
1074
+ ];
1075
+ actions.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
1076
+ const artifacts = flow.screenshotPaths.length > 0 || flow.videoPath ? {
1077
+ screenshot: flow.screenshotPaths[0] ?? void 0,
1078
+ video: flow.videoPath ?? void 0
1079
+ } : null;
1080
+ const tags = [...flow.tags];
1081
+ if (flow.platform !== "unknown" && !tags.includes(flow.platform)) {
1082
+ tags.push(flow.platform);
1083
+ }
1084
+ return {
1085
+ title: flow.flowName,
1086
+ status: flow.status,
1087
+ duration: flow.duration,
1088
+ startedAt: flow.startedAt,
1089
+ completedAt: flow.completedAt,
1090
+ retryCount: 0,
1091
+ tags,
1092
+ failure: flow.failureMessage ? { message: flow.failureMessage, line: null, code: null, stack: null } : null,
1093
+ testId: `${flow.flowFile}::${flow.flowName}`,
1094
+ filePath: flow.flowFile,
1095
+ suiteName: flow.appId ?? "maestro-suite",
1096
+ testType: "mobile",
1097
+ isFlaky: false,
1098
+ retryStatus: null,
1099
+ expectedStatus: "passed",
1100
+ actualStatus: flow.status,
1101
+ artifacts,
1102
+ networkRequests: null,
1103
+ apiCalls: null,
1104
+ apiAssertions: null,
1105
+ actions: actions.length > 0 ? actions : null,
1106
+ consoleLogs: null
1107
+ };
1108
+ }
1109
+ function buildTimelineEntry(flow) {
1110
+ const testResult = buildTestResult(flow);
1111
+ return {
1112
+ url: flow.appId ?? "maestro-flow",
1113
+ navigationType: "page_load",
1114
+ visitedAt: flow.startedAt,
1115
+ duration: flow.duration,
1116
+ specFile: flow.flowFile,
1117
+ domContentLoadedAt: null,
1118
+ networkIdleAt: null,
1119
+ networkStats: null,
1120
+ tests: [testResult]
1121
+ };
1122
+ }
1123
+ function buildTimeline(flows) {
1124
+ return flows.map(buildTimelineEntry);
1125
+ }
1126
+
1127
+ // src/summary-builder.ts
1128
+ var EMPTY_STATUS_RANGE = {
1129
+ "2xx": 0,
1130
+ "3xx": 0,
1131
+ "4xx": 0,
1132
+ "5xx": 0,
1133
+ error: 0
1134
+ };
1135
+ function buildSummary(timeline) {
1136
+ let total = 0;
1137
+ let passed = 0;
1138
+ let failed = 0;
1139
+ let flaky = 0;
1140
+ let skipped = 0;
1141
+ let timedout = 0;
1142
+ let totalAssertions = 0;
1143
+ let passedAssertions = 0;
1144
+ let failedAssertions = 0;
1145
+ const totalNavigations = timeline.length;
1146
+ let totalActionSteps = 0;
1147
+ const actionCategoryCounts = {};
1148
+ const uniqueUrls = /* @__PURE__ */ new Set();
1149
+ for (const entry of timeline) {
1150
+ uniqueUrls.add(entry.url);
1151
+ for (const test of entry.tests) {
1152
+ total++;
1153
+ switch (test.status) {
1154
+ case "passed":
1155
+ passed++;
1156
+ break;
1157
+ case "failed":
1158
+ failed++;
1159
+ break;
1160
+ case "flaky":
1161
+ flaky++;
1162
+ break;
1163
+ case "skipped":
1164
+ skipped++;
1165
+ break;
1166
+ case "timedout":
1167
+ timedout++;
1168
+ break;
1169
+ }
1170
+ if (test.actions) {
1171
+ for (const action of test.actions) {
1172
+ totalActionSteps++;
1173
+ if (action.category === "assertion") {
1174
+ totalAssertions++;
1175
+ if (action.status === "passed") passedAssertions++;
1176
+ else failedAssertions++;
1177
+ } else {
1178
+ const cat = action.category;
1179
+ actionCategoryCounts[cat] = (actionCategoryCounts[cat] ?? 0) + 1;
1180
+ }
1181
+ }
1182
+ }
1183
+ }
1184
+ }
1185
+ return {
1186
+ total,
1187
+ passed,
1188
+ failed,
1189
+ flaky,
1190
+ skipped,
1191
+ timedout,
1192
+ totalApiCalls: 0,
1193
+ uniqueApiUrls: 0,
1194
+ apiCallsByMethod: {},
1195
+ apiCallsByStatusRange: EMPTY_STATUS_RANGE,
1196
+ apiResponseTime: null,
1197
+ totalAssertions,
1198
+ passedAssertions,
1199
+ failedAssertions,
1200
+ totalNavigations,
1201
+ uniqueNavigationUrls: uniqueUrls.size,
1202
+ totalTimelineSteps: timeline.length,
1203
+ totalActionSteps,
1204
+ actionStepsByCategory: actionCategoryCounts
1205
+ };
1206
+ }
1207
+
1208
+ // src/html-report.ts
1209
+ var import_node_fs10 = require("fs");
1210
+ var import_node_path8 = require("path");
1211
+
1212
+ // src/html-css.ts
1213
+ var CSS = `
1214
+ /* \u2500\u2500 Theme Variables (verbatim from Appium) \u2500\u2500 */
1215
+ :root,[data-theme="dark"]{
1216
+ --bg:#0f1117;--bg-1:#161b22;--bg-2:#1c2128;--bg-3:#21262d;--bg-code:#13111c;
1217
+ --fg:#e6edf3;--fg-1:#8b949e;--fg-2:#484f58;--fg-code:#d4d4d4;--fg-err:#f8d7da;
1218
+ --bd:rgba(255,255,255,0.06);--bd-s:rgba(255,255,255,0.04);--bd-m:rgba(255,255,255,0.08);--bd-l:rgba(255,255,255,0.1);--bd-xs:rgba(255,255,255,0.03);
1219
+ --hvr:rgba(255,255,255,0.025);--hvr-s:rgba(255,255,255,0.02);
1220
+ --overlay-bg:rgba(0,0,0,.55);--shadow-c:rgba(0,0,0,.35);
1221
+ --lb-bg:rgba(0,0,0,.92);--lb-shadow:rgba(0,0,0,.6);--lb-btn:rgba(255,255,255,.1);--lb-btn-h:rgba(255,255,255,.2);
1222
+ --scroll-thumb:#21262d;
1223
+ }
1224
+ [data-theme="light"]{
1225
+ --bg:#ffffff;--bg-1:#f6f8fa;--bg-2:#eaeef2;--bg-3:#d0d7de;--bg-code:#f6f8fa;
1226
+ --fg:#1f2328;--fg-1:#656d76;--fg-2:#8b949e;--fg-code:#24292e;--fg-err:#82071e;
1227
+ --bd:rgba(0,0,0,0.08);--bd-s:rgba(0,0,0,0.04);--bd-m:rgba(0,0,0,0.12);--bd-l:rgba(0,0,0,0.15);--bd-xs:rgba(0,0,0,0.03);
1228
+ --hvr:rgba(0,0,0,0.04);--hvr-s:rgba(0,0,0,0.03);
1229
+ --overlay-bg:rgba(0,0,0,.3);--shadow-c:rgba(0,0,0,.1);
1230
+ --lb-bg:rgba(0,0,0,.85);--lb-shadow:rgba(0,0,0,.3);--lb-btn:rgba(0,0,0,.12);--lb-btn-h:rgba(0,0,0,.2);
1231
+ --scroll-thumb:#d0d7de;
1232
+ }
1233
+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
1234
+ body{font-family:Inter,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;background:var(--bg);color:var(--fg);line-height:1.5;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}
1235
+
1236
+ /* \u2500\u2500 Layout \u2500\u2500 */
1237
+ .wrap{max-width:960px;margin:0 auto;padding:32px 24px 64px}
1238
+
1239
+ /* \u2500\u2500 Topbar (same as Appium) \u2500\u2500 */
1240
+ .top-bar{display:flex;align-items:center;gap:14px;margin-bottom:20px;flex-wrap:wrap}
1241
+ .top-bar-actions{display:flex;align-items:center;gap:8px;flex-shrink:0;margin-left:auto}
1242
+ .brand{display:flex;align-items:center;gap:10px}
1243
+ .brand svg{flex-shrink:0}
1244
+ .brand-text{display:flex;flex-direction:column}
1245
+ .brand-title{font-size:17px;font-weight:700;color:var(--fg);line-height:1.2}
1246
+ .brand-sub{font-size:10px;font-weight:600;color:#03b79c;letter-spacing:.06em;text-transform:uppercase;margin-top:1px}
1247
+ .run-meta{display:flex;flex-wrap:wrap;gap:4px 14px;font-size:11px;color:var(--fg-1);flex:1;min-width:0}
1248
+ .run-meta-item{display:flex;align-items:center;gap:4px}
1249
+ .run-meta-label{font-weight:600}
1250
+ .run-id-tag{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:10px;background:var(--bg-2);padding:1px 6px;border-radius:4px;color:var(--fg-1)}
1251
+ .ci-tag{display:inline-flex;align-items:center;gap:4px;background:rgba(59,130,246,0.12);color:#60a5fa;padding:1px 6px;border-radius:4px;font-size:10px;font-weight:600}
1252
+ .platform-tag{display:inline-flex;align-items:center;gap:4px;background:rgba(3,183,156,0.12);color:#2dd4a8;padding:1px 6px;border-radius:4px;font-size:10px;font-weight:600}
1253
+
1254
+ /* \u2500\u2500 Theme Toggle (same as Appium) \u2500\u2500 */
1255
+ .theme-toggle{display:inline-flex;border:1px solid var(--bd-m);border-radius:8px;overflow:hidden;background:var(--bg);flex-shrink:0}
1256
+ .theme-btn{padding:6px 10px;border:none;background:transparent;color:var(--fg-2);cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all .15s;font-family:inherit}
1257
+ .theme-btn:not(:last-child){border-right:1px solid var(--bd-m)}
1258
+ .theme-btn.active{background:var(--bg-3);color:var(--fg)}
1259
+ .theme-btn:hover:not(.active){color:var(--fg-1);background:var(--hvr)}
1260
+ .theme-btn svg{width:14px;height:14px}
1261
+
1262
+ /* \u2500\u2500 CTA Button (same as Appium) \u2500\u2500 */
1263
+ .cta-btn{display:inline-flex;align-items:center;gap:5px;font-size:11px;font-weight:500;color:#e6edf3;background:linear-gradient(135deg,rgba(3,183,156,0.15),rgba(14,165,233,0.15));border:1px solid rgba(3,183,156,0.3);padding:6px 14px;border-radius:8px;text-decoration:none;white-space:nowrap;flex-shrink:0;transition:all .2s;letter-spacing:.01em}
1264
+ .cta-btn:hover{background:linear-gradient(135deg,rgba(3,183,156,0.25),rgba(14,165,233,0.25));border-color:rgba(3,183,156,0.5);box-shadow:0 0 16px rgba(3,183,156,0.15);color:#fff}
1265
+ .cta-btn strong{font-weight:700;color:#2dd4a8}
1266
+ .cta-btn:hover strong{color:#5eead4}
1267
+ .cta-icon{width:13px;height:13px;color:#2dd4a8;flex-shrink:0}
1268
+ .cta-arrow{width:11px;height:11px;color:#2dd4a8;flex-shrink:0;transition:transform .2s}
1269
+ .cta-btn:hover .cta-arrow{transform:translateX(2px)}
1270
+ [data-theme="light"] .cta-btn{color:#1f2328;background:linear-gradient(135deg,rgba(3,183,156,0.08),rgba(14,165,233,0.08));border-color:rgba(3,183,156,0.25)}
1271
+ [data-theme="light"] .cta-btn:hover{background:linear-gradient(135deg,rgba(3,183,156,0.15),rgba(14,165,233,0.15));border-color:rgba(3,183,156,0.4);color:#0f172a}
1272
+ [data-theme="light"] .cta-btn strong{color:#059669}
1273
+ [data-theme="light"] .cta-icon,[data-theme="light"] .cta-arrow{color:#059669}
1274
+
1275
+ /* \u2500\u2500 Hero Strip (Maestro: progress rings + summary chips) \u2500\u2500 */
1276
+ .hero-strip{border:1px solid var(--bd);border-radius:10px;background:var(--bg-1);padding:20px;margin-bottom:20px}
1277
+ .hero-top{display:flex;align-items:center;gap:24px;margin-bottom:16px;flex-wrap:wrap}
1278
+ .hero-rings{display:flex;gap:20px;flex-shrink:0}
1279
+ .ring-wrap{text-align:center}
1280
+ .ring-wrap svg{display:block;margin:0 auto 4px}
1281
+ .ring-label{font-size:9px;font-weight:600;text-transform:uppercase;letter-spacing:.06em;color:var(--fg-2)}
1282
+ .hero-chips{display:flex;gap:8px;flex:1;flex-wrap:wrap}
1283
+ .summary-chip{flex:1;text-align:center;padding:12px 4px;border-radius:8px;border:1px solid var(--bd-s);min-width:70px;cursor:pointer;transition:border-color .15s}
1284
+ .summary-chip:hover{border-color:var(--bd-m)}
1285
+ .summary-chip.active{border-color:#03b79c}
1286
+ .summary-chip .s-count{font-size:22px;font-weight:800;line-height:1}
1287
+ .summary-chip .s-label{font-size:9px;font-weight:600;text-transform:uppercase;letter-spacing:.06em;margin-top:4px;color:var(--fg-2)}
1288
+ .s-total{background:rgba(99,102,241,0.06)}.s-total .s-count{color:#818cf8}
1289
+ .s-passed{background:rgba(34,197,94,0.06)}.s-passed .s-count{color:#22c55e}
1290
+ .s-failed{background:rgba(239,68,68,0.06)}.s-failed .s-count{color:#ef4444}
1291
+ .s-flaky{background:rgba(245,158,11,0.06)}.s-flaky .s-count{color:#f59e0b}
1292
+ .s-skipped{background:rgba(107,114,128,0.06)}.s-skipped .s-count{color:#6b7280}
1293
+ .s-ai{background:rgba(168,85,247,0.06)}.s-ai .s-count{color:#a855f7}
1294
+ .hero-footer{display:flex;gap:14px;font-size:11px;color:var(--fg-1);flex-wrap:wrap;padding-top:12px;border-top:1px solid var(--bd-s)}
1295
+
1296
+ /* \u2500\u2500 Execution Waterfall \u2500\u2500 */
1297
+ .waterfall-card{border:1px solid var(--bd);border-radius:10px;background:var(--bg-1);padding:16px;margin-bottom:20px}
1298
+ .waterfall-title{font-size:11px;font-weight:600;color:var(--fg-2);text-transform:uppercase;letter-spacing:.06em;margin-bottom:10px}
1299
+ .waterfall-row{display:flex;align-items:center;gap:8px;padding:3px 0;font-size:11px;cursor:pointer;transition:background .1s;border-radius:4px;padding:3px 6px;margin:0 -6px}
1300
+ .waterfall-row:hover{background:var(--hvr)}
1301
+ .waterfall-name{width:140px;flex-shrink:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--fg-1);font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:10px}
1302
+ .waterfall-track{flex:1;height:14px;background:var(--bg-2);border-radius:3px;overflow:hidden;position:relative}
1303
+ .waterfall-bar{height:100%;border-radius:3px;min-width:2px;transition:width .3s}
1304
+ .wb-passed{background:rgba(34,197,94,0.35)}
1305
+ .wb-failed{background:rgba(239,68,68,0.35)}
1306
+ .wb-skipped{background:rgba(107,114,128,0.2)}
1307
+ .waterfall-dur{width:56px;flex-shrink:0;text-align:right;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:10px;color:var(--fg-2)}
1308
+
1309
+ /* \u2500\u2500 Filter Bar (same pattern as Appium: search + status chips + filter icon) \u2500\u2500 */
1310
+ .filter-bar{display:flex;align-items:center;gap:8px;margin-bottom:24px;flex-wrap:wrap}
1311
+ .filter-chips{display:flex;gap:5px;flex-wrap:wrap}
1312
+ .filter-chip{font-size:12px;font-weight:500;padding:5px 14px;border-radius:9999px;border:1px solid var(--bd-m);background:transparent;color:var(--fg-1);cursor:pointer;transition:all .15s;font-family:inherit;white-space:nowrap}
1313
+ .filter-chip:hover{border-color:#03b79c;color:var(--fg)}
1314
+ .filter-chip.active{background:rgba(3,183,156,0.12);border-color:#03b79c;color:#2dd4a8}
1315
+ .filter-chip--dimmed{opacity:.45}
1316
+ .chip-count{font-weight:700;margin-left:3px}
1317
+ .filter-clear{font-size:11px;font-weight:600;color:#03b79c;background:none;border:none;cursor:pointer;padding:4px 8px;border-radius:6px;font-family:inherit;transition:background .15s}
1318
+ .filter-clear:hover{background:rgba(3,183,156,0.1)}
1319
+ .filter-indicator{font-size:11px;color:var(--fg-2)}
1320
+ .search-box{position:relative;width:260px;flex-shrink:1;min-width:160px;margin-left:0}
1321
+ .search-input{width:100%;padding:6px 10px 6px 32px;border:1px solid var(--bd-m);border-radius:8px;background:var(--bg-1);color:var(--fg);font-size:12px;font-family:inherit;outline:none;transition:border-color .15s}
1322
+ .search-input::placeholder{color:var(--fg-2)}
1323
+ .search-input:focus{border-color:#03b79c}
1324
+ .search-icon{position:absolute;left:10px;top:50%;transform:translateY(-50%);color:var(--fg-2);pointer-events:none}
1325
+
1326
+ /* \u2500\u2500 Filter Icon Button (opens tag drawer) \u2500\u2500 */
1327
+ .filter-icon-btn{position:relative;display:flex;align-items:center;justify-content:center;width:34px;height:34px;border-radius:8px;border:1px solid var(--bd-m);background:transparent;color:var(--fg-2);cursor:pointer;transition:all .15s;flex-shrink:0;margin-left:auto}
1328
+ .filter-icon-btn:hover{background:var(--hvr);color:var(--fg);border-color:var(--bd-l)}
1329
+ .filter-icon-badge{position:absolute;top:5px;right:5px;width:7px;height:7px;border-radius:50%;background:#03b79c}
1330
+
1331
+ /* \u2500\u2500 Filter Drawer (right panel for tags + file filters) \u2500\u2500 */
1332
+ .filter-drawer-backdrop{position:fixed;inset:0;background:var(--overlay-bg);z-index:100;opacity:0;pointer-events:none;transition:opacity .25s}
1333
+ .filter-drawer-backdrop.open{opacity:1;pointer-events:auto}
1334
+ .filter-drawer{position:fixed;top:0;right:0;bottom:0;width:320px;max-width:90vw;z-index:110;background:var(--bg-1);border-left:1px solid var(--bd);transform:translateX(100%);transition:transform .3s cubic-bezier(.4,0,.2,1);display:flex;flex-direction:column;overflow:hidden;box-shadow:-4px 0 24px var(--shadow-c)}
1335
+ .filter-drawer.open{transform:translateX(0)}
1336
+ .filter-drawer-bar{display:flex;align-items:center;justify-content:space-between;padding:14px 20px;border-bottom:1px solid var(--bd);background:linear-gradient(180deg,rgba(3,183,156,0.04) 0%,transparent 100%);flex-shrink:0}
1337
+ .filter-drawer-title{font-size:12px;font-weight:600;color:var(--fg-1);text-transform:uppercase;letter-spacing:.06em}
1338
+ .filter-drawer-close{width:32px;height:32px;border-radius:8px;border:1px solid var(--bd-m);background:transparent;color:var(--fg-1);font-size:18px;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:background .15s,color .15s}
1339
+ .filter-drawer-close:hover{background:var(--bd);color:var(--fg)}
1340
+ .filter-drawer-body{flex:1;overflow-y:auto;padding:20px;scrollbar-width:thin;scrollbar-color:var(--scroll-thumb) transparent}
1341
+ .filter-drawer-body::-webkit-scrollbar{width:5px}
1342
+ .filter-drawer-body::-webkit-scrollbar-thumb{background:var(--bg-3);border-radius:3px}
1343
+ .filter-drawer-section{margin-bottom:20px}
1344
+ .filter-drawer-section-label{display:block;font-size:10px;font-weight:600;color:var(--fg-2);text-transform:uppercase;letter-spacing:.04em;margin-bottom:8px}
1345
+ .filter-drawer-actions{display:flex;align-items:center;gap:12px;padding-top:16px;border-top:1px solid var(--bd)}
1346
+
1347
+ /* \u2500\u2500 Flow List (same pattern as Appium file-group/test-row) \u2500\u2500 */
1348
+ .file-group{margin-bottom:16px}
1349
+ .file-group-header{font-size:11px;font-weight:600;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;color:var(--fg-2);padding:0 4px 6px}
1350
+ .file-group-card{border:1px solid var(--bd);border-radius:10px;overflow:hidden;background:var(--bg-1)}
1351
+ .test-row{display:flex;align-items:center;gap:12px;padding:12px 18px;cursor:pointer;transition:background .1s;border-bottom:1px solid var(--bd-s)}
1352
+ .test-row:last-child{border-bottom:none}
1353
+ .test-row:hover{background:var(--hvr)}
1354
+ .test-row.active{background:rgba(3,183,156,0.07)}
1355
+ .status-indicator{width:10px;height:10px;border-radius:50%;flex-shrink:0}
1356
+ .si-passed{background:#22c55e}.si-failed{background:#ef4444}.si-flaky{background:#f59e0b}.si-skipped{background:#6b7280}.si-timedout{background:#f97316}
1357
+ .test-row-info{flex:1;min-width:0;display:flex;flex-direction:column;gap:3px}
1358
+ .test-row-title{font-size:14px;font-weight:500;color:var(--fg);line-height:1.3;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1359
+ .test-row-badges{display:flex;gap:5px;align-items:center;flex-wrap:wrap}
1360
+ .trb{font-size:10px;font-weight:600;padding:1px 7px;border-radius:4px}
1361
+ .trb-app{background:rgba(59,130,246,0.12);color:#60a5fa}
1362
+ .trb-tag{background:rgba(139,92,246,0.12);color:#a78bfa}
1363
+ .trb-platform{background:rgba(3,183,156,0.12);color:#2dd4a8}
1364
+ .test-row-dur{font-size:13px;font-weight:700;color:var(--fg-1);flex-shrink:0;white-space:nowrap}
1365
+ .test-row-arrow{color:var(--fg-2);flex-shrink:0;transition:color .15s}
1366
+ .test-row:hover .test-row-arrow{color:var(--fg-1)}
1367
+ .test-row-error{font-size:11px;color:#ef4444;margin-top:2px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1368
+ .no-tests{text-align:center;padding:48px 20px;color:var(--fg-2);font-size:14px}
1369
+
1370
+ /* \u2500\u2500 Drawer (same as Appium) \u2500\u2500 */
1371
+ .drawer-backdrop{position:fixed;inset:0;background:var(--overlay-bg);z-index:100;opacity:0;pointer-events:none;transition:opacity .25s}
1372
+ .drawer-backdrop.open{opacity:1;pointer-events:auto}
1373
+ .drawer{position:fixed;top:0;right:0;bottom:0;width:50vw;max-width:50vw;z-index:110;background:var(--bg-1);border-left:1px solid var(--bd);transform:translateX(100%);transition:transform .3s cubic-bezier(.4,0,.2,1);display:flex;flex-direction:column;overflow:hidden;box-shadow:-8px 0 40px var(--shadow-c)}
1374
+ .drawer.open{transform:translateX(0)}
1375
+ .drawer-bar{display:flex;align-items:center;justify-content:space-between;padding:14px 20px;border-bottom:1px solid var(--bd);background:linear-gradient(180deg,rgba(3,183,156,0.04) 0%,transparent 100%);flex-shrink:0}
1376
+ .drawer-bar-title{font-size:12px;font-weight:600;color:var(--fg-1);text-transform:uppercase;letter-spacing:.06em}
1377
+ .drawer-close{width:32px;height:32px;border-radius:8px;border:1px solid var(--bd-m);background:transparent;color:var(--fg-1);font-size:18px;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:background .15s,color .15s}
1378
+ .drawer-close:hover{background:var(--bd);color:var(--fg)}
1379
+ .drawer-body{flex:1;overflow-y:auto;scrollbar-width:thin;scrollbar-color:var(--scroll-thumb) transparent}
1380
+ .drawer-body::-webkit-scrollbar{width:5px}
1381
+ .drawer-body::-webkit-scrollbar-track{background:transparent}
1382
+ .drawer-body::-webkit-scrollbar-thumb{background:var(--bg-3);border-radius:3px}
1383
+
1384
+ /* \u2500\u2500 Drawer Tabs (same seg-ctrl as Appium) \u2500\u2500 */
1385
+ .seg-ctrl{display:flex;gap:2px;padding:8px 12px 0;border-bottom:1px solid var(--bd);background:var(--bg-1);flex-wrap:wrap}
1386
+ .seg-btn{display:flex;align-items:center;gap:5px;font-size:11px;padding:5px 12px;border-radius:6px 6px 0 0;border:none;background:none;color:var(--fg-2);cursor:pointer;font-weight:500;transition:all .15s;border-bottom:2px solid transparent;margin-bottom:-1px;font-family:inherit}
1387
+ .seg-btn:hover{color:var(--fg-1);background:var(--hvr)}
1388
+ .seg-btn.active{color:#03b79c;border-bottom-color:#03b79c;font-weight:600;background:var(--bg)}
1389
+ .seg-pane{display:none;padding:20px 24px}
1390
+ .seg-pane.active{display:block;animation:trFadeIn .15s ease-out}
1391
+ @keyframes trFadeIn{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}
1392
+
1393
+ /* \u2500\u2500 Overview Tab \u2500\u2500 */
1394
+ .detail-header{margin-bottom:20px;padding-bottom:16px;border-bottom:1px solid var(--bd)}
1395
+ .detail-top{display:flex;align-items:flex-start;gap:12px;margin-bottom:10px}
1396
+ .detail-status-badge{font-size:11px;font-weight:700;padding:4px 14px;border-radius:9999px;text-transform:uppercase;letter-spacing:.04em;flex-shrink:0;margin-top:2px}
1397
+ .dbg-passed{background:rgba(34,197,94,0.1);color:#22c55e;border:1px solid rgba(34,197,94,0.2)}
1398
+ .dbg-failed{background:rgba(239,68,68,0.1);color:#ef4444;border:1px solid rgba(239,68,68,0.2)}
1399
+ .dbg-skipped{background:rgba(107,114,128,0.1);color:#6b7280;border:1px solid rgba(107,114,128,0.2)}
1400
+ .dbg-flaky{background:rgba(245,158,11,0.1);color:#f59e0b;border:1px solid rgba(245,158,11,0.2)}
1401
+ .dbg-timedout{background:rgba(249,115,22,0.1);color:#f97316;border:1px solid rgba(249,115,22,0.2)}
1402
+ .detail-title-section{flex:1;min-width:0}
1403
+ .detail-title{font-size:16px;font-weight:700;color:var(--fg);line-height:1.35;margin-bottom:6px}
1404
+ .detail-meta{display:flex;flex-wrap:wrap;gap:5px;align-items:center}
1405
+ .dm-badge{font-size:10px;font-weight:600;padding:2px 8px;border-radius:4px}
1406
+ .dm-app{background:rgba(59,130,246,0.12);color:#60a5fa}
1407
+ .dm-tag{background:rgba(139,92,246,0.12);color:#a78bfa}
1408
+ .dm-platform{background:rgba(3,183,156,0.12);color:#2dd4a8}
1409
+ .detail-duration{font-size:24px;font-weight:800;color:var(--fg);flex-shrink:0;white-space:nowrap}
1410
+ .detail-props{display:grid;grid-template-columns:auto 1fr;gap:4px 16px;font-size:12px;margin-top:12px}
1411
+ .detail-props-k{color:var(--fg-2);font-weight:600;text-transform:uppercase;letter-spacing:.04em;font-size:10px}
1412
+ .detail-props-v{color:var(--fg);font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:11px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1413
+
1414
+ /* \u2500\u2500 Failure Panel (same as Appium) \u2500\u2500 */
1415
+ .failure-panel{margin-bottom:20px;border:1px solid rgba(239,68,68,0.2);border-radius:10px;overflow:hidden;background:var(--bg-2)}
1416
+ .failure-panel-header{display:flex;align-items:center;gap:8px;padding:10px 14px;background:rgba(239,68,68,0.08);font-size:12px;font-weight:600;color:#ef4444}
1417
+ .failure-message{padding:12px 14px;background:var(--bg-code);color:var(--fg-err);font-size:12px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;white-space:pre-wrap;word-break:break-word;line-height:1.6;position:relative}
1418
+ .copy-btn{position:absolute;top:8px;right:8px;font-size:10px;padding:3px 10px;border-radius:4px;border:1px solid var(--bd-m);background:var(--bg-3);color:var(--fg-1);cursor:pointer;font-family:inherit;transition:all .15s}
1419
+ .copy-btn:hover{background:var(--bg-2);color:var(--fg)}
1420
+
1421
+ /* \u2500\u2500 Fix Hint (Maestro-specific, teal accent) \u2500\u2500 */
1422
+ .fix-hint{margin-bottom:20px;border:1px solid rgba(3,183,156,0.2);border-radius:10px;overflow:hidden;background:var(--bg-2)}
1423
+ .fix-hint-header{display:flex;align-items:center;gap:8px;padding:10px 14px;background:rgba(3,183,156,0.06);font-size:12px;font-weight:600;color:#2dd4a8}
1424
+ .fix-hint-body{padding:12px 14px;font-size:12px;color:var(--fg-1);line-height:1.7}
1425
+ .fix-hint-body ul{margin:4px 0 0 16px;list-style:disc}
1426
+ .fix-hint-body li{margin:2px 0}
1427
+ .fix-hint-body code{font-size:11px;padding:1px 5px;background:var(--bg-code);border-radius:3px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;color:var(--fg-code)}
1428
+ .fix-hint-section{margin-top:10px;padding-top:8px;border-top:1px solid var(--bd-s)}
1429
+ .fix-hint-section-title{font-size:10px;font-weight:600;color:var(--fg-2);text-transform:uppercase;letter-spacing:.04em;margin-bottom:4px}
1430
+ .fix-code{margin:6px 0;padding:8px 12px;background:var(--bg-code);border:1px solid var(--bd);border-radius:6px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:11px;color:var(--fg-code);white-space:pre-wrap;line-height:1.5}
1431
+
1432
+ /* \u2500\u2500 Subflow Graph \u2500\u2500 */
1433
+ .subflow-tree{margin-top:16px;padding:12px;background:var(--bg-2);border:1px solid var(--bd-s);border-radius:8px;font-size:11px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;color:var(--fg-1)}
1434
+ .subflow-tree .sf-node{padding:2px 0}
1435
+ .subflow-tree .sf-child{padding-left:20px;border-left:1px solid var(--bd-m)}
1436
+
1437
+ /* \u2500\u2500 Steps Tab \u2500\u2500 */
1438
+ .steps-header{font-size:11px;font-weight:700;color:var(--fg-1);text-transform:uppercase;letter-spacing:.06em;margin-bottom:12px;display:flex;align-items:center;gap:8px}
1439
+ .steps-stat{font-weight:400;color:var(--fg-2);font-size:10px}
1440
+ .steps-waterfall{margin-bottom:16px;border:1px solid var(--bd);border-radius:8px;background:var(--bg-2);padding:8px 12px;overflow-x:auto}
1441
+ .sw-row{display:flex;align-items:center;gap:6px;padding:2px 0;font-size:10px}
1442
+ .sw-name{width:120px;flex-shrink:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--fg-2);font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
1443
+ .sw-track{flex:1;height:10px;background:var(--bg-3);border-radius:2px;overflow:hidden}
1444
+ .sw-bar{height:100%;border-radius:2px;min-width:1px}
1445
+ .sw-bar-green{background:#22c55e}.sw-bar-amber{background:#f59e0b}.sw-bar-red{background:#ef4444}.sw-bar-grey{background:#6b7280}
1446
+ .sw-dur{width:52px;flex-shrink:0;text-align:right;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;color:var(--fg-2)}
1447
+ .cmd-step{display:flex;align-items:center;gap:8px;padding:6px 12px;border-radius:6px;font-size:12px;transition:background .1s;border-left:3px solid transparent}
1448
+ .cmd-step:hover{background:var(--hvr)}
1449
+ .cmd-step-failed{background:rgba(239,68,68,0.04);border-left-color:#ef4444}
1450
+ .cmd-step-failed:hover{background:rgba(239,68,68,0.08)}
1451
+ .cmd-step-slow{border-left-color:#f59e0b;background:rgba(245,158,11,0.03)}
1452
+ .cmd-step-slow:hover{background:rgba(245,158,11,0.07)}
1453
+ .cmd-step-fast{border-left-color:#22c55e}
1454
+ .cmd-dot{width:8px;height:8px;border-radius:50%;flex-shrink:0}
1455
+ .cmd-dot-pass{background:#22c55e}.cmd-dot-fail{background:#ef4444}
1456
+ .cmd-badge{font-size:9px;font-weight:600;padding:2px 7px;border-radius:4px;text-transform:uppercase;letter-spacing:.03em;flex-shrink:0;white-space:nowrap}
1457
+ .cmd-badge-ui{background:rgba(59,130,246,0.12);color:#60a5fa}
1458
+ .cmd-badge-assert{background:rgba(34,197,94,0.12);color:#22c55e}
1459
+ .cmd-badge-nav{background:rgba(168,85,247,0.12);color:#a78bfa}
1460
+ .cmd-badge-device{background:rgba(249,115,22,0.12);color:#fb923c}
1461
+ .cmd-badge-ai{background:rgba(236,72,153,0.12);color:#f472b6}
1462
+ .cmd-badge-cmd{background:var(--bg-3);color:var(--fg-2)}
1463
+ .cmd-badge-slow{background:rgba(245,158,11,0.15);color:#f59e0b;margin-left:auto}
1464
+ .cmd-title{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--fg);font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:11px}
1465
+ .cmd-dur{font-size:10px;color:var(--fg-2);flex-shrink:0;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
1466
+ .cmd-error{font-size:11px;color:#ef4444;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;white-space:pre-wrap;word-break:break-word;line-height:1.5;padding:4px 12px 8px 31px}
1467
+ .cmd-connector{width:2px;height:4px;background:var(--bd-m);margin-left:15px}
1468
+ .steps-legend{display:flex;flex-wrap:wrap;gap:10px;margin-top:16px;padding-top:12px;border-top:1px solid var(--bd);font-size:10px;color:var(--fg-2)}
1469
+ .steps-legend span{display:inline-flex;align-items:center;gap:4px}
1470
+
1471
+ /* \u2500\u2500 Assertions Tab \u2500\u2500 */
1472
+ .assert-header{display:flex;align-items:center;gap:16px;margin-bottom:16px;flex-wrap:wrap}
1473
+ .assert-ring{flex-shrink:0}
1474
+ .assert-stats{font-size:12px;color:var(--fg-1);line-height:1.6}
1475
+ .assert-stats strong{font-weight:700}
1476
+ .assert-bar-wrap{flex:1;min-width:100px}
1477
+ .assert-bar{height:6px;background:var(--bg-3);border-radius:3px;overflow:hidden}
1478
+ .assert-bar-fill{height:100%;background:#22c55e;border-radius:3px;transition:width .3s}
1479
+ .assert-pct{font-size:11px;font-weight:700;color:var(--fg-1);margin-top:2px;text-align:right}
1480
+ .assert-table{width:100%;border-collapse:collapse;font-size:12px}
1481
+ .assert-table th{text-align:left;padding:6px 10px;font-size:10px;font-weight:600;color:var(--fg-2);text-transform:uppercase;letter-spacing:.04em;border-bottom:1px solid var(--bd)}
1482
+ .assert-table td{padding:6px 10px;border-bottom:1px solid var(--bd-s);vertical-align:top}
1483
+ .assert-table tr:hover{background:var(--hvr)}
1484
+ .assert-result{font-weight:700;font-size:13px}
1485
+ .ar-pass{color:#22c55e}.ar-fail{color:#ef4444}
1486
+ .assert-error-row td{padding:2px 10px 8px 40px;border-bottom:1px solid var(--bd-s);color:#ef4444;font-size:11px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
1487
+
1488
+ /* \u2500\u2500 Screenshots Tab \u2500\u2500 */
1489
+ .screenshot-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:12px}
1490
+ .screenshot-card{border:1px solid var(--bd);border-radius:8px;overflow:hidden;background:var(--bg-2);cursor:pointer;transition:border-color .15s}
1491
+ .screenshot-card:hover{border-color:#03b79c}
1492
+ .screenshot-card img{width:100%;display:block;object-fit:contain}
1493
+ .screenshot-card-label{padding:6px 10px;font-size:10px;font-weight:600;color:var(--fg-2);border-top:1px solid var(--bd-s)}
1494
+ .screenshot-card.failure-shot{border-color:rgba(239,68,68,0.3)}
1495
+ .screenshot-card.failure-shot .screenshot-card-label{background:rgba(239,68,68,0.06);color:#ef4444}
1496
+ .screenshot-empty{padding:24px 14px;text-align:center;font-size:12px;color:var(--fg-2);font-style:italic;border:1px dashed var(--bd-m);border-radius:10px}
1497
+
1498
+ /* \u2500\u2500 AI Defects Tab \u2500\u2500 */
1499
+ .ai-card{border:1px solid var(--bd);border-radius:10px;overflow:hidden;background:var(--bg-2);margin-bottom:12px;border-left:3px solid transparent}
1500
+ .ai-card-critical{border-left-color:rgba(239,68,68,0.5)}
1501
+ .ai-card-warning{border-left-color:rgba(245,158,11,0.5)}
1502
+ .ai-card-info{border-left-color:rgba(59,130,246,0.5)}
1503
+ .ai-card-header{display:flex;align-items:center;gap:8px;padding:10px 14px;border-bottom:1px solid var(--bd-s)}
1504
+ .ai-severity{font-size:10px;font-weight:700;padding:2px 10px;border-radius:9999px;text-transform:uppercase;letter-spacing:.04em}
1505
+ .ai-sev-critical{background:rgba(239,68,68,0.12);color:#ef4444;border:1px solid rgba(239,68,68,0.2)}
1506
+ .ai-sev-warning{background:rgba(245,158,11,0.12);color:#f59e0b;border:1px solid rgba(245,158,11,0.2)}
1507
+ .ai-sev-info{background:rgba(59,130,246,0.12);color:#60a5fa;border:1px solid rgba(59,130,246,0.2)}
1508
+ .ai-type{font-size:11px;font-weight:600;color:var(--fg-1);text-transform:capitalize}
1509
+ .ai-desc{padding:10px 14px;font-size:12px;color:var(--fg);line-height:1.6}
1510
+ .ai-fix{padding:10px 14px;border-top:1px solid var(--bd-s);background:rgba(3,183,156,0.03)}
1511
+ .ai-fix-label{font-size:10px;font-weight:700;color:#2dd4a8;text-transform:uppercase;letter-spacing:.06em;margin-bottom:6px}
1512
+ .ai-fix-body{font-size:12px;color:var(--fg-1);line-height:1.7}
1513
+ .ai-fix-body ul{margin:0 0 0 16px;list-style:disc}
1514
+ .ai-fix-body li{margin:2px 0}
1515
+ .ai-fix-code{margin:6px 0;padding:8px 12px;background:var(--bg-code);border:1px solid var(--bd);border-radius:6px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:11px;color:var(--fg-code);white-space:pre-wrap;line-height:1.5}
1516
+ .ai-fix-platform{font-size:10px;font-weight:600;color:var(--fg-2);margin:8px 0 2px;text-transform:uppercase;letter-spacing:.04em}
1517
+ .ai-empty{text-align:center;padding:32px;color:#22c55e;font-weight:600;font-size:14px}
1518
+
1519
+ /* \u2500\u2500 Lightbox (same as Appium) \u2500\u2500 */
1520
+ .lightbox-overlay{position:fixed;inset:0;background:var(--lb-bg);z-index:1000;display:flex;align-items:center;justify-content:center;cursor:zoom-out;animation:trFadeIn .15s}
1521
+ .lightbox-overlay img{max-width:92vw;max-height:92vh;border-radius:8px;box-shadow:0 8px 40px var(--lb-shadow)}
1522
+ .lightbox-close{position:fixed;top:16px;right:16px;z-index:1001;width:40px;height:40px;border-radius:50%;border:none;background:var(--lb-btn);color:#fff;font-size:22px;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:background .15s;backdrop-filter:blur(8px)}
1523
+ .lightbox-close:hover{background:var(--lb-btn-h)}
1524
+ .lightbox-nav{position:fixed;top:50%;z-index:1001;width:40px;height:40px;border-radius:50%;border:none;background:var(--lb-btn);color:#fff;font-size:18px;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:background .15s;transform:translateY(-50%);backdrop-filter:blur(8px)}
1525
+ .lightbox-nav:hover{background:var(--lb-btn-h)}
1526
+ .lightbox-prev{left:16px}
1527
+ .lightbox-next{right:16px}
1528
+ .lightbox-caption{position:fixed;bottom:20px;left:50%;transform:translateX(-50%);z-index:1001;font-size:12px;color:#fff;background:rgba(0,0,0,.6);padding:4px 16px;border-radius:8px;backdrop-filter:blur(8px)}
1529
+
1530
+ /* \u2500\u2500 Footer \u2500\u2500 */
1531
+ .report-footer{text-align:center;padding:24px;font-size:12px;color:var(--fg-2)}
1532
+ .report-footer a{color:#03b79c;text-decoration:none}
1533
+ .report-footer a:hover{text-decoration:underline}
1534
+
1535
+ /* \u2500\u2500 Loading (same as Appium) \u2500\u2500 */
1536
+ .loading-overlay{position:fixed;top:0;left:0;right:0;bottom:0;background:var(--bg);z-index:9999;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:16px}
1537
+ .loading-spinner{width:36px;height:36px;border:3px solid var(--bd-l);border-top-color:var(--fg-1);border-radius:50%;animation:spin .8s linear infinite}
1538
+ .loading-text{font:13px/1 inherit;color:var(--fg-1)}
1539
+ @keyframes spin{to{transform:rotate(360deg)}}
1540
+
1541
+ /* \u2500\u2500 Scrollbar (same as Appium) \u2500\u2500 */
1542
+ *{scrollbar-width:thin;scrollbar-color:var(--scroll-thumb) transparent}
1543
+ ::-webkit-scrollbar{width:6px;height:6px}
1544
+ ::-webkit-scrollbar-track{background:transparent}
1545
+ ::-webkit-scrollbar-thumb{background:var(--scroll-thumb);border-radius:3px}
1546
+ ::-webkit-scrollbar-thumb:hover{background:var(--fg-2)}
1547
+ ::-webkit-scrollbar-corner{background:transparent}
1548
+
1549
+ /* \u2500\u2500 Responsive (same breakpoints as Appium) \u2500\u2500 */
1550
+ @media(max-width:1100px){.drawer{width:60vw;max-width:60vw}}
1551
+ @media(max-width:800px){.drawer{width:85vw;max-width:85vw}}
1552
+ @media(max-width:640px){
1553
+ .wrap{padding:16px 12px 48px}
1554
+ .top-bar{flex-direction:column;align-items:flex-start;gap:8px}
1555
+ .top-bar-actions{margin-left:0}
1556
+ .hero-top{flex-direction:column;align-items:stretch}
1557
+ .hero-rings{justify-content:center}
1558
+ .hero-chips{flex-wrap:wrap}
1559
+ .summary-chip{min-width:60px}
1560
+ .filter-bar{flex-direction:column;align-items:stretch}
1561
+ .search-box{width:100%;margin-left:0}
1562
+ .drawer{width:100%;max-width:100%}
1563
+ .filter-drawer{width:100%;max-width:100%}
1564
+ .cta-btn{font-size:10px;padding:5px 10px;order:10}
1565
+ .detail-title{font-size:14px}
1566
+ .detail-duration{font-size:20px}
1567
+ .waterfall-name{width:80px}
1568
+ }
1569
+
1570
+ /* \u2500\u2500 Print (same as Appium) \u2500\u2500 */
1571
+ @media print{
1572
+ body{background:#fff;color:#000}
1573
+ .drawer-backdrop,.drawer,.lightbox-overlay,.lightbox-close,.lightbox-nav,.lightbox-caption{display:none}
1574
+ .test-row-arrow{display:none}
1575
+ .summary-chip,.filter-chip,.status-indicator,.detail-status-badge,.dm-badge,.trb,.cmd-badge,.ai-severity{print-color-adjust:exact;-webkit-print-color-adjust:exact}
1576
+ }
1577
+ `;
1578
+
1579
+ // src/html-logo.ts
1580
+ var LOGO_SVG_RAW = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 196 247" fill="none">
1581
+ <path fill-rule="evenodd" clip-rule="evenodd" d="M4.75 1.08009C2.034 2.66209 -0.130999 7.63009 0.610001 10.5821C0.969001 12.0121 3.021 15.2131 5.17 17.6971C14.375 28.3321 18 39.7791 18 58.2101V71.0001H12.434C1.16501 71.0001 0 73.4641 0 97.3051C0 106.858 0.298003 128.922 0.662003 146.337L1.323 178H33.606C65.786 178 65.897 178.007 68.544 180.284C72.228 183.453 72.244 189.21 68.579 192.877L65.957 195.5L33.479 195.801L1 196.103V204.551V213H24.577H48.154L51.077 215.923C55.007 219.853 55.007 224.147 51.077 228.077L48.154 231H26.469H4.783L5.41901 233.534C5.76901 234.927 7.143 238.527 8.472 241.534L10.89 247H40.945H71L71.006 241.75C71.017 230.748 76.027 221.606 84.697 216.767C97.854 209.424 114.086 213.895 121.323 226.857C123.659 231.041 124.418 233.833 124.789 239.607L125.263 247H155.187H185.11L187.528 241.534C188.857 238.527 190.231 234.927 190.581 233.534L191.217 231H169.531H147.846L144.923 228.077C142.928 226.082 142 224.152 142 222C142 219.848 142.928 217.918 144.923 215.923L147.846 213H171.423H195V204.551V196.103L162.521 195.801L130.043 195.5L127.421 192.877C123.991 189.445 123.835 183.869 127.074 180.421L129.349 178H162.013H194.677L195.338 146.337C195.702 128.922 196 106.858 196 97.3051C196 73.4641 194.835 71.0001 183.566 71.0001H178V58.2101C178 39.6501 181.397 28.7731 190.538 18.0651C195.631 12.0971 196.572 9.00809 194.511 5.02109C192.672 1.46509 190.197 9.12233e-05 186.028 9.12233e-05C179.761 9.12233e-05 168.713 14.8831 163.388 30.5001C160.975 37.5771 160.608 40.3751 160.213 54.7501L159.765 71.0001H150.732H141.7L142.286 53.2501C142.904 34.5511 144.727 24.3761 148.938 16.1211C151.823 10.4671 151.628 5.90109 148.364 2.63609C145 -0.726907 140.105 -0.887909 136.596 2.25009C133.481 5.03609 128.686 17.0811 126.507 27.5921C125.569 32.1191 124.617 43.0901 124.28 53.2501L123.69 71.0001H115.345H107V38.4231V5.84609L104.077 2.92309C102.082 0.928088 100.152 9.12233e-05 98 9.12233e-05C95.848 9.12233e-05 93.918 0.928088 91.923 2.92309L89 5.84609V38.4231V71.0001H80.655H72.31L71.72 53.2501C71.383 43.0901 70.431 32.1191 69.493 27.5921C67.314 17.0811 62.519 5.03609 59.404 2.25009C55.998 -0.795909 51.059 -0.710905 47.646 2.45209C44.221 5.62609 44.191 9.92109 47.539 17.4911C51.71 26.9241 53.007 34.4791 53.676 53.2501L54.31 71.0001H45.272H36.235L35.787 54.7501C35.392 40.3751 35.025 37.5771 32.612 30.5001C27.194 14.6091 16.228 -0.02891 9.787 0.03009C7.979 0.04709 5.712 0.519093 4.75 1.08009ZM42.687 108.974C33.431 112.591 20.036 125.024 18.408 131.512C17.476 135.223 20.677 140.453 28.253 147.599C37.495 156.319 44.191 159.471 53.5 159.485C59.317 159.494 61.645 158.953 67.274 156.289C77.634 151.385 88.987 139.161 88.996 132.9C89.004 127.304 76.787 114.707 66.745 109.956C59.16 106.368 50.285 106.006 42.687 108.974ZM129.255 109.904C119.151 114.768 106.996 127.33 107.004 132.9C107.013 139.108 118.562 151.475 128.939 156.389C134.338 158.945 136.744 159.496 142.521 159.498C152.526 159.501 160.369 155.502 169.771 145.605C180.444 134.368 180.278 130.975 168.486 119.388C160.043 111.094 152.727 107.595 143 107.201C136.364 106.933 134.78 107.244 129.255 109.904ZM48.5 125.922C46.3 126.969 43.152 128.945 41.505 130.314L38.511 132.802L40.504 135.005C41.601 136.216 44.434 138.342 46.8 139.728C52.577 143.114 57.36 142.466 64.009 137.395L68.978 133.606L66.756 131.24C60.944 125.054 54.357 123.135 48.5 125.922ZM138.386 125.063C136.674 125.571 133.375 127.677 131.057 129.743L126.841 133.5L131.901 137.343C138.65 142.468 143.407 143.124 149.2 139.728C151.566 138.342 154.351 136.269 155.389 135.122C157.684 132.587 156.742 131.097 150.58 127.511C145.438 124.519 142.329 123.895 138.386 125.063ZM91.923 162.923C89.043 165.804 89 166.008 89 176.973C89 184.805 89.435 188.941 90.47 190.941C92.356 194.589 96.918 196.273 101.03 194.84C105.82 193.17 107 189.638 107 176.973C107 166.008 106.957 165.804 104.077 162.923C102.082 160.928 100.152 160 98 160C95.848 160 93.918 160.928 91.923 162.923ZM94.5 232.155C91.026 234.055 90 236.229 90 241.691V247H98H106V242.082C106 235.732 105.37 234.242 101.928 232.463C98.591 230.737 97.197 230.679 94.5 232.155Z" fill="url(#paint0_linear_55_11)"/>
1582
+ <defs><linearGradient id="paint0_linear_55_11" x1="98" y1="0.000244141" x2="98" y2="247" gradientUnits="userSpaceOnUse">
1583
+ <stop stop-color="#03B79C"/><stop offset="0.504808" stop-color="#4EDAA4"/><stop offset="0.865285" stop-color="#84F3AA"/>
1584
+ </linearGradient></defs></svg>`;
1585
+ var LOGO_SVG = `<svg width="32" height="40" viewBox="0 0 196 247" fill="none" xmlns="http://www.w3.org/2000/svg">
1586
+ <path fill-rule="evenodd" clip-rule="evenodd" d="M4.75 1.08009C2.034 2.66209 -0.130999 7.63009 0.610001 10.5821C0.969001 12.0121 3.021 15.2131 5.17 17.6971C14.375 28.3321 18 39.7791 18 58.2101V71.0001H12.434C1.16501 71.0001 0 73.4641 0 97.3051C0 106.858 0.298003 128.922 0.662003 146.337L1.323 178H33.606C65.786 178 65.897 178.007 68.544 180.284C72.228 183.453 72.244 189.21 68.579 192.877L65.957 195.5L33.479 195.801L1 196.103V204.551V213H24.577H48.154L51.077 215.923C55.007 219.853 55.007 224.147 51.077 228.077L48.154 231H26.469H4.783L5.41901 233.534C5.76901 234.927 7.143 238.527 8.472 241.534L10.89 247H40.945H71L71.006 241.75C71.017 230.748 76.027 221.606 84.697 216.767C97.854 209.424 114.086 213.895 121.323 226.857C123.659 231.041 124.418 233.833 124.789 239.607L125.263 247H155.187H185.11L187.528 241.534C188.857 238.527 190.231 234.927 190.581 233.534L191.217 231H169.531H147.846L144.923 228.077C142.928 226.082 142 224.152 142 222C142 219.848 142.928 217.918 144.923 215.923L147.846 213H171.423H195V204.551V196.103L162.521 195.801L130.043 195.5L127.421 192.877C123.991 189.445 123.835 183.869 127.074 180.421L129.349 178H162.013H194.677L195.338 146.337C195.702 128.922 196 106.858 196 97.3051C196 73.4641 194.835 71.0001 183.566 71.0001H178V58.2101C178 39.6501 181.397 28.7731 190.538 18.0651C195.631 12.0971 196.572 9.00809 194.511 5.02109C192.672 1.46509 190.197 9.12233e-05 186.028 9.12233e-05C179.761 9.12233e-05 168.713 14.8831 163.388 30.5001C160.975 37.5771 160.608 40.3751 160.213 54.7501L159.765 71.0001H150.732H141.7L142.286 53.2501C142.904 34.5511 144.727 24.3761 148.938 16.1211C151.823 10.4671 151.628 5.90109 148.364 2.63609C145 -0.726907 140.105 -0.887909 136.596 2.25009C133.481 5.03609 128.686 17.0811 126.507 27.5921C125.569 32.1191 124.617 43.0901 124.28 53.2501L123.69 71.0001H115.345H107V38.4231V5.84609L104.077 2.92309C102.082 0.928088 100.152 9.12233e-05 98 9.12233e-05C95.848 9.12233e-05 93.918 0.928088 91.923 2.92309L89 5.84609V38.4231V71.0001H80.655H72.31L71.72 53.2501C71.383 43.0901 70.431 32.1191 69.493 27.5921C67.314 17.0811 62.519 5.03609 59.404 2.25009C55.998 -0.795909 51.059 -0.710905 47.646 2.45209C44.221 5.62609 44.191 9.92109 47.539 17.4911C51.71 26.9241 53.007 34.4791 53.676 53.2501L54.31 71.0001H45.272H36.235L35.787 54.7501C35.392 40.3751 35.025 37.5771 32.612 30.5001C27.194 14.6091 16.228 -0.02891 9.787 0.03009C7.979 0.04709 5.712 0.519093 4.75 1.08009ZM42.687 108.974C33.431 112.591 20.036 125.024 18.408 131.512C17.476 135.223 20.677 140.453 28.253 147.599C37.495 156.319 44.191 159.471 53.5 159.485C59.317 159.494 61.645 158.953 67.274 156.289C77.634 151.385 88.987 139.161 88.996 132.9C89.004 127.304 76.787 114.707 66.745 109.956C59.16 106.368 50.285 106.006 42.687 108.974ZM129.255 109.904C119.151 114.768 106.996 127.33 107.004 132.9C107.013 139.108 118.562 151.475 128.939 156.389C134.338 158.945 136.744 159.496 142.521 159.498C152.526 159.501 160.369 155.502 169.771 145.605C180.444 134.368 180.278 130.975 168.486 119.388C160.043 111.094 152.727 107.595 143 107.201C136.364 106.933 134.78 107.244 129.255 109.904ZM48.5 125.922C46.3 126.969 43.152 128.945 41.505 130.314L38.511 132.802L40.504 135.005C41.601 136.216 44.434 138.342 46.8 139.728C52.577 143.114 57.36 142.466 64.009 137.395L68.978 133.606L66.756 131.24C60.944 125.054 54.357 123.135 48.5 125.922ZM138.386 125.063C136.674 125.571 133.375 127.677 131.057 129.743L126.841 133.5L131.901 137.343C138.65 142.468 143.407 143.124 149.2 139.728C151.566 138.342 154.351 136.269 155.389 135.122C157.684 132.587 156.742 131.097 150.58 127.511C145.438 124.519 142.329 123.895 138.386 125.063ZM91.923 162.923C89.043 165.804 89 166.008 89 176.973C89 184.805 89.435 188.941 90.47 190.941C92.356 194.589 96.918 196.273 101.03 194.84C105.82 193.17 107 189.638 107 176.973C107 166.008 106.957 165.804 104.077 162.923C102.082 160.928 100.152 160 98 160C95.848 160 93.918 160.928 91.923 162.923ZM94.5 232.155C91.026 234.055 90 236.229 90 241.691V247H98H106V242.082C106 235.732 105.37 234.242 101.928 232.463C98.591 230.737 97.197 230.679 94.5 232.155Z" fill="url(#paint0_linear_55_11)"/>
1587
+ <defs><linearGradient id="paint0_linear_55_11" x1="98" y1="0.000244141" x2="98" y2="247" gradientUnits="userSpaceOnUse">
1588
+ <stop stop-color="#03B79C"/><stop offset="0.504808" stop-color="#4EDAA4"/><stop offset="0.865285" stop-color="#84F3AA"/>
1589
+ </linearGradient></defs></svg>`;
1590
+
1591
+ // src/html-js-render.ts
1592
+ var JS_RENDER = `
1593
+ /* \u2500\u2500 Utilities \u2500\u2500 */
1594
+ function esc(s){if(!s)return '';return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;')}
1595
+ function fmtDur(ms){if(!ms||ms<=0)return '\\u2014';if(ms<1000)return Math.round(ms)+'ms';if(ms<60000)return (ms/1000).toFixed(1)+'s';var m=Math.floor(ms/60000),s=Math.round((ms%60000)/1000);return s>0?m+'m '+s+'s':m+'m'}
1596
+ function fmtDate(iso){try{return new Date(iso).toLocaleString()}catch(e){return iso}}
1597
+ function $(id){return document.getElementById(id)}
1598
+
1599
+ /* \u2500\u2500 Data Transform \u2500\u2500 */
1600
+ var flows=[];
1601
+ (report.timeline||[]).forEach(function(entry,ei){
1602
+ if(!entry.tests)return;
1603
+ entry.tests.forEach(function(t,ti){
1604
+ flows.push({entry:entry,test:t,idx:ei*1000+ti});
1605
+ });
1606
+ });
1607
+ flows.sort(function(a,b){
1608
+ if(a.test.filePath!==b.test.filePath)return a.test.filePath<b.test.filePath?-1:1;
1609
+ return (a.test.startedAt||'')<(b.test.startedAt||'')?-1:1;
1610
+ });
1611
+
1612
+ var summary=report.summary||{};
1613
+ var currentFilter='all';
1614
+ var searchQuery='';
1615
+ var openFlowIdx=-1;
1616
+
1617
+ function detectPlatform(){
1618
+ for(var i=0;i<flows.length;i++){
1619
+ var tags=flows[i].test.tags||[];
1620
+ for(var j=0;j<tags.length;j++){
1621
+ var t=tags[j].toLowerCase();
1622
+ if(t==='android'||t==='ios'||t==='web')return t;
1623
+ }
1624
+ }
1625
+ return '';
1626
+ }
1627
+
1628
+ /* \u2500\u2500 SVG Progress Ring \u2500\u2500 */
1629
+ function svgRing(pct,size,stroke,color){
1630
+ var r=(size-stroke)/2;
1631
+ var c=2*Math.PI*r;
1632
+ var offset=c*(1-pct/100);
1633
+ return '<svg width="'+size+'" height="'+size+'" viewBox="0 0 '+size+' '+size+'">'
1634
+ +'<circle cx="'+(size/2)+'" cy="'+(size/2)+'" r="'+r+'" fill="none" stroke="var(--bd-l)" stroke-width="'+stroke+'"/>'
1635
+ +'<circle cx="'+(size/2)+'" cy="'+(size/2)+'" r="'+r+'" fill="none" stroke="'+color+'" stroke-width="'+stroke+'"'
1636
+ +' stroke-dasharray="'+c+'" stroke-dashoffset="'+offset+'" stroke-linecap="round" transform="rotate(-90 '+(size/2)+' '+(size/2)+')"/>'
1637
+ +'<text x="'+(size/2)+'" y="'+(size/2+5)+'" text-anchor="middle" fill="var(--fg)" font-size="'+(size>60?14:12)+'" font-weight="700">'+Math.round(pct)+'%</text>'
1638
+ +'</svg>';
1639
+ }
1640
+
1641
+ /* \u2500\u2500 Render: Run Meta \u2500\u2500 */
1642
+ function renderRunMeta(){
1643
+ var el=$('run-meta');if(!el)return;
1644
+ var h='';
1645
+ h+='<span class="run-meta-item"><span class="run-meta-label">Run</span><span class="run-id-tag">'+esc((report.testRunId||'').substring(0,12))+'</span></span>';
1646
+ h+='<span class="run-meta-item"><span class="run-meta-label">Duration</span>'+fmtDur(report.totalDuration)+'</span>';
1647
+ h+='<span class="run-meta-item">'+fmtDate(report.startedAt)+'</span>';
1648
+ if(report.ci){
1649
+ h+='<span class="run-meta-item"><span class="ci-tag">'+esc(report.ci.provider)+'</span></span>';
1650
+ if(report.ci.branch)h+='<span class="run-meta-item"><span class="run-meta-label">Branch</span>'+esc(report.ci.branch)+'</span>';
1651
+ if(report.ci.commitSha)h+='<span class="run-meta-item"><span class="run-meta-label">Commit</span><span class="run-id-tag">'+esc(report.ci.commitSha.substring(0,8))+'</span></span>';
1652
+ }
1653
+ var plat=detectPlatform();
1654
+ if(plat)h+='<span class="platform-tag">'+esc(plat)+'</span>';
1655
+ el.innerHTML=h;
1656
+ }
1657
+
1658
+ /* \u2500\u2500 Render: Hero Strip (rings + chips) \u2500\u2500 */
1659
+ function renderHeroStrip(){
1660
+ var el=$('hero-strip');if(!el)return;
1661
+ var passRate=summary.total>0?Math.round((summary.passed/summary.total)*100):0;
1662
+ var assertRate=summary.totalAssertions>0?Math.round((summary.passedAssertions/summary.totalAssertions)*100):0;
1663
+
1664
+ var h='<div class="hero-top">';
1665
+ h+='<div class="hero-rings">';
1666
+ h+='<div class="ring-wrap">'+svgRing(passRate,64,5,'#22c55e')+'<div class="ring-label">Pass Rate</div></div>';
1667
+ h+='<div class="ring-wrap">'+svgRing(assertRate,64,5,'#a78bfa')+'<div class="ring-label">Assert Rate</div></div>';
1668
+ h+='</div>';
1669
+
1670
+ h+='<div class="hero-chips">';
1671
+ var chips=[
1672
+ {cls:'s-total',n:summary.total||0,l:'Total',f:'all'},
1673
+ {cls:'s-failed',n:summary.failed||0,l:'Failed',f:'failed'},
1674
+ {cls:'s-passed',n:summary.passed||0,l:'Passed',f:'passed'},
1675
+ {cls:'s-skipped',n:summary.skipped||0,l:'Skipped',f:'skipped'},
1676
+ {cls:'s-ai',n:aiDefects.length,l:'AI Defects',f:null}
1677
+ ];
1678
+ chips.forEach(function(c){
1679
+ h+='<div class="summary-chip '+c.cls+'" data-filter="'+(c.f||'')+'">'
1680
+ +'<div class="s-count">'+c.n+'</div>'
1681
+ +'<div class="s-label">'+c.l+'</div></div>';
1682
+ });
1683
+ h+='</div></div>';
1684
+
1685
+ h+='<div class="hero-footer">';
1686
+ h+='<span>Total Duration: <strong>'+fmtDur(report.totalDuration)+'</strong></span>';
1687
+ var plat=detectPlatform();
1688
+ if(plat)h+='<span>Platform: <strong>'+esc(plat)+'</strong></span>';
1689
+ if(summary.totalActionSteps)h+='<span>Steps: <strong>'+summary.totalActionSteps+'</strong></span>';
1690
+ if(summary.totalAssertions)h+='<span>Assertions: <strong>'+summary.totalAssertions+'</strong></span>';
1691
+ h+='</div>';
1692
+
1693
+ el.innerHTML=h;
1694
+
1695
+ el.querySelectorAll('.summary-chip[data-filter]').forEach(function(chip){
1696
+ chip.addEventListener('click',function(){
1697
+ var f=chip.dataset.filter;
1698
+ if(f){currentFilter=f;renderFilterBar();renderFlowList()}
1699
+ });
1700
+ });
1701
+ }
1702
+
1703
+ /* \u2500\u2500 Render: Execution Waterfall \u2500\u2500 */
1704
+ function renderWaterfall(){
1705
+ var el=$('waterfall');if(!el)return;
1706
+ if(flows.length===0){el.style.display='none';return}
1707
+ var maxDur=0;
1708
+ flows.forEach(function(f){if(f.test.duration>maxDur)maxDur=f.test.duration});
1709
+ if(maxDur===0)maxDur=1;
1710
+
1711
+ var h='<div class="waterfall-title">Execution Timeline</div>';
1712
+ flows.forEach(function(f){
1713
+ var t=f.test;
1714
+ var pct=Math.max(1,Math.round((t.duration/maxDur)*100));
1715
+ var cls=t.status==='passed'?'wb-passed':t.status==='failed'?'wb-failed':'wb-skipped';
1716
+ h+='<div class="waterfall-row" data-wf-idx="'+f.idx+'">'
1717
+ +'<div class="waterfall-name" title="'+esc(t.title)+'">'+esc(t.title)+'</div>'
1718
+ +'<div class="waterfall-track"><div class="waterfall-bar '+cls+'" style="width:'+pct+'%"></div></div>'
1719
+ +'<div class="waterfall-dur">'+fmtDur(t.duration)+'</div>'
1720
+ +'</div>';
1721
+ });
1722
+ el.innerHTML=h;
1723
+ }
1724
+
1725
+ /* \u2500\u2500 Tag filter state \u2500\u2500 */
1726
+ var activeTagFilter='';
1727
+
1728
+ /* \u2500\u2500 Compute tag counts \u2500\u2500 */
1729
+ function getTagCounts(){
1730
+ var tags={};
1731
+ flows.forEach(function(f){(f.test.tags||[]).forEach(function(t){
1732
+ var low=t.toLowerCase();if(low!=='android'&&low!=='ios'&&low!=='web')tags[t]=(tags[t]||0)+1;
1733
+ })});
1734
+ return tags;
1735
+ }
1736
+
1737
+ /* \u2500\u2500 Render: Filter Bar (clean: search + status pills + filter icon) \u2500\u2500 */
1738
+ function renderFilterBar(){
1739
+ var el=$('filter-bar');if(!el)return;
1740
+ var h='';
1741
+
1742
+ h+='<div class="search-box"><svg class="search-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/></svg>'
1743
+ +'<input class="search-input" id="search-input" type="text" placeholder="Search flows..." value="'+esc(searchQuery)+'"></div>';
1744
+
1745
+ h+='<div class="filter-chips">';
1746
+ var statuses=['passed','failed','skipped'];
1747
+ var statusLabels={passed:'Passed',failed:'Failed',skipped:'Skipped'};
1748
+ statuses.forEach(function(s){
1749
+ var cnt=flows.filter(function(f){return f.test.status===s}).length;
1750
+ var cls='filter-chip'+(currentFilter===s?' active':'')+(cnt===0?' filter-chip--dimmed':'');
1751
+ h+='<button class="'+cls+'" data-status="'+s+'">'+statusLabels[s]+' <span class="chip-count">'+cnt+'</span></button>';
1752
+ });
1753
+ h+='</div>';
1754
+
1755
+ if(currentFilter!=='all'||activeTagFilter){
1756
+ var parts=[];
1757
+ if(currentFilter!=='all')parts.push(currentFilter);
1758
+ if(activeTagFilter)parts.push('#'+activeTagFilter);
1759
+ h+='<span class="filter-indicator">Filtering: '+esc(parts.join(' + '))+'</span>';
1760
+ h+='<button class="filter-clear">Clear all</button>';
1761
+ }
1762
+
1763
+ var tagCounts=getTagCounts();
1764
+ var hasTagFilter=!!activeTagFilter;
1765
+ h+='<button class="filter-icon-btn" title="Tags &amp; filters">'
1766
+ +'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 3H2l8 9.46V19l4 2v-8.54L22 3z"/></svg>'
1767
+ +(hasTagFilter?'<span class="filter-icon-badge"></span>':'')
1768
+ +'</button>';
1769
+
1770
+ el.innerHTML=h;
1771
+
1772
+ renderFilterDrawerBody(tagCounts);
1773
+ }
1774
+
1775
+ /* \u2500\u2500 Render: Filter Drawer Body \u2500\u2500 */
1776
+ function renderFilterDrawerBody(tagCounts){
1777
+ var el=$('filter-drawer-body');if(!el)return;
1778
+ var tags=Object.keys(tagCounts).sort();
1779
+ if(tags.length===0){el.innerHTML='<div style="font-size:12px;color:var(--fg-2)">No tags found in flow metadata.</div>';return}
1780
+
1781
+ var h='<div class="filter-drawer-section">';
1782
+ h+='<span class="filter-drawer-section-label">Tags</span>';
1783
+ h+='<div class="filter-chips">';
1784
+ tags.forEach(function(t){
1785
+ var cnt=tagCounts[t];
1786
+ var cls='filter-chip'+(activeTagFilter===t?' active':'');
1787
+ h+='<button class="'+cls+'" data-tag="'+esc(t)+'">'+esc(t)+' <span class="chip-count">'+cnt+'</span></button>';
1788
+ });
1789
+ h+='</div></div>';
1790
+
1791
+ var specCounts={};
1792
+ flows.forEach(function(f){
1793
+ var key=f.test.filePath||f.entry.specFile||'';
1794
+ if(key)specCounts[key]=(specCounts[key]||0)+1;
1795
+ });
1796
+ var specs=Object.keys(specCounts).sort();
1797
+ if(specs.length>1){
1798
+ h+='<div class="filter-drawer-section">';
1799
+ h+='<span class="filter-drawer-section-label">Flow Files</span>';
1800
+ h+='<div class="filter-chips">';
1801
+ specs.forEach(function(sp){
1802
+ var short=sp.split(/[\\/\\\\]/).pop()||sp;
1803
+ h+='<button class="filter-chip" data-tag="'+esc(short)+'" title="'+esc(sp)+'">'+esc(short)+' <span class="chip-count">'+specCounts[sp]+'</span></button>';
1804
+ });
1805
+ h+='</div></div>';
1806
+ }
1807
+
1808
+ if(activeTagFilter){
1809
+ h+='<div class="filter-drawer-actions"><button class="filter-clear">Clear all filters</button></div>';
1810
+ }
1811
+
1812
+ el.innerHTML=h;
1813
+ }
1814
+
1815
+ /* \u2500\u2500 Render: Flow List \u2500\u2500 */
1816
+ function getFilteredFlows(){
1817
+ return flows.filter(function(f){
1818
+ if(currentFilter!=='all'&&f.test.status!==currentFilter)return false;
1819
+ if(activeTagFilter){
1820
+ var tags=(f.test.tags||[]).map(function(t){return t.toLowerCase()});
1821
+ if(tags.indexOf(activeTagFilter.toLowerCase())<0)return false;
1822
+ }
1823
+ if(searchQuery){
1824
+ var q=searchQuery.toLowerCase();
1825
+ var title=(f.test.title||'').toLowerCase();
1826
+ var tagStr=(f.test.tags||[]).join(' ').toLowerCase();
1827
+ var file=(f.test.filePath||'').toLowerCase();
1828
+ if(title.indexOf(q)<0&&tagStr.indexOf(q)<0&&file.indexOf(q)<0)return false;
1829
+ }
1830
+ return true;
1831
+ });
1832
+ }
1833
+
1834
+ function renderFlowList(){
1835
+ var el=$('flow-list');if(!el)return;
1836
+ var filtered=getFilteredFlows();
1837
+ if(filtered.length===0){el.innerHTML='<div class="no-tests">No flows match the current filter.</div>';return}
1838
+
1839
+ var groups={};
1840
+ filtered.forEach(function(f){
1841
+ var key=f.test.filePath||f.entry.specFile||'flows';
1842
+ if(!groups[key])groups[key]=[];
1843
+ groups[key].push(f);
1844
+ });
1845
+
1846
+ var h='';
1847
+ for(var key in groups){
1848
+ if(!groups.hasOwnProperty(key))continue;
1849
+ h+='<div class="file-group">';
1850
+ h+='<div class="file-group-header">'+esc(key)+'</div>';
1851
+ h+='<div class="file-group-card">';
1852
+ groups[key].forEach(function(f){
1853
+ var t=f.test;
1854
+ var badges='';
1855
+ if(f.entry.url&&f.entry.url!=='maestro-flow')badges+='<span class="trb trb-app">'+esc(f.entry.url)+'</span>';
1856
+ (t.tags||[]).forEach(function(tag){
1857
+ var low=tag.toLowerCase();
1858
+ if(low==='android'||low==='ios'||low==='web')badges+='<span class="trb trb-platform">'+esc(tag)+'</span>';
1859
+ else badges+='<span class="trb trb-tag">'+esc(tag)+'</span>';
1860
+ });
1861
+ var activeClass=f.idx===openFlowIdx?' active':'';
1862
+ h+='<div class="test-row'+activeClass+'" data-flow-idx="'+f.idx+'">'
1863
+ +'<div class="status-indicator si-'+esc(t.status)+'"></div>'
1864
+ +'<div class="test-row-info">'
1865
+ +'<div class="test-row-title">'+esc(t.title)+'</div>'
1866
+ +'<div class="test-row-badges">'+badges+'</div>'
1867
+ +(t.failure?'<div class="test-row-error">'+esc(t.failure.message||'')+'</div>':'')
1868
+ +'</div>'
1869
+ +'<div class="test-row-dur">'+fmtDur(t.duration)+'</div>'
1870
+ +'<svg class="test-row-arrow" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m9 18 6-6-6-6"/></svg>'
1871
+ +'</div>';
1872
+ });
1873
+ h+='</div></div>';
1874
+ }
1875
+ el.innerHTML=h;
1876
+ }
1877
+ `;
1878
+
1879
+ // src/html-js-drawer.ts
1880
+ var JS_DRAWER = `
1881
+ /* \u2500\u2500 Drawer Open/Close \u2500\u2500 */
1882
+ function openDrawer(flowIdx){
1883
+ openFlowIdx=flowIdx;
1884
+ renderFlowList();
1885
+ var flow=flows.find(function(f){return f.idx===flowIdx});
1886
+ if(!flow)return;
1887
+ $('drawer-backdrop').classList.add('open');
1888
+ $('drawer').classList.add('open');
1889
+ renderDrawerContent(flow);
1890
+ }
1891
+ function closeDrawer(){
1892
+ openFlowIdx=-1;
1893
+ renderFlowList();
1894
+ $('drawer-backdrop').classList.remove('open');
1895
+ $('drawer').classList.remove('open');
1896
+ }
1897
+
1898
+ function renderDrawerContent(flow){
1899
+ var tabs=['Overview','Steps','Assertions','Screenshots','AI Defects'];
1900
+ var h='<div class="seg-ctrl">';
1901
+ tabs.forEach(function(name,i){
1902
+ h+='<button class="seg-btn'+(i===0?' active':'')+'" data-seg="tab'+i+'">'+name+'</button>';
1903
+ });
1904
+ h+='</div>';
1905
+
1906
+ h+='<div class="seg-pane active" data-seg-pane="tab0">'+renderOverviewTab(flow)+'</div>';
1907
+ h+='<div class="seg-pane" data-seg-pane="tab1">'+renderStepsTab(flow)+'</div>';
1908
+ h+='<div class="seg-pane" data-seg-pane="tab2">'+renderAssertionsTab(flow)+'</div>';
1909
+ h+='<div class="seg-pane" data-seg-pane="tab3">'+renderScreenshotsTab()+'</div>';
1910
+ h+='<div class="seg-pane" data-seg-pane="tab4">'+renderAiDefectsTab()+'</div>';
1911
+
1912
+ $('drawer-body').innerHTML=h;
1913
+ }
1914
+
1915
+ /* \u2500\u2500 Overview Tab \u2500\u2500 */
1916
+ function renderOverviewTab(flow){
1917
+ var t=flow.test;
1918
+ var h='<div class="detail-header"><div class="detail-top">';
1919
+ h+='<span class="detail-status-badge dbg-'+esc(t.status)+'">'+esc(t.status)+'</span>';
1920
+ h+='<div class="detail-title-section"><div class="detail-title">'+esc(t.title)+'</div>';
1921
+ h+='<div class="detail-meta">';
1922
+ if(flow.entry.url&&flow.entry.url!=='maestro-flow')h+='<span class="dm-badge dm-app">'+esc(flow.entry.url)+'</span>';
1923
+ (t.tags||[]).forEach(function(tag){
1924
+ var low=tag.toLowerCase();
1925
+ if(low==='android'||low==='ios'||low==='web')h+='<span class="dm-badge dm-platform">'+esc(tag)+'</span>';
1926
+ else h+='<span class="dm-badge dm-tag">'+esc(tag)+'</span>';
1927
+ });
1928
+ h+='</div></div>';
1929
+ h+='<div class="detail-duration">'+fmtDur(t.duration)+'</div>';
1930
+ h+='</div>';
1931
+
1932
+ h+='<div class="detail-props">';
1933
+ h+='<span class="detail-props-k">Flow File</span><span class="detail-props-v">'+esc(t.filePath||flow.entry.specFile||'\\u2014')+'</span>';
1934
+ h+='<span class="detail-props-k">App ID</span><span class="detail-props-v">'+esc(flow.entry.url||'\\u2014')+'</span>';
1935
+ h+='<span class="detail-props-k">Suite</span><span class="detail-props-v">'+esc(t.suiteName||'\\u2014')+'</span>';
1936
+ h+='<span class="detail-props-k">Started</span><span class="detail-props-v">'+esc(t.startedAt?fmtDate(t.startedAt):'\\u2014')+'</span>';
1937
+ h+='<span class="detail-props-k">Test ID</span><span class="detail-props-v">'+esc(t.testId||'\\u2014')+'</span>';
1938
+ h+='</div></div>';
1939
+
1940
+ if(t.failure){
1941
+ h+='<div class="failure-panel">';
1942
+ h+='<div class="failure-panel-header"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="m15 9-6 6M9 9l6 6"/></svg> Failure Diagnostic</div>';
1943
+ h+='<div class="failure-message">'+esc(t.failure.message||'Unknown error')+'<button class="copy-btn" data-copy="'+esc(t.failure.message||'')+'">Copy</button></div>';
1944
+ h+='</div>';
1945
+ h+=renderRootCauseAnalysis(t,flow);
1946
+ }
1947
+
1948
+ if(t.tags&&t.tags.length>0){
1949
+ var subflows=[];
1950
+ (t.actions||[]).forEach(function(a){
1951
+ if(a.title&&a.title.indexOf('runFlow')>=0)subflows.push(a.title.replace('runFlow \\u2192 ',''));
1952
+ });
1953
+ if(subflows.length>0){
1954
+ h+='<div class="subflow-tree"><div class="sf-node">'+esc(t.filePath||t.title)+'</div>';
1955
+ subflows.forEach(function(sf){h+='<div class="sf-child"><div class="sf-node">\\u2514\\u2500 '+esc(sf)+' (subflow)</div></div>'});
1956
+ h+='</div>';
1957
+ }
1958
+ }
1959
+
1960
+ return h;
1961
+ }
1962
+
1963
+ /* \u2500\u2500 Root Cause Analysis \u2500\u2500 */
1964
+ function renderRootCauseAnalysis(t,flow){
1965
+ var msg=(t.failure&&t.failure.message)||'';
1966
+ var lower=msg.toLowerCase();
1967
+ var actions=t.actions||[];
1968
+ var failedSteps=actions.filter(function(a){return a.status==='failed'});
1969
+
1970
+ var analysis='';
1971
+ if(lower.indexOf('not found')>=0||lower.indexOf('not visible')>=0||lower.indexOf('could not find')>=0){
1972
+ var prevFailed=failedSteps.length>1;
1973
+ analysis+='<p>The test attempted to interact with an element that was not present in the view hierarchy.';
1974
+ if(prevFailed)analysis+=' The preceding step also failed, suggesting the target screen did not fully load.';
1975
+ analysis+='</p>';
1976
+ }else if(lower.indexOf('timeout')>=0||lower.indexOf('timed out')>=0){
1977
+ analysis+='<p>The operation exceeded its timeout threshold. This typically indicates a slow network response, a heavy UI render, or the target element appearing after the timeout window.</p>';
1978
+ }else if(lower.indexOf('assert')>=0){
1979
+ analysis+='<p>An assertion did not match the expected state. This could indicate a UI regression, dynamic content change, or a race condition between the app and the test.</p>';
1980
+ }else{
1981
+ analysis+='<p>Review the step timeline to identify the exact failing command and its preceding context.</p>';
1982
+ }
1983
+
1984
+ var h='<div class="fix-hint">';
1985
+ h+='<div class="fix-hint-header"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></svg> Root Cause Analysis</div>';
1986
+ h+='<div class="fix-hint-body">';
1987
+ h+='<div class="fix-hint-section"><div class="fix-hint-section-title">What Went Wrong</div>'+analysis+'</div>';
1988
+
1989
+ h+='<div class="fix-hint-section"><div class="fix-hint-section-title">Recommended Actions</div><ul>';
1990
+ if(lower.indexOf('not found')>=0||lower.indexOf('not visible')>=0){
1991
+ h+='<li>Add <code>extendedWaitUntil</code> before the interaction:</li>';
1992
+ h+='</ul><div class="fix-code">- extendedWaitUntil:\\n visible: "Pay Now"\\n timeout: 10000</div><ul>';
1993
+ h+='<li>Verify the selector with <strong>Maestro Studio</strong> on the target device</li>';
1994
+ h+='<li>Add an <code>assertVisible</code> guard before <code>tapOn</code></li>';
1995
+ h+='<li>Check if the element requires scrolling into view first</li>';
1996
+ h+='<li>Inspect network requests \\u2014 the backend API may be slow</li>';
1997
+ }else if(lower.indexOf('timeout')>=0||lower.indexOf('timed out')>=0){
1998
+ h+='<li>Increase timeout with <code>extendedWaitUntil</code> (default 5s may be too short)</li>';
1999
+ h+='<li>Check for loading spinners or network requests blocking the UI</li>';
2000
+ h+='<li>Run on a faster emulator or physical device to rule out performance</li>';
2001
+ h+='<li>Add <code>waitForAnimationToEnd</code> before the assertion</li>';
2002
+ }else if(lower.indexOf('assert')>=0){
2003
+ h+='<li>Verify the expected text/element exists on the current screen</li>';
2004
+ h+='<li>Check for dynamic content that changes between runs</li>';
2005
+ h+='<li>Use <code>assertWithAI</code> for fuzzy visual assertions</li>';
2006
+ h+='<li>Add <code>waitForAnimationToEnd</code> before <code>assertVisible</code></li>';
2007
+ }else{
2008
+ h+='<li>Review the step timeline for the exact failing command</li>';
2009
+ h+='<li>Run the flow in <strong>Maestro Studio</strong> to debug interactively</li>';
2010
+ h+='<li>Check device logs for crash traces or ANR</li>';
2011
+ h+='<li>Try <code>clearState</code> before <code>launchApp</code></li>';
2012
+ }
2013
+ h+='</ul></div>';
2014
+
2015
+ h+='</div></div>';
2016
+ return h;
2017
+ }
2018
+ `;
2019
+
2020
+ // src/html-js-steps.ts
2021
+ var JS_STEPS = `
2022
+ function renderStepsTab(flow){
2023
+ var actions=flow.test.actions||[];
2024
+ if(actions.length===0)return '<div class="no-tests">No step data available for this flow.</div>';
2025
+
2026
+ var failCount=actions.filter(function(a){return a.status==='failed'}).length;
2027
+ var slowCount=actions.filter(function(a){return a.duration>2000}).length;
2028
+ var maxDur=0;
2029
+ actions.forEach(function(a){if(a.duration>maxDur)maxDur=a.duration});
2030
+
2031
+ var h='<div class="steps-header">'+actions.length+' steps'
2032
+ +'<span class="steps-stat">'+failCount+' failed</span>'
2033
+ +(slowCount?'<span class="steps-stat">'+slowCount+' slow (&gt;2s)</span>':'')
2034
+ +'<span class="steps-stat">slowest: '+fmtDur(maxDur)+'</span></div>';
2035
+
2036
+ /* Mini waterfall */
2037
+ h+='<div class="steps-waterfall">';
2038
+ var wfMax=maxDur||1;
2039
+ actions.forEach(function(a){
2040
+ var pct=Math.max(1,Math.round((a.duration/wfMax)*100));
2041
+ var barCls=a.status==='failed'?'sw-bar-red':a.duration>2000?'sw-bar-amber':a.duration>500?'sw-bar-amber':'sw-bar-green';
2042
+ var nameStr=a.title||'step';
2043
+ if(nameStr.length>18)nameStr=nameStr.substring(0,18)+'\\u2026';
2044
+ h+='<div class="sw-row">'
2045
+ +'<div class="sw-name" title="'+esc(a.title)+'">'+esc(nameStr)+'</div>'
2046
+ +'<div class="sw-track"><div class="sw-bar '+barCls+'" style="width:'+pct+'%"></div></div>'
2047
+ +'<div class="sw-dur">'+fmtDur(a.duration)+'</div></div>';
2048
+ });
2049
+ h+='</div>';
2050
+
2051
+ /* Step list */
2052
+ actions.forEach(function(a,i){
2053
+ var isFailed=a.status==='failed';
2054
+ var isSlow=a.duration>2000&&!isFailed;
2055
+ var isFast=a.duration<=500&&!isFailed;
2056
+ var rowCls='cmd-step';
2057
+ if(isFailed)rowCls+=' cmd-step-failed';
2058
+ else if(isSlow)rowCls+=' cmd-step-slow';
2059
+ else if(isFast)rowCls+=' cmd-step-fast';
2060
+ var dotCls='cmd-dot '+(isFailed?'cmd-dot-fail':'cmd-dot-pass');
2061
+ h+='<div class="'+rowCls+'">';
2062
+ h+='<div class="'+dotCls+'"></div>';
2063
+ h+=getCmdBadge(a.category);
2064
+ h+='<div class="cmd-title" title="'+esc(a.title)+'">'+esc(a.title)+'</div>';
2065
+ if(isSlow||isFailed&&a.duration>2000)h+='<span class="cmd-badge cmd-badge-slow">SLOW</span>';
2066
+ h+='<div class="cmd-dur">'+fmtDur(a.duration)+'</div>';
2067
+ h+='</div>';
2068
+ if(a.error)h+='<div class="cmd-error">'+esc(a.error)+'</div>';
2069
+ if(i<actions.length-1)h+='<div class="cmd-connector"></div>';
2070
+ });
2071
+
2072
+ h+='<div class="steps-legend">';
2073
+ h+='<span><span class="cmd-badge cmd-badge-ui">UI</span> ui_action</span>';
2074
+ h+='<span><span class="cmd-badge cmd-badge-assert">ASSERT</span> assertion</span>';
2075
+ h+='<span><span class="cmd-badge cmd-badge-ai">AI</span> ai</span>';
2076
+ h+='<span><span class="cmd-badge cmd-badge-cmd">CMD</span> custom_step</span>';
2077
+ h+='<span><span class="cmd-badge cmd-badge-slow">SLOW</span> &gt; 2s</span>';
2078
+ h+='</div>';
2079
+ h+='<div class="steps-legend" style="margin-top:4px">';
2080
+ h+='<span>Duration: <span style="color:#22c55e;font-weight:700">&lt;500ms</span></span>';
2081
+ h+='<span style="color:#f59e0b;font-weight:700">500ms\\u20132s</span>';
2082
+ h+='<span style="color:#ef4444;font-weight:700">&gt;2s</span>';
2083
+ h+='</div>';
2084
+ return h;
2085
+ }
2086
+
2087
+ function getCmdBadge(cat){
2088
+ var m={ui_action:['UI','cmd-badge-ui'],assertion:['ASSERT','cmd-badge-assert'],navigation:['NAV','cmd-badge-nav'],custom_step:['CMD','cmd-badge-cmd'],ai:['AI','cmd-badge-ai'],device:['DEV','cmd-badge-device']};
2089
+ var pair=m[cat]||['CMD','cmd-badge-cmd'];
2090
+ return '<span class="cmd-badge '+pair[1]+'">'+pair[0]+'</span>';
2091
+ }
2092
+ `;
2093
+
2094
+ // src/html-js-assertions.ts
2095
+ var JS_ASSERTIONS = `
2096
+ function renderAssertionsTab(flow){
2097
+ var actions=flow.test.actions||[];
2098
+ var asserts=actions.filter(function(a){return a.category==='assertion'});
2099
+ if(asserts.length===0)return '<div class="no-tests">No assertions recorded for this flow.</div>';
2100
+
2101
+ var passCount=asserts.filter(function(a){return a.status==='passed'}).length;
2102
+ var failCount=asserts.length-passCount;
2103
+ var pct=Math.round((passCount/asserts.length)*100);
2104
+
2105
+ var h='<div class="assert-header">';
2106
+ h+='<div class="assert-ring">'+svgRing(pct,56,4,'#22c55e')+'</div>';
2107
+ h+='<div class="assert-stats"><strong>'+asserts.length+'</strong> assertions<br>';
2108
+ h+='<span style="color:#22c55e;font-weight:700">'+passCount+' passed</span> &middot; ';
2109
+ h+='<span style="color:#ef4444;font-weight:700">'+failCount+' failed</span></div>';
2110
+ h+='<div class="assert-bar-wrap"><div class="assert-bar"><div class="assert-bar-fill" style="width:'+pct+'%"></div></div>';
2111
+ h+='<div class="assert-pct">'+pct+'% pass rate</div></div>';
2112
+ h+='</div>';
2113
+
2114
+ h+='<table class="assert-table"><thead><tr><th>Result</th><th>Command</th><th>Duration</th></tr></thead><tbody>';
2115
+ asserts.forEach(function(a){
2116
+ var icon=a.status==='passed'?'\\u2713':'\\u2717';
2117
+ var cls=a.status==='passed'?'ar-pass':'ar-fail';
2118
+ h+='<tr><td class="assert-result '+cls+'">'+icon+'</td>';
2119
+ h+='<td style="font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:11px">'+esc(a.title)+'</td>';
2120
+ h+='<td class="cmd-dur">'+fmtDur(a.duration)+'</td></tr>';
2121
+ if(a.error)h+='<tr class="assert-error-row"><td></td><td colspan="2">'+esc(a.error)+'</td></tr>';
2122
+ });
2123
+ h+='</tbody></table>';
2124
+ return h;
2125
+ }
2126
+ `;
2127
+
2128
+ // src/html-js-ai-defects.ts
2129
+ var JS_AI_DEFECTS = `
2130
+ function renderAiDefectsTab(){
2131
+ if(aiDefects.length===0)return '<div class="ai-empty">\\u2714 No AI defects detected.</div>';
2132
+ var h='<div style="font-size:12px;color:var(--fg-1);margin-bottom:16px">'+aiDefects.length+' defect'+(aiDefects.length>1?'s':'')+' found by Maestro AI analysis</div>';
2133
+
2134
+ aiDefects.forEach(function(d){
2135
+ var sev=d.severity||'info';
2136
+ var type=(d.type||'ui').toLowerCase();
2137
+ h+='<div class="ai-card ai-card-'+sev+'">';
2138
+ h+='<div class="ai-card-header"><span class="ai-severity ai-sev-'+sev+'">'+esc(sev)+'</span><span class="ai-type">'+esc(d.type||'UI')+'</span></div>';
2139
+ h+='<div class="ai-desc">'+esc(d.description||'')+'</div>';
2140
+ h+='<div class="ai-fix"><div class="ai-fix-label">Fix Playbook</div><div class="ai-fix-body">'+getFixPlaybook(type,d)+'</div></div>';
2141
+ h+='</div>';
2142
+ });
2143
+ return h;
2144
+ }
2145
+
2146
+ function getFixPlaybook(type,d){
2147
+ if(type==='ui')return uiFixPlaybook(d);
2148
+ if(type==='spelling')return spellingFixPlaybook(d);
2149
+ if(type==='layout')return layoutFixPlaybook(d);
2150
+ if(type==='i18n')return i18nFixPlaybook(d);
2151
+ if(type==='accessibility')return a11yFixPlaybook(d);
2152
+ return genericFixPlaybook(d);
2153
+ }
2154
+
2155
+ function uiFixPlaybook(d){
2156
+ return '<div class="ai-fix-platform">Android (XML)</div>'
2157
+ +'<div class="ai-fix-code">android:layout_width="wrap_content"\\nandroid:minWidth="120dp"\\nandroid:paddingHorizontal="16dp"</div>'
2158
+ +'<div class="ai-fix-platform">Jetpack Compose</div>'
2159
+ +'<div class="ai-fix-code">Modifier\\n .widthIn(min = 120.dp)\\n .padding(horizontal = 16.dp)</div>'
2160
+ +'<div class="ai-fix-platform">Verify</div>'
2161
+ +'<div class="ai-fix-code">maestro test --device Pixel_4a ./flows</div>'
2162
+ +'<ul><li>Test on smallest supported screen (360dp width)</li>'
2163
+ +'<li>Run <code>assertNoDefectsWithAI</code> to catch regressions</li></ul>';
2164
+ }
2165
+
2166
+ function spellingFixPlaybook(d){
2167
+ var desc=d.description||'';
2168
+ var match=desc.match(/"([^"]+)"/);
2169
+ var typo=match?match[1]:'typo';
2170
+ return '<div class="ai-fix-platform">Find &amp; Replace</div>'
2171
+ +'<div class="ai-fix-code">grep -r "'+esc(typo)+'" --include="*.xml" --include="*.strings"\\ngrep -r "'+esc(typo)+'" --include="*.kt" --include="*.swift"</div>'
2172
+ +'<ul><li>Android: <code>res/values/strings.xml</code></li>'
2173
+ +'<li>iOS: <code>Localizable.strings</code></li>'
2174
+ +'<li>Add a CI linting rule for common typos</li></ul>';
2175
+ }
2176
+
2177
+ function layoutFixPlaybook(d){
2178
+ return '<div class="ai-fix-platform">Android (XML)</div>'
2179
+ +'<div class="ai-fix-code">android:maxLines="1"\\nandroid:ellipsize="end"</div>'
2180
+ +'<div class="ai-fix-platform">iOS (Swift)</div>'
2181
+ +'<div class="ai-fix-code">label.lineBreakMode = .byTruncatingTail\\nlabel.numberOfLines = 1</div>'
2182
+ +'<ul><li>Use ConstraintLayout / Auto Layout to prevent overlap</li>'
2183
+ +'<li>Test with long strings (20+ characters)</li></ul>';
2184
+ }
2185
+
2186
+ function i18nFixPlaybook(d){
2187
+ return '<ul><li>Audit translation files for missing keys</li>'
2188
+ +'<li>Run extraction tool to find untranslated strings</li>'
2189
+ +'<li>Verify all locales in CI with locale-specific flows</li></ul>'
2190
+ +'<div class="ai-fix-platform">Example Flow</div>'
2191
+ +'<div class="ai-fix-code">env:\\n LANG: fr_FR\\n---\\n- launchApp\\n- assertVisible: "Bienvenue"</div>';
2192
+ }
2193
+
2194
+ function a11yFixPlaybook(d){
2195
+ return '<div class="ai-fix-platform">Android</div>'
2196
+ +'<div class="ai-fix-code">android:contentDescription="1 item in cart"</div>'
2197
+ +'<div class="ai-fix-platform">iOS (Swift)</div>'
2198
+ +'<div class="ai-fix-code">cartBadge.accessibilityLabel = "1 item in cart"</div>'
2199
+ +'<ul><li>WCAG 2.1 SC 1.1.1: Non-text Content</li>'
2200
+ +'<li>Ensure 4.5:1 contrast ratio (SC 1.4.3)</li>'
2201
+ +'<li>Test with TalkBack (Android) / VoiceOver (iOS)</li></ul>';
2202
+ }
2203
+
2204
+ function genericFixPlaybook(d){
2205
+ return '<ul><li>Review the defect description and identify the affected screen</li>'
2206
+ +'<li>Reproduce on a physical device</li>'
2207
+ +'<li>Add <code>assertNoDefectsWithAI</code> for regression detection</li></ul>';
2208
+ }
2209
+ `;
2210
+
2211
+ // src/html-js-interactions.ts
2212
+ var JS_INTERACTIONS = `
2213
+ /* \u2500\u2500 Theme \u2500\u2500 */
2214
+ function applyTheme(){
2215
+ var pref=localStorage.getItem('tr-theme')||'system';
2216
+ var resolved=pref==='system'?(window.matchMedia('(prefers-color-scheme:light)').matches?'light':'dark'):pref;
2217
+ document.documentElement.setAttribute('data-theme',resolved);
2218
+ document.querySelectorAll('.theme-btn').forEach(function(b){
2219
+ b.classList.toggle('active',b.dataset.themeVal===pref);
2220
+ });
2221
+ }
2222
+
2223
+ /* \u2500\u2500 Screenshots Tab \u2500\u2500 */
2224
+ function renderScreenshotsTab(){
2225
+ if(screenshotPaths.length===0)return '<div class="screenshot-empty">No screenshots captured for this run.</div>';
2226
+ var h='<div class="screenshot-grid">';
2227
+ screenshotPaths.forEach(function(p,i){
2228
+ var name=p.split(/[\\/\\\\]/).pop()||'screenshot';
2229
+ var isFail=name.toLowerCase().indexOf('fail')>=0||name.toLowerCase().indexOf('error')>=0;
2230
+ h+='<div class="screenshot-card'+(isFail?' failure-shot':'')+'" data-lb-idx="'+i+'">'
2231
+ +'<img src="'+esc(p)+'" alt="'+esc(name)+'" loading="lazy" onerror="this.parentElement.style.display=\\'none\\'"/>'
2232
+ +'<div class="screenshot-card-label">'+(isFail?'Failure Screenshot':esc(name))+'</div></div>';
2233
+ });
2234
+ h+='</div>';
2235
+ return h;
2236
+ }
2237
+
2238
+ /* \u2500\u2500 Lightbox \u2500\u2500 */
2239
+ function openLightbox(idx){
2240
+ if(idx<0||idx>=screenshotPaths.length)return;
2241
+ var existing=document.querySelector('.lightbox-overlay');
2242
+ if(existing)existing.remove();
2243
+
2244
+ var name=screenshotPaths[idx].split(/[\\/\\\\]/).pop()||'screenshot';
2245
+ var div=document.createElement('div');
2246
+ div.className='lightbox-overlay';
2247
+ div.innerHTML='<img src="'+esc(screenshotPaths[idx])+'"/>'
2248
+ +'<button class="lightbox-close">&times;</button>'
2249
+ +(idx>0?'<button class="lightbox-nav lightbox-prev">&lsaquo;</button>':'')
2250
+ +(idx<screenshotPaths.length-1?'<button class="lightbox-nav lightbox-next">&rsaquo;</button>':'')
2251
+ +'<div class="lightbox-caption">'+esc(name)+' ('+(idx+1)+' / '+screenshotPaths.length+')</div>';
2252
+ document.body.appendChild(div);
2253
+
2254
+ function cleanup(){div.remove();document.removeEventListener('keydown',keyHandler)}
2255
+ function keyHandler(e){
2256
+ if(e.key==='Escape'){cleanup()}
2257
+ if(e.key==='ArrowLeft'&&idx>0){cleanup();openLightbox(idx-1)}
2258
+ if(e.key==='ArrowRight'&&idx<screenshotPaths.length-1){cleanup();openLightbox(idx+1)}
2259
+ }
2260
+ div.querySelector('.lightbox-close').addEventListener('click',cleanup);
2261
+ div.addEventListener('click',function(e){if(e.target===div)cleanup()});
2262
+ var prev=div.querySelector('.lightbox-prev');
2263
+ var next=div.querySelector('.lightbox-next');
2264
+ if(prev)prev.addEventListener('click',function(e){e.stopPropagation();cleanup();openLightbox(idx-1)});
2265
+ if(next)next.addEventListener('click',function(e){e.stopPropagation();cleanup();openLightbox(idx+1)});
2266
+ document.addEventListener('keydown',keyHandler);
2267
+ }
2268
+
2269
+ /* \u2500\u2500 Event Delegation \u2500\u2500 */
2270
+ document.addEventListener('click',function(e){
2271
+ var target=e.target;
2272
+
2273
+ /* Test row -> open drawer */
2274
+ var row=target.closest('.test-row');
2275
+ if(row){openDrawer(parseInt(row.dataset.flowIdx));return}
2276
+
2277
+ /* Waterfall row -> open drawer */
2278
+ var wfRow=target.closest('.waterfall-row');
2279
+ if(wfRow){openDrawer(parseInt(wfRow.dataset.wfIdx));return}
2280
+
2281
+ /* Drawer close */
2282
+ if(target.closest('#drawer-close')){closeDrawer();return}
2283
+ if(target.closest('#drawer-backdrop')){closeDrawer();return}
2284
+
2285
+ /* Filter chip (status) */
2286
+ var statusChip=target.closest('.filter-chip[data-status]');
2287
+ if(statusChip){
2288
+ var s=statusChip.dataset.status;
2289
+ currentFilter=currentFilter===s?'all':s;
2290
+ renderFilterBar();renderFlowList();
2291
+ return;
2292
+ }
2293
+
2294
+ /* Filter chip (tag \u2014 in filter drawer) */
2295
+ var tagChip=target.closest('.filter-chip[data-tag]');
2296
+ if(tagChip){
2297
+ var tag=tagChip.dataset.tag;
2298
+ activeTagFilter=activeTagFilter===tag?'':tag;
2299
+ renderFilterBar();renderFlowList();
2300
+ return;
2301
+ }
2302
+
2303
+ /* Filter icon -> open filter drawer */
2304
+ if(target.closest('.filter-icon-btn')){
2305
+ $('filter-drawer-backdrop').classList.add('open');
2306
+ $('filter-drawer').classList.add('open');
2307
+ return;
2308
+ }
2309
+
2310
+ /* Filter drawer close */
2311
+ if(target.closest('#filter-drawer-close')||target.closest('#filter-drawer-backdrop')){
2312
+ $('filter-drawer-backdrop').classList.remove('open');
2313
+ $('filter-drawer').classList.remove('open');
2314
+ return;
2315
+ }
2316
+
2317
+ /* Clear all filters */
2318
+ if(target.closest('.filter-clear')){
2319
+ currentFilter='all';searchQuery='';activeTagFilter='';
2320
+ $('filter-drawer-backdrop').classList.remove('open');
2321
+ $('filter-drawer').classList.remove('open');
2322
+ renderFilterBar();renderFlowList();
2323
+ return;
2324
+ }
2325
+
2326
+ /* Seg-ctrl tab switching */
2327
+ var segBtn=target.closest('.seg-btn');
2328
+ if(segBtn){
2329
+ var parent=segBtn.parentElement;
2330
+ if(parent&&parent.classList.contains('seg-ctrl')){
2331
+ var container=parent.parentElement;
2332
+ parent.querySelectorAll('.seg-btn').forEach(function(b){b.classList.remove('active')});
2333
+ segBtn.classList.add('active');
2334
+ container.querySelectorAll('.seg-pane').forEach(function(p){p.classList.remove('active')});
2335
+ var pane=container.querySelector('[data-seg-pane="'+segBtn.dataset.seg+'"]');
2336
+ if(pane)pane.classList.add('active');
2337
+ }
2338
+ return;
2339
+ }
2340
+
2341
+ /* Copy button */
2342
+ var copyBtn=target.closest('.copy-btn');
2343
+ if(copyBtn){
2344
+ e.stopPropagation();
2345
+ var text=copyBtn.dataset.copy||'';
2346
+ navigator.clipboard.writeText(text).then(function(){copyBtn.textContent='Copied!'});
2347
+ setTimeout(function(){copyBtn.textContent='Copy'},1500);
2348
+ return;
2349
+ }
2350
+
2351
+ /* Screenshot lightbox */
2352
+ var card=target.closest('.screenshot-card');
2353
+ if(card&&card.dataset.lbIdx!==undefined){openLightbox(parseInt(card.dataset.lbIdx));return}
2354
+ });
2355
+
2356
+ /* Theme buttons */
2357
+ document.querySelectorAll('.theme-btn').forEach(function(b){
2358
+ b.addEventListener('click',function(){
2359
+ localStorage.setItem('tr-theme',b.dataset.themeVal);
2360
+ applyTheme();
2361
+ });
2362
+ });
2363
+
2364
+ /* Search input */
2365
+ document.addEventListener('input',function(e){
2366
+ if(e.target&&e.target.id==='search-input'){
2367
+ searchQuery=e.target.value.toLowerCase();
2368
+ renderFlowList();
2369
+ }
2370
+ });
2371
+
2372
+ /* Escape to close drawer */
2373
+ document.addEventListener('keydown',function(e){
2374
+ if(e.key==='Escape'&&$('drawer').classList.contains('open'))closeDrawer();
2375
+ });
2376
+ `;
2377
+
2378
+ // src/html-template.ts
2379
+ var JS = `
2380
+ (function(){
2381
+ var payload=JSON.parse(document.getElementById('report-data').textContent);
2382
+ var report=payload.report;
2383
+ var aiDefects=payload.aiDefects||[];
2384
+ var screenshotPaths=payload.screenshotPaths||[];
2385
+
2386
+ ${JS_RENDER}
2387
+ ${JS_DRAWER}
2388
+ ${JS_STEPS}
2389
+ ${JS_ASSERTIONS}
2390
+ ${JS_AI_DEFECTS}
2391
+ ${JS_INTERACTIONS}
2392
+
2393
+ applyTheme();
2394
+ renderRunMeta();
2395
+ renderHeroStrip();
2396
+ renderWaterfall();
2397
+ renderFilterBar();
2398
+ renderFlowList();
2399
+
2400
+ var _lo=document.getElementById('loading-overlay');if(_lo)_lo.remove();
2401
+ })();`;
2402
+ function renderHtmlDocument(reportJson) {
2403
+ const safeJson = reportJson.replace(/<\//g, "<\\/");
2404
+ return `<!-- TestRelic Maestro Report \u2014 self-contained, no external dependencies -->
2405
+ <!DOCTYPE html>
2406
+ <html lang="en" data-theme="">
2407
+ <head>
2408
+ <meta charset="UTF-8">
2409
+ <meta name="viewport" content="width=device-width,initial-scale=1">
2410
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src data: blob: file: 'self'; media-src blob: 'self'; connect-src 'self';">
2411
+ <title>TestRelic Maestro Test Report</title>
2412
+ <link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(LOGO_SVG_RAW).toString("base64")}">
2413
+ <style>${CSS}</style>
2414
+ <script>(function(){var p=localStorage.getItem('tr-theme')||'system';var t=p==='system'?(window.matchMedia('(prefers-color-scheme:light)').matches?'light':'dark'):p;document.documentElement.setAttribute('data-theme',t);})()</script>
2415
+ </head>
2416
+ <body>
2417
+ <div class="wrap">
2418
+ <div class="top-bar">
2419
+ <div class="brand">
2420
+ ${LOGO_SVG}
2421
+ <div class="brand-text">
2422
+ <span class="brand-title">TestRelic AI</span>
2423
+ <span class="brand-sub">Maestro Test Report</span>
2424
+ </div>
2425
+ </div>
2426
+ <div class="run-meta" id="run-meta"></div>
2427
+ <div class="top-bar-actions">
2428
+ <a class="cta-btn" href="https://testrelic.ai" target="_blank" rel="noopener noreferrer"><svg class="cta-icon" viewBox="0 0 16 16" fill="none"><path d="M8 1l1.545 4.955L14.5 7.5l-4.955 1.545L8 14l-1.545-4.955L1.5 7.5l4.955-1.545L8 1z" fill="currentColor"/></svg>Advanced Insights with AI<span style="color:var(--fg-2);margin:0 2px">&ndash;</span><strong>Get Started</strong><svg class="cta-arrow" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M2.5 6h7M6.5 3l3 3-3 3"/></svg></a>
2429
+ <div class="theme-toggle">
2430
+ <button class="theme-btn" data-theme-val="system" title="System"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8M12 17v4"/></svg></button>
2431
+ <button class="theme-btn" data-theme-val="light" title="Light"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="5"/><path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/></svg></button>
2432
+ <button class="theme-btn" data-theme-val="dark" title="Dark"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg></button>
2433
+ </div>
2434
+ </div>
2435
+ </div>
2436
+
2437
+ <div id="hero-strip" class="hero-strip"></div>
2438
+ <div id="waterfall" class="waterfall-card"></div>
2439
+ <div id="filter-bar" class="filter-bar"></div>
2440
+ <div id="flow-list"></div>
2441
+
2442
+ <div class="report-footer">
2443
+ Generated by <a href="https://testrelic.ai">TestRelic AI</a> &middot; <code>@testrelic/maestro-analytics</code> &middot; <a href="https://docs.testrelic.ai">Documentation</a>
2444
+ </div>
2445
+ </div>
2446
+
2447
+ <div class="loading-overlay" id="loading-overlay"><div class="loading-spinner"></div><div class="loading-text">Loading report...</div></div>
2448
+ <div class="filter-drawer-backdrop" id="filter-drawer-backdrop"></div>
2449
+ <aside class="filter-drawer" id="filter-drawer">
2450
+ <div class="filter-drawer-bar">
2451
+ <span class="filter-drawer-title">Filters</span>
2452
+ <button class="filter-drawer-close" id="filter-drawer-close">&times;</button>
2453
+ </div>
2454
+ <div class="filter-drawer-body" id="filter-drawer-body"></div>
2455
+ </aside>
2456
+ <div class="drawer-backdrop" id="drawer-backdrop"></div>
2457
+ <aside class="drawer" id="drawer">
2458
+ <div class="drawer-bar">
2459
+ <span class="drawer-bar-title">Flow Details</span>
2460
+ <button class="drawer-close" id="drawer-close">&times;</button>
2461
+ </div>
2462
+ <div class="drawer-body" id="drawer-body"></div>
2463
+ </aside>
2464
+ <script id="report-data" type="application/json">${safeJson}</script>
2465
+ <script>${JS}</script>
2466
+ </body>
2467
+ </html>`;
2468
+ }
2469
+
2470
+ // src/html-report.ts
2471
+ function generateHtmlReport(report, aiDefects, screenshotPaths, outputPath) {
2472
+ const htmlPath = (0, import_node_path8.resolve)(outputPath);
2473
+ const htmlDir = (0, import_node_path8.dirname)(htmlPath);
2474
+ if (!(0, import_node_fs10.existsSync)(htmlDir)) (0, import_node_fs10.mkdirSync)(htmlDir, { recursive: true });
2475
+ const payload = { report, aiDefects, screenshotPaths };
2476
+ const reportJson = JSON.stringify(payload);
2477
+ const html = renderHtmlDocument(reportJson);
2478
+ (0, import_node_fs10.writeFileSync)(htmlPath, html, "utf-8");
2479
+ }
2480
+
2481
+ // src/console-summary.ts
2482
+ var BOX_WIDTH = 62;
2483
+ function pad(text) {
2484
+ const padding = BOX_WIDTH - 2 - text.length;
2485
+ return padding > 0 ? text + " ".repeat(padding) : text;
2486
+ }
2487
+ function line(text) {
2488
+ return `\u2502 ${pad(text)} \u2502
2489
+ `;
2490
+ }
2491
+ function printConsoleSummary(summary, outputPath, htmlReportPath, quiet, aiDefects) {
2492
+ if (quiet) return;
2493
+ if (summary.total === 0) return;
2494
+ const top = `\u250C${"\u2500".repeat(BOX_WIDTH)}\u2510
2495
+ `;
2496
+ const bottom = `\u2514${"\u2500".repeat(BOX_WIDTH)}\u2518
2497
+ `;
2498
+ const blank = line("");
2499
+ let output = top;
2500
+ output += line("TestRelic AI - Maestro Test Report");
2501
+ output += blank;
2502
+ const parts = [];
2503
+ if (summary.passed > 0) parts.push(`${summary.passed} \u2713`);
2504
+ if (summary.failed > 0) parts.push(`${summary.failed} \u2717`);
2505
+ if (summary.flaky > 0) parts.push(`${summary.flaky} \u26A0`);
2506
+ if (summary.skipped > 0) parts.push(`${summary.skipped} skipped`);
2507
+ if (summary.timedout > 0) parts.push(`${summary.timedout} timedout`);
2508
+ output += line(`Flows: ${summary.total} total (${parts.join(" ")})`);
2509
+ if (summary.totalAssertions > 0) {
2510
+ output += line(
2511
+ `Assertions: ${summary.totalAssertions} total (${summary.passedAssertions} \u2713 ${summary.failedAssertions} \u2717)`
2512
+ );
2513
+ }
2514
+ if (summary.totalActionSteps > 0) {
2515
+ const catParts = [];
2516
+ const catMap = summary.actionStepsByCategory;
2517
+ if (catMap["ui_action"]) catParts.push(`${catMap["ui_action"]} UI`);
2518
+ if (catMap["navigation"]) catParts.push(`${catMap["navigation"]} nav`);
2519
+ if (catMap["custom_step"]) catParts.push(`${catMap["custom_step"]} custom`);
2520
+ const catStr = catParts.length > 0 ? ` (${catParts.join(" ")})` : "";
2521
+ output += line(`Steps: ${summary.totalActionSteps} total${catStr}`);
2522
+ }
2523
+ if (aiDefects && aiDefects.length > 0) {
2524
+ const critical = aiDefects.filter((d) => d.severity === "critical").length;
2525
+ const warning = aiDefects.filter((d) => d.severity === "warning").length;
2526
+ const info = aiDefects.filter((d) => d.severity === "info").length;
2527
+ const defectParts = [];
2528
+ if (critical > 0) defectParts.push(`${critical} critical`);
2529
+ if (warning > 0) defectParts.push(`${warning} warning`);
2530
+ if (info > 0) defectParts.push(`${info} info`);
2531
+ output += line(`AI Defects: ${aiDefects.length} found (${defectParts.join(" ")})`);
2532
+ }
2533
+ output += line(`Report: ${htmlReportPath}`);
2534
+ output += line(`Data: ${outputPath}`);
2535
+ output += bottom;
2536
+ output += "For more information visit us at https://docs.testrelic.ai\n";
2537
+ process.stderr.write(output);
2538
+ }
2539
+
2540
+ // src/browser-open.ts
2541
+ var import_node_child_process2 = require("child_process");
2542
+ function openInBrowser(filePath) {
2543
+ const platform = process.platform;
2544
+ let command;
2545
+ if (platform === "darwin") {
2546
+ command = `open "${filePath}"`;
2547
+ } else if (platform === "win32") {
2548
+ command = `start "" "${filePath}"`;
2549
+ } else {
2550
+ command = `xdg-open "${filePath}"`;
2551
+ }
2552
+ (0, import_node_child_process2.exec)(command, () => {
2553
+ });
2554
+ }
2555
+
2556
+ // src/cloud-client.ts
2557
+ var import_node_fs13 = require("fs");
2558
+ var import_node_path11 = require("path");
2559
+ var import_node_crypto2 = require("crypto");
2560
+
2561
+ // src/cloud-auth.ts
2562
+ var import_core3 = require("@testrelic/core");
2563
+ var LOCALHOST_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "0.0.0.0"]);
2564
+ function enforceHttps(endpoint) {
2565
+ const url = new URL(endpoint);
2566
+ if (url.protocol === "https:") return;
2567
+ if (url.protocol === "http:" && LOCALHOST_HOSTS.has(url.hostname)) return;
2568
+ throw (0, import_core3.createError)(
2569
+ import_core3.ErrorCode.CLOUD_CONFIG_INVALID,
2570
+ `HTTPS is required for cloud communication. Got: ${url.protocol}//${url.hostname}`
2571
+ );
2572
+ }
2573
+ var HEALTH_CHECK_TIMEOUT_MS = 3e3;
2574
+ async function healthCheck(endpoint) {
2575
+ const controller = new AbortController();
2576
+ const timer = setTimeout(() => controller.abort(), HEALTH_CHECK_TIMEOUT_MS);
2577
+ try {
2578
+ const response = await fetch(`${endpoint}/health`, {
2579
+ method: "GET",
2580
+ signal: controller.signal
2581
+ });
2582
+ return response.ok;
2583
+ } catch {
2584
+ return false;
2585
+ } finally {
2586
+ clearTimeout(timer);
2587
+ }
2588
+ }
2589
+ async function sleep(ms) {
2590
+ return new Promise((resolve5) => setTimeout(resolve5, ms));
2591
+ }
2592
+ async function parseCloudError(response) {
2593
+ try {
2594
+ const body = await response.json();
2595
+ const error = body.error;
2596
+ if (error && typeof error.message === "string") {
2597
+ return error.message;
2598
+ }
2599
+ } catch {
2600
+ }
2601
+ return `HTTP ${response.status}`;
2602
+ }
2603
+ async function exchangeToken(endpoint, apiKey, timeout) {
2604
+ const controller = new AbortController();
2605
+ const timer = setTimeout(() => controller.abort(), timeout);
2606
+ try {
2607
+ const response = await fetch(`${endpoint}/sdk/auth/token`, {
2608
+ method: "POST",
2609
+ headers: { "Content-Type": "application/json" },
2610
+ body: JSON.stringify({ apiKey }),
2611
+ signal: controller.signal
2612
+ });
2613
+ if (response.ok) {
2614
+ const body = await response.json();
2615
+ return {
2616
+ accessToken: body.accessToken,
2617
+ refreshToken: body.refreshToken,
2618
+ expiresIn: body.expiresIn,
2619
+ orgId: body.orgId,
2620
+ orgName: body.orgName,
2621
+ userId: body.userId,
2622
+ userName: body.userName
2623
+ };
2624
+ }
2625
+ if (response.status === 429) {
2626
+ const retryAfter = response.headers.get("Retry-After");
2627
+ const waitMs = retryAfter ? parseInt(retryAfter, 10) * 1e3 : 5e3;
2628
+ if (!isNaN(waitMs) && waitMs > 0) {
2629
+ await sleep(waitMs);
2630
+ const retryResponse = await fetch(`${endpoint}/sdk/auth/token`, {
2631
+ method: "POST",
2632
+ headers: { "Content-Type": "application/json" },
2633
+ body: JSON.stringify({ apiKey }),
2634
+ signal: controller.signal
2635
+ });
2636
+ if (retryResponse.ok) {
2637
+ const body = await retryResponse.json();
2638
+ return {
2639
+ accessToken: body.accessToken,
2640
+ refreshToken: body.refreshToken,
2641
+ expiresIn: body.expiresIn,
2642
+ orgId: body.orgId,
2643
+ orgName: body.orgName,
2644
+ userId: body.userId,
2645
+ userName: body.userName
2646
+ };
2647
+ }
2648
+ }
2649
+ return { code: "rate_limited", message: "Rate limited during token exchange.", statusCode: 429 };
2650
+ }
2651
+ if (response.status === 400) {
2652
+ const errorMessage2 = await parseCloudError(response);
2653
+ return { code: "validation_error", message: errorMessage2, statusCode: 400 };
2654
+ }
2655
+ if (response.status === 401) {
2656
+ return { code: "invalid_key", message: "API key is invalid or has been revoked.", statusCode: 401 };
2657
+ }
2658
+ if (response.status === 403) {
2659
+ return { code: "expired_key", message: "API key has expired.", statusCode: 403 };
2660
+ }
2661
+ const errorMessage = await parseCloudError(response);
2662
+ return { code: "server_error", message: errorMessage, statusCode: response.status };
2663
+ } catch (err) {
2664
+ if (err instanceof DOMException && err.name === "AbortError") {
2665
+ return { code: "timeout", message: "Token exchange timed out.", statusCode: null };
2666
+ }
2667
+ return { code: "network_error", message: "Failed to reach cloud for token exchange.", statusCode: null };
2668
+ } finally {
2669
+ clearTimeout(timer);
2670
+ }
2671
+ }
2672
+ function isAuthError(result) {
2673
+ return "code" in result && typeof result.code === "string" && ["invalid_key", "expired_key", "validation_error", "rate_limited", "server_error", "network_error", "timeout"].includes(result.code);
2674
+ }
2675
+ async function refreshAccessToken(endpoint, currentRefreshToken, timeout) {
2676
+ const controller = new AbortController();
2677
+ const timer = setTimeout(() => controller.abort(), timeout);
2678
+ try {
2679
+ let response = await fetch(`${endpoint}/sdk/auth/refresh`, {
2680
+ method: "POST",
2681
+ headers: { "Content-Type": "application/json" },
2682
+ body: JSON.stringify({ refreshToken: currentRefreshToken }),
2683
+ signal: controller.signal
2684
+ });
2685
+ if (response.status === 429) {
2686
+ const retryAfter = response.headers.get("Retry-After");
2687
+ const waitMs = retryAfter ? parseInt(retryAfter, 10) * 1e3 : 5e3;
2688
+ if (!isNaN(waitMs) && waitMs > 0) {
2689
+ await sleep(waitMs);
2690
+ response = await fetch(`${endpoint}/sdk/auth/refresh`, {
2691
+ method: "POST",
2692
+ headers: { "Content-Type": "application/json" },
2693
+ body: JSON.stringify({ refreshToken: currentRefreshToken }),
2694
+ signal: controller.signal
2695
+ });
2696
+ }
2697
+ }
2698
+ if (!response.ok) return null;
2699
+ const body = await response.json();
2700
+ return {
2701
+ accessToken: body.accessToken,
2702
+ refreshToken: body.refreshToken,
2703
+ expiresIn: body.expiresIn
2704
+ };
2705
+ } catch {
2706
+ return null;
2707
+ } finally {
2708
+ clearTimeout(timer);
2709
+ }
2710
+ }
2711
+ async function resolveRepo(endpoint, accessToken, gitId, displayName, timeout, branch) {
2712
+ const controller = new AbortController();
2713
+ const timer = setTimeout(() => controller.abort(), timeout);
2714
+ try {
2715
+ const requestBody = { gitId, displayName };
2716
+ if (branch) requestBody.branch = branch;
2717
+ const response = await fetch(`${endpoint}/repos/resolve`, {
2718
+ method: "POST",
2719
+ headers: {
2720
+ "Content-Type": "application/json",
2721
+ "Authorization": `Bearer ${accessToken}`
2722
+ },
2723
+ body: JSON.stringify(requestBody),
2724
+ signal: controller.signal
2725
+ });
2726
+ if (!response.ok) return null;
2727
+ const responseBody = await response.json();
2728
+ return {
2729
+ repoId: responseBody.repoId,
2730
+ displayName: responseBody.displayName
2731
+ };
2732
+ } catch {
2733
+ return null;
2734
+ } finally {
2735
+ clearTimeout(timer);
2736
+ }
2737
+ }
2738
+
2739
+ // src/git-metadata.ts
2740
+ var import_node_child_process3 = require("child_process");
2741
+ var import_node_fs11 = require("fs");
2742
+ var import_node_path9 = require("path");
2743
+ var GIT_TIMEOUT_MS = 5e3;
2744
+ function execGit(command, cwd) {
2745
+ try {
2746
+ const result = (0, import_node_child_process3.execSync)(command, {
2747
+ cwd,
2748
+ timeout: GIT_TIMEOUT_MS,
2749
+ encoding: "utf-8",
2750
+ stdio: ["pipe", "pipe", "pipe"]
2751
+ });
2752
+ return result.trim() || null;
2753
+ } catch {
2754
+ return null;
2755
+ }
2756
+ }
2757
+ function collectGitMetadata(cwd) {
2758
+ const branch = execGit("git rev-parse --abbrev-ref HEAD", cwd);
2759
+ const commitSha = execGit("git rev-parse --short HEAD", cwd);
2760
+ const commitMessage = execGit("git log -1 --pretty=%s", cwd);
2761
+ const commitAuthor = execGit("git log -1 --format=%an", cwd) ?? execGit("git config user.name", cwd);
2762
+ const rawRemoteUrl = getRemoteUrl(cwd);
2763
+ const remoteUrl = rawRemoteUrl ? normalizeGitRemoteUrl(rawRemoteUrl) : null;
2764
+ return { branch, commitSha, commitMessage, commitAuthor, remoteUrl };
2765
+ }
2766
+ function getRemoteUrl(cwd) {
2767
+ const originUrl = execGit("git remote get-url origin", cwd);
2768
+ if (originUrl) return originUrl;
2769
+ const remotes = execGit("git remote", cwd);
2770
+ if (!remotes) return null;
2771
+ const firstRemote = remotes.split("\n")[0]?.trim();
2772
+ if (!firstRemote) return null;
2773
+ return execGit(`git remote get-url ${firstRemote}`, cwd);
2774
+ }
2775
+ function normalizeGitRemoteUrl(url) {
2776
+ let normalized = url.trim();
2777
+ normalized = normalized.replace(/^[a-z+]+:\/\//, "");
2778
+ normalized = normalized.replace(/^[^@]+@/, "");
2779
+ normalized = normalized.replace(/:(?!\d)/, "/");
2780
+ normalized = normalized.replace(/\.git$/, "");
2781
+ normalized = normalized.replace(/\/+$/, "");
2782
+ normalized = normalized.replace(/^[^@/]+@/, "");
2783
+ return normalized.toLowerCase();
2784
+ }
2785
+ function deriveRepoDisplayName(normalizedUrl) {
2786
+ const segments = normalizedUrl.split("/").filter(Boolean);
2787
+ return segments[segments.length - 1] ?? normalizedUrl;
2788
+ }
2789
+ function readPackageJsonName(dirPath) {
2790
+ try {
2791
+ const raw = (0, import_node_fs11.readFileSync)((0, import_node_path9.join)(dirPath, "package.json"), "utf-8");
2792
+ const pkg = JSON.parse(raw);
2793
+ return typeof pkg.name === "string" && pkg.name.length > 0 ? pkg.name : null;
2794
+ } catch {
2795
+ return null;
2796
+ }
2797
+ }
2798
+ function deriveNonGitProjectId(dirPath) {
2799
+ const pkgName = readPackageJsonName(dirPath);
2800
+ if (pkgName) return pkgName;
2801
+ return `local/${(0, import_node_path9.basename)(dirPath)}`;
2802
+ }
2803
+
2804
+ // src/cloud-queue.ts
2805
+ var import_node_fs12 = require("fs");
2806
+ var import_node_path10 = require("path");
2807
+ var import_core4 = require("@testrelic/core");
2808
+ var QUEUE_ENTRY_VERSION = "1.0.0";
2809
+ var FLUSH_BATCH_SIZE = 10;
2810
+ function writeToQueue(queueDirectory, runId, type, reason, targetEndpoint, method, payload, headers) {
2811
+ try {
2812
+ (0, import_node_fs12.mkdirSync)(queueDirectory, { recursive: true });
2813
+ const timestamp = Date.now();
2814
+ const filename = `${timestamp}-${runId}-${type}.json`;
2815
+ const filePath = (0, import_node_path10.join)(queueDirectory, filename);
2816
+ const entry = { version: QUEUE_ENTRY_VERSION, queuedAt: new Date(timestamp).toISOString(), reason, retryCount: 0, targetEndpoint, method, payload, headers };
2817
+ const tmpPath = filePath + ".tmp";
2818
+ (0, import_node_fs12.writeFileSync)(tmpPath, JSON.stringify(entry, null, 2), "utf-8");
2819
+ (0, import_node_fs12.renameSync)(tmpPath, filePath);
2820
+ } catch (err) {
2821
+ const code = err.code;
2822
+ if (code === "ENOSPC") {
2823
+ process.stderr.write("\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.\n");
2824
+ } else {
2825
+ process.stderr.write("\u26A0 TestRelic: Unable to queue upload data.\n");
2826
+ }
2827
+ }
2828
+ }
2829
+ async function flushQueue(queueDirectory, endpoint, accessToken) {
2830
+ let files;
2831
+ try {
2832
+ files = (0, import_node_fs12.readdirSync)(queueDirectory).filter((f) => f.endsWith(".json") && !f.endsWith(".tmp")).sort();
2833
+ } catch {
2834
+ return;
2835
+ }
2836
+ if (files.length === 0) return;
2837
+ const batches = [];
2838
+ for (let i = 0; i < files.length; i += FLUSH_BATCH_SIZE) {
2839
+ batches.push(files.slice(i, i + FLUSH_BATCH_SIZE));
2840
+ }
2841
+ for (const batch of batches) {
2842
+ for (const file of batch) {
2843
+ const filePath = (0, import_node_path10.join)(queueDirectory, file);
2844
+ try {
2845
+ const stat = (0, import_node_fs12.statSync)(filePath);
2846
+ if (!stat.isFile()) continue;
2847
+ const raw = (0, import_node_fs12.readFileSync)(filePath, "utf-8");
2848
+ const entry = JSON.parse(raw);
2849
+ if (!(0, import_core4.isValidQueueEntry)(entry)) {
2850
+ (0, import_node_fs12.unlinkSync)(filePath);
2851
+ continue;
2852
+ }
2853
+ const queueEntry = entry;
2854
+ const response = await fetch(queueEntry.targetEndpoint, {
2855
+ method: queueEntry.method,
2856
+ headers: { ...queueEntry.headers, "Authorization": `Bearer ${accessToken}` },
2857
+ body: JSON.stringify(queueEntry.payload)
2858
+ });
2859
+ if (response.ok) {
2860
+ (0, import_node_fs12.unlinkSync)(filePath);
2861
+ } else {
2862
+ return;
2863
+ }
2864
+ } catch {
2865
+ return;
2866
+ }
2867
+ }
2868
+ }
2869
+ }
2870
+ function cleanupExpiredQueue(queueDirectory, maxAge) {
2871
+ try {
2872
+ const files = (0, import_node_fs12.readdirSync)(queueDirectory).filter((f) => f.endsWith(".json") && !f.endsWith(".tmp"));
2873
+ const now = Date.now();
2874
+ for (const file of files) {
2875
+ const filePath = (0, import_node_path10.join)(queueDirectory, file);
2876
+ try {
2877
+ const raw = (0, import_node_fs12.readFileSync)(filePath, "utf-8");
2878
+ const entry = JSON.parse(raw);
2879
+ const queuedAt = entry.queuedAt;
2880
+ if (typeof queuedAt === "string") {
2881
+ const queuedTime = new Date(queuedAt).getTime();
2882
+ if (now - queuedTime > maxAge) (0, import_node_fs12.unlinkSync)(filePath);
2883
+ }
2884
+ } catch {
2885
+ try {
2886
+ (0, import_node_fs12.unlinkSync)(filePath);
2887
+ } catch {
2888
+ }
2889
+ }
2890
+ }
2891
+ } catch {
2892
+ }
2893
+ }
2894
+
2895
+ // src/cloud-client.ts
2896
+ var TOKEN_REFRESH_BUFFER_MS = 3e5;
2897
+ var PROJECT_CACHE_TTL_MS = 864e5;
2898
+ var HEALTH_CHECK_INTERVAL_MS = 6e4;
2899
+ var FLUSH_TIMEOUT_MS = 3e4;
2900
+ var DASHBOARD_SETTINGS_URL = "https://platform.testrelic.ai/settings/api-keys";
2901
+ var CloudClient = class {
2902
+ constructor(cloudConfig) {
2903
+ this.gitMetadata = null;
2904
+ this.repoId = null;
2905
+ this.failureReason = null;
2906
+ this.flushPromise = null;
2907
+ this.healthCheckTimer = null;
2908
+ this.config = cloudConfig;
2909
+ this.authState = {
2910
+ mode: "pending",
2911
+ accessToken: null,
2912
+ refreshToken: null,
2913
+ expiresAt: null,
2914
+ orgId: null,
2915
+ orgName: null,
2916
+ userId: null,
2917
+ userName: null
2918
+ };
2919
+ }
2920
+ async initialize() {
2921
+ if (!this.config || !this.config.apiKey) {
2922
+ this.setLocalMode("no_api_key");
2923
+ process.stderr.write("\u2139 TestRelic: No API key configured. Running in local mode.\n");
2924
+ return;
2925
+ }
2926
+ try {
2927
+ enforceHttps(this.config.endpoint);
2928
+ this.gitMetadata = collectGitMetadata();
2929
+ const healthy = await healthCheck(this.config.endpoint);
2930
+ if (!healthy) {
2931
+ this.setLocalMode("cloud_unreachable");
2932
+ process.stderr.write("\u26A0 TestRelic: Cloud unreachable. Switching to local mode.\n");
2933
+ return;
2934
+ }
2935
+ const result = await exchangeToken(this.config.endpoint, this.config.apiKey, this.config.timeout);
2936
+ if (isAuthError(result)) {
2937
+ this.handleAuthError(result.code, result.statusCode);
2938
+ return;
2939
+ }
2940
+ const tokenResult = result;
2941
+ this.authState = {
2942
+ mode: "cloud",
2943
+ accessToken: tokenResult.accessToken,
2944
+ refreshToken: tokenResult.refreshToken,
2945
+ expiresAt: Date.now() + tokenResult.expiresIn * 1e3,
2946
+ orgId: tokenResult.orgId,
2947
+ orgName: tokenResult.orgName,
2948
+ userId: tokenResult.userId,
2949
+ userName: tokenResult.userName
2950
+ };
2951
+ process.stderr.write(`\u2713 TestRelic: Connected to cloud (${tokenResult.orgName} / ${tokenResult.userName})
2952
+ `);
2953
+ await this.resolveRepoId();
2954
+ if (this.config.queueDirectory) {
2955
+ cleanupExpiredQueue(this.config.queueDirectory, this.config.queueMaxAge);
2956
+ this.startBackgroundFlush();
2957
+ }
2958
+ this.startHealthCheck();
2959
+ } catch (err) {
2960
+ this.setLocalMode("unexpected_error");
2961
+ process.stderr.write(`\u26A0 TestRelic: Unexpected error during cloud initialization. ${err instanceof Error ? err.message : String(err)}
2962
+ `);
2963
+ }
2964
+ }
2965
+ getMode() {
2966
+ return this.authState.mode;
2967
+ }
2968
+ isCloudMode() {
2969
+ return this.authState.mode === "cloud";
2970
+ }
2971
+ isLocalMode() {
2972
+ return this.authState.mode === "local";
2973
+ }
2974
+ getAccessToken() {
2975
+ return this.authState.accessToken;
2976
+ }
2977
+ getRepoId() {
2978
+ return this.repoId;
2979
+ }
2980
+ getGitMetadata() {
2981
+ return this.gitMetadata;
2982
+ }
2983
+ getConfig() {
2984
+ return this.config;
2985
+ }
2986
+ getFailureReason() {
2987
+ return this.failureReason;
2988
+ }
2989
+ getEndpoint() {
2990
+ return this.config?.endpoint ?? "https://platform.testrelic.ai/api/v1";
2991
+ }
2992
+ async ensureValidToken() {
2993
+ if (!this.isCloudMode() || !this.authState.accessToken) return false;
2994
+ const expiresAt = this.authState.expiresAt ?? 0;
2995
+ if (Date.now() + TOKEN_REFRESH_BUFFER_MS < expiresAt) return true;
2996
+ if (!this.config || !this.authState.refreshToken) {
2997
+ this.switchToLocalMode("token_expired_no_refresh");
2998
+ return false;
2999
+ }
3000
+ try {
3001
+ const refreshResult = await refreshAccessToken(this.config.endpoint, this.authState.refreshToken, this.config.timeout);
3002
+ if (!refreshResult) {
3003
+ this.switchToLocalMode("token_refresh_failed");
3004
+ return false;
3005
+ }
3006
+ this.authState.accessToken = refreshResult.accessToken;
3007
+ this.authState.refreshToken = refreshResult.refreshToken;
3008
+ this.authState.expiresAt = Date.now() + refreshResult.expiresIn * 1e3;
3009
+ return true;
3010
+ } catch {
3011
+ this.switchToLocalMode("token_refresh_error");
3012
+ return false;
3013
+ }
3014
+ }
3015
+ switchToLocalMode(reason) {
3016
+ if (this.authState.mode === "local") return;
3017
+ this.authState.mode = "local";
3018
+ this.failureReason = reason;
3019
+ process.stderr.write(`\u26A0 TestRelic: Switched to local mode (${reason}).
3020
+ `);
3021
+ }
3022
+ async dispose() {
3023
+ if (this.healthCheckTimer) {
3024
+ clearInterval(this.healthCheckTimer);
3025
+ this.healthCheckTimer = null;
3026
+ }
3027
+ if (this.flushPromise) {
3028
+ try {
3029
+ await Promise.race([this.flushPromise, new Promise((resolve5) => setTimeout(resolve5, FLUSH_TIMEOUT_MS))]);
3030
+ } catch {
3031
+ }
3032
+ this.flushPromise = null;
3033
+ }
3034
+ this.authState = { mode: "local", accessToken: null, refreshToken: null, expiresAt: null, orgId: null, orgName: null, userId: null, userName: null };
3035
+ this.repoId = null;
3036
+ this.gitMetadata = null;
3037
+ }
3038
+ setLocalMode(reason) {
3039
+ this.authState.mode = "local";
3040
+ this.failureReason = reason;
3041
+ }
3042
+ handleAuthError(code, statusCode) {
3043
+ switch (code) {
3044
+ case "invalid_key":
3045
+ this.setLocalMode("invalid_api_key");
3046
+ process.stderr.write(`\u26A0 TestRelic: API key is invalid or revoked. Running in local mode.
3047
+ \u2192 Manage keys: ${DASHBOARD_SETTINGS_URL}
3048
+ `);
3049
+ break;
3050
+ case "expired_key":
3051
+ this.setLocalMode("expired_api_key");
3052
+ process.stderr.write(`\u26A0 TestRelic: API key has expired. Running in local mode.
3053
+ \u2192 Generate a new key: ${DASHBOARD_SETTINGS_URL}
3054
+ `);
3055
+ break;
3056
+ case "rate_limited":
3057
+ this.setLocalMode("rate_limited");
3058
+ process.stderr.write("\u26A0 TestRelic: Rate limited during authentication. Running in local mode.\n");
3059
+ break;
3060
+ default:
3061
+ this.setLocalMode(`auth_error_${statusCode ?? "unknown"}`);
3062
+ process.stderr.write("\u26A0 TestRelic: Cloud authentication failed. Running in local mode.\n");
3063
+ break;
3064
+ }
3065
+ }
3066
+ async resolveRepoId() {
3067
+ if (!this.config || !this.authState.accessToken) return;
3068
+ const gitId = this.gitMetadata?.remoteUrl ? normalizeGitRemoteUrl(this.gitMetadata.remoteUrl) : null;
3069
+ const displayName = gitId ? deriveRepoDisplayName(gitId) : this.config.projectName ?? deriveNonGitProjectId(process.cwd());
3070
+ const effectiveGitId = gitId ?? (this.config.projectName ?? deriveNonGitProjectId(process.cwd()));
3071
+ const cached = this.readRepoCache(effectiveGitId);
3072
+ if (cached) {
3073
+ this.repoId = cached.repoId;
3074
+ return;
3075
+ }
3076
+ try {
3077
+ const resolved = await resolveRepo(this.config.endpoint, this.authState.accessToken, effectiveGitId, displayName, this.config.timeout, this.gitMetadata?.branch);
3078
+ if (resolved) {
3079
+ this.repoId = resolved.repoId;
3080
+ this.writeRepoCache(effectiveGitId, resolved.repoId, resolved.displayName);
3081
+ }
3082
+ } catch {
3083
+ }
3084
+ }
3085
+ readRepoCache(gitId) {
3086
+ if (!this.config) return null;
3087
+ const cachePath = (0, import_node_path11.join)(this.config.queueDirectory, "..", "cache", "repo.json");
3088
+ try {
3089
+ if (!(0, import_node_fs13.existsSync)(cachePath)) return null;
3090
+ const raw = (0, import_node_fs13.readFileSync)(cachePath, "utf-8");
3091
+ const cache = JSON.parse(raw);
3092
+ if (cache.gitId !== gitId) return null;
3093
+ if (Date.now() - cache.resolvedAt > PROJECT_CACHE_TTL_MS) return null;
3094
+ const currentKeyHash = this.hashApiKey();
3095
+ if (currentKeyHash && cache.apiKeyHash !== currentKeyHash) return null;
3096
+ return cache;
3097
+ } catch {
3098
+ return null;
3099
+ }
3100
+ }
3101
+ writeRepoCache(gitId, repoId, displayName) {
3102
+ if (!this.config) return;
3103
+ const cacheDir = (0, import_node_path11.join)(this.config.queueDirectory, "..", "cache");
3104
+ const cachePath = (0, import_node_path11.join)(cacheDir, "repo.json");
3105
+ try {
3106
+ (0, import_node_fs13.mkdirSync)(cacheDir, { recursive: true });
3107
+ const cache = { repoId, gitId, displayName, resolvedAt: Date.now(), apiKeyHash: this.hashApiKey() ?? "" };
3108
+ const tmpPath = cachePath + ".tmp";
3109
+ (0, import_node_fs13.writeFileSync)(tmpPath, JSON.stringify(cache, null, 2), "utf-8");
3110
+ (0, import_node_fs13.renameSync)(tmpPath, cachePath);
3111
+ } catch {
3112
+ }
3113
+ }
3114
+ hashApiKey() {
3115
+ if (!this.config?.apiKey) return null;
3116
+ return (0, import_node_crypto2.createHash)("sha256").update(this.config.apiKey).digest("hex").substring(0, 16);
3117
+ }
3118
+ startBackgroundFlush() {
3119
+ if (!this.config || !this.authState.accessToken) return;
3120
+ const accessToken = this.authState.accessToken;
3121
+ const queueDir = this.config.queueDirectory;
3122
+ const endpoint = this.config.endpoint;
3123
+ this.flushPromise = Promise.race([
3124
+ flushQueue(queueDir, endpoint, accessToken),
3125
+ new Promise((resolve5) => setTimeout(resolve5, FLUSH_TIMEOUT_MS))
3126
+ ]).catch(() => {
3127
+ });
3128
+ }
3129
+ startHealthCheck() {
3130
+ if (!this.config) return;
3131
+ const endpoint = this.config.endpoint;
3132
+ this.healthCheckTimer = setInterval(async () => {
3133
+ if (this.isCloudMode()) return;
3134
+ if (!this.failureReason || !["cloud_unreachable", "auth_timeout", "network_error"].includes(this.failureReason)) return;
3135
+ try {
3136
+ const healthy = await healthCheck(endpoint);
3137
+ if (!healthy) return;
3138
+ if (this.config?.apiKey) {
3139
+ const result = await exchangeToken(this.config.endpoint, this.config.apiKey, this.config.timeout);
3140
+ if (!isAuthError(result)) {
3141
+ const tokenResult = result;
3142
+ this.authState = { mode: "cloud", accessToken: tokenResult.accessToken, refreshToken: tokenResult.refreshToken, expiresAt: Date.now() + tokenResult.expiresIn * 1e3, orgId: tokenResult.orgId, orgName: tokenResult.orgName, userId: tokenResult.userId, userName: tokenResult.userName };
3143
+ this.failureReason = null;
3144
+ process.stderr.write("\u2713 TestRelic: Cloud connectivity restored.\n");
3145
+ this.startBackgroundFlush();
3146
+ }
3147
+ }
3148
+ } catch {
3149
+ }
3150
+ }, HEALTH_CHECK_INTERVAL_MS);
3151
+ }
3152
+ };
3153
+
3154
+ // src/cloud-upload.ts
3155
+ var import_node_zlib = require("zlib");
3156
+ var GZIP_THRESHOLD_BYTES = 1048576;
3157
+ var RETRY_DELAYS_MS = [1e3, 3e3, 9e3];
3158
+ var MAX_RETRIES = 3;
3159
+ function buildUploadPayload(report, repoGitId, git, ci, tests) {
3160
+ const environment = ci?.provider && ci.provider !== "unknown" ? ci.provider : "local";
3161
+ const payload = {
3162
+ runId: report.testRunId,
3163
+ repoGitId,
3164
+ startedAt: report.startedAt,
3165
+ summary: report.summary,
3166
+ timeline: report.timeline,
3167
+ environment,
3168
+ testFramework: "maestro",
3169
+ ...tests && tests.length > 0 ? { tests } : {},
3170
+ ...git?.branch ? { branch: git.branch } : {},
3171
+ ...git?.commitSha ? { commit: git.commitSha } : {},
3172
+ ...git?.commitMessage ? { commitMessage: git.commitMessage } : {},
3173
+ ...git?.commitAuthor ? { commitAuthor: git.commitAuthor } : {},
3174
+ ...report.completedAt ? { finishedAt: report.completedAt } : {},
3175
+ ...report.totalDuration ? { duration: report.totalDuration } : {},
3176
+ ...ci?.provider ? { ciProvider: ci.provider } : {},
3177
+ ...ci?.runUrl ? { ciRunUrl: ci.runUrl } : {}
3178
+ };
3179
+ return payload;
3180
+ }
3181
+ async function sleep2(ms) {
3182
+ return new Promise((resolve5) => setTimeout(resolve5, ms));
3183
+ }
3184
+ async function retryWithBackoff(url, init, onTokenRefresh) {
3185
+ for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
3186
+ try {
3187
+ const response = await fetch(url, init);
3188
+ if (response.ok) return response;
3189
+ if (response.status === 401 && onTokenRefresh && attempt === 0) {
3190
+ const newToken = await onTokenRefresh();
3191
+ if (newToken) {
3192
+ const refreshedInit = {
3193
+ ...init,
3194
+ headers: { ...init.headers, Authorization: `Bearer ${newToken}` }
3195
+ };
3196
+ const retryResponse = await fetch(url, refreshedInit);
3197
+ if (retryResponse.ok) return retryResponse;
3198
+ }
3199
+ return null;
3200
+ }
3201
+ if (response.status === 429 && attempt < MAX_RETRIES - 1) {
3202
+ const retryAfter = response.headers.get("Retry-After");
3203
+ const waitMs = retryAfter ? parseInt(retryAfter, 10) * 1e3 : RETRY_DELAYS_MS[attempt];
3204
+ if (!isNaN(waitMs) && waitMs > 0) {
3205
+ await sleep2(waitMs);
3206
+ } else {
3207
+ await sleep2(RETRY_DELAYS_MS[attempt]);
3208
+ }
3209
+ continue;
3210
+ }
3211
+ if (response.status >= 500 && attempt < MAX_RETRIES - 1) {
3212
+ await sleep2(RETRY_DELAYS_MS[attempt]);
3213
+ continue;
3214
+ }
3215
+ return response;
3216
+ } catch {
3217
+ if (attempt < MAX_RETRIES - 1) {
3218
+ await sleep2(RETRY_DELAYS_MS[attempt]);
3219
+ continue;
3220
+ }
3221
+ return null;
3222
+ }
3223
+ }
3224
+ return null;
3225
+ }
3226
+ function prepareBody(payload) {
3227
+ const json = JSON.stringify(payload);
3228
+ const headers = { "Content-Type": "application/json" };
3229
+ if (Buffer.byteLength(json, "utf-8") > GZIP_THRESHOLD_BYTES) {
3230
+ const compressed = (0, import_node_zlib.gzipSync)(Buffer.from(json, "utf-8"));
3231
+ headers["Content-Encoding"] = "gzip";
3232
+ return { body: compressed, headers };
3233
+ }
3234
+ return { body: json, headers };
3235
+ }
3236
+ async function uploadBatchRun(endpoint, accessToken, payload, onTokenRefresh) {
3237
+ const url = `${endpoint}/runs`;
3238
+ const { body, headers } = prepareBody(payload);
3239
+ headers["Authorization"] = `Bearer ${accessToken}`;
3240
+ const response = await retryWithBackoff(url, { method: "POST", headers, body }, onTokenRefresh);
3241
+ if (response?.ok) {
3242
+ return { success: true, statusCode: response.status, error: null };
3243
+ }
3244
+ if (response?.status === 409) {
3245
+ return { success: true, statusCode: 409, error: null };
3246
+ }
3247
+ return {
3248
+ success: false,
3249
+ reason: response ? `Upload failed with status ${response.status}` : "Upload failed after retries",
3250
+ statusCode: response?.status ?? null,
3251
+ payload,
3252
+ targetEndpoint: url,
3253
+ method: "POST"
3254
+ };
3255
+ }
3256
+
3257
+ // src/cloud-artifact-upload.ts
3258
+ var import_node_fs14 = require("fs");
3259
+ var import_node_path12 = require("path");
3260
+ var import_node_stream = require("stream");
3261
+ var UPLOAD_CONCURRENCY = 5;
3262
+ var RETRY_DELAYS_MS2 = [1e3, 3e3, 9e3];
3263
+ var MAX_RETRIES2 = 3;
3264
+ var CONTENT_TYPE_MAP = {
3265
+ ".png": "image/png",
3266
+ ".jpg": "image/jpeg",
3267
+ ".jpeg": "image/jpeg",
3268
+ ".webp": "image/webp",
3269
+ ".webm": "video/webm",
3270
+ ".mp4": "video/mp4",
3271
+ ".mov": "video/quicktime",
3272
+ ".zip": "application/zip"
3273
+ };
3274
+ var activeUploads = 0;
3275
+ var pendingUploads = [];
3276
+ async function acquireSlot() {
3277
+ if (activeUploads >= UPLOAD_CONCURRENCY) {
3278
+ await new Promise((resolve5) => pendingUploads.push(resolve5));
3279
+ }
3280
+ activeUploads++;
3281
+ }
3282
+ function releaseSlot() {
3283
+ activeUploads--;
3284
+ if (pendingUploads.length > 0) pendingUploads.shift()();
3285
+ }
3286
+ async function sleep3(ms) {
3287
+ return new Promise((resolve5) => setTimeout(resolve5, ms));
3288
+ }
3289
+ function getContentType(filePath) {
3290
+ const ext = filePath.substring(filePath.lastIndexOf(".")).toLowerCase();
3291
+ return CONTENT_TYPE_MAP[ext] ?? "application/octet-stream";
3292
+ }
3293
+ function getFileSize(filePath) {
3294
+ try {
3295
+ return (0, import_node_fs14.statSync)(filePath).size;
3296
+ } catch {
3297
+ return 0;
3298
+ }
3299
+ }
3300
+ async function requestUploadUrl(endpoint, accessToken, request, sizeBytes, contentType) {
3301
+ const url = `${endpoint}/artifacts/upload-url`;
3302
+ const body = JSON.stringify({ runId: request.runId, testId: request.testId, fileName: (0, import_node_path12.basename)(request.filePath), contentType, type: request.type, sizeBytes });
3303
+ for (let attempt = 0; attempt < MAX_RETRIES2; attempt++) {
3304
+ try {
3305
+ const response = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${accessToken}` }, body });
3306
+ if (response.ok) return await response.json();
3307
+ if (response.status >= 500 && attempt < MAX_RETRIES2 - 1) {
3308
+ await sleep3(RETRY_DELAYS_MS2[attempt]);
3309
+ continue;
3310
+ }
3311
+ return null;
3312
+ } catch {
3313
+ if (attempt < MAX_RETRIES2 - 1) {
3314
+ await sleep3(RETRY_DELAYS_MS2[attempt]);
3315
+ continue;
3316
+ }
3317
+ return null;
3318
+ }
3319
+ }
3320
+ return null;
3321
+ }
3322
+ async function putFileToPresignedUrl(presignedUrl, filePath, contentType, sizeBytes) {
3323
+ for (let attempt = 0; attempt < MAX_RETRIES2; attempt++) {
3324
+ try {
3325
+ const nodeStream = (0, import_node_fs14.createReadStream)(filePath);
3326
+ const webStream = import_node_stream.Readable.toWeb(nodeStream);
3327
+ const response = await fetch(presignedUrl, {
3328
+ method: "PUT",
3329
+ headers: { "Content-Type": contentType, "Content-Length": String(sizeBytes) },
3330
+ body: webStream,
3331
+ duplex: "half"
3332
+ });
3333
+ if (response.ok) return true;
3334
+ if (response.status >= 500 && attempt < MAX_RETRIES2 - 1) {
3335
+ await sleep3(RETRY_DELAYS_MS2[attempt]);
3336
+ continue;
3337
+ }
3338
+ return false;
3339
+ } catch {
3340
+ if (attempt < MAX_RETRIES2 - 1) {
3341
+ await sleep3(RETRY_DELAYS_MS2[attempt]);
3342
+ continue;
3343
+ }
3344
+ return false;
3345
+ }
3346
+ }
3347
+ return false;
3348
+ }
3349
+ async function confirmUpload(endpoint, accessToken, artifactId) {
3350
+ try {
3351
+ const response = await fetch(`${endpoint}/artifacts/confirm`, {
3352
+ method: "POST",
3353
+ headers: { "Content-Type": "application/json", "Authorization": `Bearer ${accessToken}` },
3354
+ body: JSON.stringify({ artifactId })
3355
+ });
3356
+ return response.ok;
3357
+ } catch {
3358
+ return false;
3359
+ }
3360
+ }
3361
+ async function uploadArtifact(endpoint, accessToken, request, maxSizeMb) {
3362
+ const sizeBytes = getFileSize(request.filePath);
3363
+ if (sizeBytes === 0) return { success: false, storageKey: null, artifactId: null, error: "file_not_found_or_empty" };
3364
+ if (sizeBytes > maxSizeMb * 1024 * 1024) return { success: false, storageKey: null, artifactId: null, error: "file_too_large" };
3365
+ const contentType = getContentType(request.filePath);
3366
+ await acquireSlot();
3367
+ try {
3368
+ const urlResult = await requestUploadUrl(endpoint, accessToken, request, sizeBytes, contentType);
3369
+ if (!urlResult) return { success: false, storageKey: null, artifactId: null, error: "upload_url_request_failed" };
3370
+ const uploaded = await putFileToPresignedUrl(urlResult.uploadUrl, request.filePath, contentType, sizeBytes);
3371
+ if (!uploaded) return { success: false, storageKey: urlResult.storageKey, artifactId: urlResult.artifactId, error: "presigned_put_failed" };
3372
+ const confirmed = await confirmUpload(endpoint, accessToken, urlResult.artifactId);
3373
+ return { success: confirmed, storageKey: urlResult.storageKey, artifactId: urlResult.artifactId, error: confirmed ? null : "confirm_failed" };
3374
+ } finally {
3375
+ releaseSlot();
3376
+ }
3377
+ }
3378
+ async function uploadArtifacts(endpoint, accessToken, requests, maxSizeMb) {
3379
+ const results = /* @__PURE__ */ new Map();
3380
+ const promises = requests.map(async (req) => {
3381
+ const result = await uploadArtifact(endpoint, accessToken, req, maxSizeMb);
3382
+ results.set(req.filePath, result);
3383
+ });
3384
+ await Promise.allSettled(promises);
3385
+ return results;
3386
+ }
3387
+
3388
+ // src/ci-detector.ts
3389
+ function detectGitHubActions(env) {
3390
+ if (env.GITHUB_ACTIONS !== "true") return null;
3391
+ return {
3392
+ provider: "github-actions",
3393
+ buildId: env.GITHUB_RUN_ID ?? null,
3394
+ commitSha: env.GITHUB_SHA ?? null,
3395
+ branch: env.GITHUB_REF_NAME ?? null,
3396
+ runUrl: env.GITHUB_SERVER_URL && env.GITHUB_REPOSITORY && env.GITHUB_RUN_ID ? `${env.GITHUB_SERVER_URL}/${env.GITHUB_REPOSITORY}/actions/runs/${env.GITHUB_RUN_ID}` : null
3397
+ };
3398
+ }
3399
+ function detectGitLabCI(env) {
3400
+ if (env.GITLAB_CI !== "true") return null;
3401
+ return {
3402
+ provider: "gitlab-ci",
3403
+ buildId: env.CI_PIPELINE_ID ?? null,
3404
+ commitSha: env.CI_COMMIT_SHA ?? null,
3405
+ branch: env.CI_COMMIT_BRANCH ?? env.CI_COMMIT_REF_NAME ?? null,
3406
+ runUrl: env.CI_PIPELINE_URL ?? null
3407
+ };
3408
+ }
3409
+ function detectJenkins(env) {
3410
+ if (!env.JENKINS_URL) return null;
3411
+ let branch = env.GIT_BRANCH ?? null;
3412
+ if (branch?.startsWith("origin/")) {
3413
+ branch = branch.slice("origin/".length);
3414
+ }
3415
+ return {
3416
+ provider: "jenkins",
3417
+ buildId: env.BUILD_ID ?? null,
3418
+ commitSha: env.GIT_COMMIT ?? null,
3419
+ branch,
3420
+ runUrl: env.BUILD_URL ?? null
3421
+ };
3422
+ }
3423
+ function detectCircleCI(env) {
3424
+ if (env.CIRCLECI !== "true") return null;
3425
+ return {
3426
+ provider: "circleci",
3427
+ buildId: env.CIRCLE_BUILD_NUM ?? null,
3428
+ commitSha: env.CIRCLE_SHA1 ?? null,
3429
+ branch: env.CIRCLE_BRANCH ?? null,
3430
+ runUrl: env.CIRCLE_BUILD_URL ?? null
3431
+ };
3432
+ }
3433
+ function detectBitbucketPipelines(env) {
3434
+ if (!env.BITBUCKET_PIPELINE_UUID) return null;
3435
+ const runUrl = env.BITBUCKET_WORKSPACE && env.BITBUCKET_REPO_SLUG && env.BITBUCKET_PIPELINE_UUID ? `https://bitbucket.org/${env.BITBUCKET_WORKSPACE}/${env.BITBUCKET_REPO_SLUG}/pipelines/results/${env.BITBUCKET_PIPELINE_UUID}` : null;
3436
+ return {
3437
+ provider: "bitbucket-pipelines",
3438
+ buildId: env.BITBUCKET_BUILD_NUMBER ?? null,
3439
+ commitSha: env.BITBUCKET_COMMIT ?? null,
3440
+ branch: env.BITBUCKET_BRANCH ?? null,
3441
+ runUrl
3442
+ };
3443
+ }
3444
+ var detectors = [
3445
+ detectGitHubActions,
3446
+ detectGitLabCI,
3447
+ detectJenkins,
3448
+ detectCircleCI,
3449
+ detectBitbucketPipelines
3450
+ ];
3451
+ function detectCI(env) {
3452
+ const envVars = env ?? process.env;
3453
+ for (const detect of detectors) {
3454
+ const result = detect(envVars);
3455
+ if (result) return result;
3456
+ }
3457
+ return null;
3458
+ }
3459
+
3460
+ // src/cloud-reporter.ts
3461
+ function flattenTimelineForCloud(timeline) {
3462
+ const flat = [];
3463
+ for (const entry of timeline) {
3464
+ const timelineEntry = entry;
3465
+ const tests = timelineEntry.tests;
3466
+ if (!Array.isArray(tests) || tests.length === 0) {
3467
+ flat.push(entry);
3468
+ continue;
3469
+ }
3470
+ for (const test of tests) {
3471
+ flat.push({
3472
+ timestamp: test.startedAt,
3473
+ title: test.title,
3474
+ category: "test",
3475
+ navigationType: timelineEntry.navigationType,
3476
+ url: timelineEntry.url,
3477
+ visitedAt: timelineEntry.visitedAt,
3478
+ duration: test.duration,
3479
+ status: test.status,
3480
+ test_status: test.status,
3481
+ test_id: test.testId,
3482
+ test_title: test.title,
3483
+ specfile: test.filePath,
3484
+ suiteName: test.suiteName,
3485
+ type: "test",
3486
+ ...test.failure ? { error: test.failure.message, errorMessage: test.failure.message } : {}
3487
+ });
3488
+ for (const action of test.actions ?? []) {
3489
+ flat.push({
3490
+ timestamp: action.timestamp,
3491
+ title: action.title,
3492
+ category: action.category,
3493
+ status: action.status,
3494
+ test_status: test.status,
3495
+ duration: action.duration,
3496
+ error: action.error,
3497
+ test_id: test.testId,
3498
+ test_title: test.title,
3499
+ specfile: test.filePath,
3500
+ url: timelineEntry.url,
3501
+ type: action.category === "assertion" ? "assert" : "action"
3502
+ });
3503
+ }
3504
+ }
3505
+ }
3506
+ return flat;
3507
+ }
3508
+ function getEffectiveGitId(cloudClient) {
3509
+ const gitMeta = cloudClient.getGitMetadata();
3510
+ const remoteUrl = gitMeta?.remoteUrl;
3511
+ if (remoteUrl) return normalizeGitRemoteUrl(remoteUrl);
3512
+ const projectName = cloudClient.getConfig()?.projectName;
3513
+ return projectName ?? deriveNonGitProjectId(process.cwd());
3514
+ }
3515
+ async function finalizeAndUpload(cloudClient, cloudConfig, testRunId, report, completedAt, totalDuration, summary, screenshotPaths, videoPaths, tests, videoArtifacts) {
3516
+ try {
3517
+ const perTestVideoCount = videoArtifacts?.length ?? 0;
3518
+ const hasArtifacts = (screenshotPaths?.length ?? 0) + (videoPaths?.length ?? 0) + perTestVideoCount > 0;
3519
+ if (cloudClient.isCloudMode() && hasArtifacts) {
3520
+ const tokenValid = await cloudClient.ensureValidToken();
3521
+ if (tokenValid) {
3522
+ const endpoint = cloudClient.getEndpoint();
3523
+ const token = cloudClient.getAccessToken();
3524
+ const maxSizeMb = cloudConfig?.artifactMaxSizeMb ?? 50;
3525
+ const requests = [];
3526
+ for (const path of screenshotPaths ?? []) {
3527
+ requests.push({ filePath: path, runId: testRunId, testId: "maestro-suite", type: "screenshot" });
3528
+ }
3529
+ const perTestPaths = /* @__PURE__ */ new Set();
3530
+ for (const va of videoArtifacts ?? []) {
3531
+ requests.push({ filePath: va.path, runId: testRunId, testId: va.testId, type: "video" });
3532
+ perTestPaths.add(va.path);
3533
+ }
3534
+ for (const path of videoPaths ?? []) {
3535
+ if (!perTestPaths.has(path)) {
3536
+ requests.push({ filePath: path, runId: testRunId, testId: "maestro-suite", type: "video" });
3537
+ }
3538
+ }
3539
+ if (requests.length > 0) {
3540
+ const results = await uploadArtifacts(endpoint, token, requests, maxSizeMb);
3541
+ const resultEntries = Array.from(results.entries());
3542
+ const uploaded = resultEntries.filter(([, r]) => r.success).length;
3543
+ const failed = resultEntries.filter(([, r]) => !r.success);
3544
+ if (uploaded > 0) {
3545
+ const videoCount = requests.filter((r) => r.type === "video").length;
3546
+ const perFlowVideoCount = videoArtifacts?.length ?? 0;
3547
+ const ssCount = requests.filter((r) => r.type === "screenshot").length;
3548
+ const parts = [];
3549
+ if (ssCount > 0) parts.push(`${ssCount} screenshot(s)`);
3550
+ if (videoCount > 0) {
3551
+ const perFlowNote = perFlowVideoCount > 0 ? ` (${perFlowVideoCount} per-flow)` : "";
3552
+ parts.push(`${videoCount} video(s)${perFlowNote}`);
3553
+ }
3554
+ process.stderr.write(`\u2713 TestRelic: Uploaded ${uploaded} artifact(s) [${parts.join(", ")}] to cloud storage.
3555
+ `);
3556
+ }
3557
+ if (failed.length > 0) {
3558
+ process.stderr.write(`\u26A0 TestRelic: ${failed.length} artifact(s) failed to upload:
3559
+ `);
3560
+ for (const [filePath, result] of failed) {
3561
+ const req = requests.find((r) => r.filePath === filePath);
3562
+ const label = req ? `[${req.type}] ${filePath}` : filePath;
3563
+ process.stderr.write(` \u2717 ${label} \u2014 reason: ${result.error ?? "unknown"}
3564
+ `);
3565
+ }
3566
+ }
3567
+ }
3568
+ }
3569
+ }
3570
+ if (cloudClient.isCloudMode()) {
3571
+ const tokenValid = await cloudClient.ensureValidToken();
3572
+ if (tokenValid) {
3573
+ const batchGit = cloudClient.getGitMetadata();
3574
+ const batchCi = detectCI();
3575
+ const batchGitId = getEffectiveGitId(cloudClient);
3576
+ const flatTimeline = flattenTimelineForCloud(report.timeline);
3577
+ const flatReport = { ...report, timeline: flatTimeline };
3578
+ const payload = buildUploadPayload(flatReport, batchGitId, batchGit, batchCi, tests);
3579
+ const result = await uploadBatchRun(
3580
+ cloudClient.getEndpoint(),
3581
+ cloudClient.getAccessToken(),
3582
+ payload,
3583
+ async () => {
3584
+ const refreshed = await cloudClient.ensureValidToken();
3585
+ return refreshed ? cloudClient.getAccessToken() : null;
3586
+ }
3587
+ );
3588
+ if (result.success) {
3589
+ process.stderr.write(`\u2713 TestRelic: Cloud upload succeeded \u2192 ${cloudClient.getEndpoint()}/runs/${testRunId}
3590
+ `);
3591
+ } else {
3592
+ const failure = result;
3593
+ const queueDir = cloudConfig?.queueDirectory ?? ".testrelic/queue";
3594
+ writeToQueue(queueDir, testRunId, "batch", failure.reason, failure.targetEndpoint, failure.method, failure.payload, { "Content-Type": "application/json" });
3595
+ process.stderr.write("\u26A0 TestRelic: Cloud upload failed, queued for retry.\n");
3596
+ }
3597
+ } else {
3598
+ const queueDir = cloudConfig?.queueDirectory ?? ".testrelic/queue";
3599
+ const queueGit = cloudClient.getGitMetadata();
3600
+ const queueCi = detectCI();
3601
+ const queueGitId = getEffectiveGitId(cloudClient);
3602
+ const queuePayload = buildUploadPayload(report, queueGitId, queueGit, queueCi);
3603
+ writeToQueue(queueDir, testRunId, "batch", cloudClient.getFailureReason() ?? "token_invalid", `${cloudClient.getEndpoint()}/runs`, "POST", queuePayload, { "Content-Type": "application/json" });
3604
+ }
3605
+ }
3606
+ await cloudClient.dispose();
3607
+ } catch {
3608
+ try {
3609
+ await cloudClient.dispose();
3610
+ } catch {
3611
+ }
3612
+ }
3613
+ }
3614
+
3615
+ // src/report-orchestrator.ts
3616
+ function matchVideoToFlow(flowFile, videoPaths, flowRecordingPath) {
3617
+ if (videoPaths.length === 0) return null;
3618
+ const flowBase = (0, import_node_path13.basename)(flowFile, (0, import_node_path13.extname)(flowFile)).toLowerCase();
3619
+ const exact = videoPaths.find(
3620
+ (v) => (0, import_node_path13.basename)(v, (0, import_node_path13.extname)(v)).toLowerCase() === flowBase
3621
+ );
3622
+ if (exact) return exact;
3623
+ const forward = videoPaths.find(
3624
+ (v) => (0, import_node_path13.basename)(v).toLowerCase().includes(flowBase)
3625
+ );
3626
+ if (forward) return forward;
3627
+ const reverse = videoPaths.find((v) => {
3628
+ const videoBase = (0, import_node_path13.basename)(v, (0, import_node_path13.extname)(v)).toLowerCase();
3629
+ return videoBase.length >= 3 && (flowBase.startsWith(videoBase) || flowBase.includes(videoBase));
3630
+ });
3631
+ if (reverse) return reverse;
3632
+ if (flowRecordingPath) {
3633
+ const recBase = (0, import_node_path13.basename)(flowRecordingPath, (0, import_node_path13.extname)(flowRecordingPath)).toLowerCase();
3634
+ const byRec = videoPaths.find((v) => (0, import_node_path13.basename)(v, (0, import_node_path13.extname)(v)).toLowerCase() === recBase);
3635
+ if (byRec) return byRec;
3636
+ const byRecPartial = videoPaths.find((v) => (0, import_node_path13.basename)(v).toLowerCase().includes(recBase));
3637
+ if (byRecPartial) return byRecPartial;
3638
+ }
3639
+ return null;
3640
+ }
3641
+ function matchScreenshotsToFlow(flowFile, screenshotPaths) {
3642
+ if (screenshotPaths.length === 0) return [];
3643
+ const flowBase = (0, import_node_path13.basename)(flowFile, (0, import_node_path13.extname)(flowFile)).toLowerCase();
3644
+ const matched = screenshotPaths.filter((s) => {
3645
+ const name = (0, import_node_path13.basename)(s).toLowerCase();
3646
+ const nameBase = (0, import_node_path13.basename)(s, (0, import_node_path13.extname)(s)).toLowerCase();
3647
+ if (name.startsWith(flowBase) || name.includes(flowBase)) return true;
3648
+ return nameBase.length >= 3 && (flowBase.startsWith(nameBase) || flowBase.includes(nameBase));
3649
+ });
3650
+ return matched.length > 0 ? matched : screenshotPaths.slice();
3651
+ }
3652
+ function extractRecordingPath(commands) {
3653
+ for (const cmd of commands) {
3654
+ if (cmd.command === "startRecording") {
3655
+ const meta = cmd.metadata;
3656
+ const path = meta?.path ?? meta?.recording ?? meta?.fileName;
3657
+ if (typeof path === "string") return path;
3658
+ if (typeof cmd.selector === "string") return cmd.selector;
3659
+ }
3660
+ }
3661
+ return null;
3662
+ }
3663
+ function buildFlowRecordingMap(commandSteps) {
3664
+ const map = /* @__PURE__ */ new Map();
3665
+ for (const [filePath, commands] of commandSteps) {
3666
+ const name = (0, import_node_path13.basename)(filePath).replace(/^commands[-_]?/i, "").replace(/\.json$/i, "").toLowerCase();
3667
+ const recPath = extractRecordingPath(commands);
3668
+ if (recPath && name) map.set(name, recPath);
3669
+ }
3670
+ return map;
3671
+ }
3672
+ function platformToOs(platform) {
3673
+ switch (platform) {
3674
+ case "android":
3675
+ return "Android";
3676
+ case "ios":
3677
+ return "iOS";
3678
+ case "web":
3679
+ return "Web";
3680
+ default:
3681
+ return void 0;
3682
+ }
3683
+ }
3684
+ function flowToTestResult(flow) {
3685
+ return {
3686
+ testId: `${flow.flowFile}::${flow.flowName}`,
3687
+ title: flow.flowName,
3688
+ status: flow.status,
3689
+ duration: flow.duration,
3690
+ suiteName: flow.appId ?? "maestro-suite",
3691
+ filePath: flow.flowFile,
3692
+ testType: "mobile",
3693
+ isFlaky: false,
3694
+ startedAt: flow.startedAt,
3695
+ completedAt: flow.completedAt,
3696
+ tags: flow.tags,
3697
+ failure: flow.failureMessage ? { message: flow.failureMessage } : null,
3698
+ retry: 0,
3699
+ retryCount: 0,
3700
+ retryStatus: null,
3701
+ source: "maestro",
3702
+ platform: flow.platform !== "unknown" ? flow.platform : void 0,
3703
+ os: platformToOs(flow.platform),
3704
+ deviceName: flow.deviceId
3705
+ };
3706
+ }
3707
+ async function orchestrateReport(input) {
3708
+ const { config } = input;
3709
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
3710
+ const testRunId = config.testRunId ?? (0, import_node_crypto3.randomUUID)();
3711
+ const artifacts = collectArtifacts(input.testOutputDir, input.debugOutputDir);
3712
+ const junitPath = input.junitPath ?? artifacts.junitReportPath;
3713
+ let platform = input.platform ?? "unknown";
3714
+ if (platform === "unknown") {
3715
+ const logFiles = input.debugOutputDir ? discoverLogFiles(input.debugOutputDir) : artifacts.logPaths;
3716
+ for (const logFile of logFiles) {
3717
+ const logEntries = parseLogFile(logFile);
3718
+ const detected = detectPlatformFromLogs(logEntries);
3719
+ if (detected !== "unknown") {
3720
+ platform = detected;
3721
+ break;
3722
+ }
3723
+ }
3724
+ }
3725
+ const flowMetadataMap = /* @__PURE__ */ new Map();
3726
+ if (input.flowsDir && (0, import_node_fs15.existsSync)(input.flowsDir)) {
3727
+ const flowFiles = discoverFlowFiles(input.flowsDir);
3728
+ for (const flowFile of flowFiles) {
3729
+ const meta = parseFlowFile(flowFile);
3730
+ const name = meta.name ?? flowFile;
3731
+ flowMetadataMap.set(name, meta);
3732
+ }
3733
+ }
3734
+ const commandSteps = /* @__PURE__ */ new Map();
3735
+ const commandFiles = input.testOutputDir ? discoverCommandFiles(input.testOutputDir) : artifacts.commandJsonPaths;
3736
+ for (const cmdFile of commandFiles) {
3737
+ commandSteps.set(cmdFile, parseCommandsFile(cmdFile));
3738
+ }
3739
+ const allAiDefects = [];
3740
+ const aiReportFiles = input.testOutputDir ? discoverAiReports(input.testOutputDir) : artifacts.aiReportPaths;
3741
+ for (const aiFile of aiReportFiles) {
3742
+ const aiReport = parseAiReportFile(aiFile);
3743
+ allAiDefects.push(...aiReport.defects);
3744
+ }
3745
+ const flowRecordingMap = buildFlowRecordingMap(commandSteps);
3746
+ const flowResults = [];
3747
+ if (junitPath && (0, import_node_fs15.existsSync)(junitPath)) {
3748
+ const junit = parseJUnitFile(junitPath);
3749
+ const allCommands = Array.from(commandSteps.values()).flat();
3750
+ const assertionCommands = allCommands.filter((c) => c.category === "assertion");
3751
+ const nonAssertionCommands = allCommands.filter((c) => c.category !== "assertion");
3752
+ for (const suite of junit.testSuites) {
3753
+ for (const testCase of suite.testCases) {
3754
+ const name = testCase.name;
3755
+ const meta = flowMetadataMap.get(name);
3756
+ const status = testCase.status === "SUCCESS" ? "passed" : testCase.status === "SKIPPED" ? "skipped" : "failed";
3757
+ const durationMs = testCase.time * 1e3;
3758
+ const flowStartedAt = startedAt;
3759
+ const flowCompletedAt = new Date(new Date(flowStartedAt).getTime() + durationMs).toISOString();
3760
+ const flowFile = testCase.classname || name;
3761
+ const flowBase = (0, import_node_path13.basename)(flowFile, (0, import_node_path13.extname)(flowFile)).toLowerCase();
3762
+ const recordingPath = flowRecordingMap.get(flowBase) ?? null;
3763
+ flowResults.push({
3764
+ flowName: name,
3765
+ flowFile,
3766
+ appId: meta?.appId ?? null,
3767
+ platform,
3768
+ deviceId: input.device,
3769
+ status,
3770
+ duration: durationMs,
3771
+ startedAt: flowStartedAt,
3772
+ completedAt: flowCompletedAt,
3773
+ tags: meta?.tags ?? [],
3774
+ properties: meta?.properties ?? {},
3775
+ commands: nonAssertionCommands,
3776
+ assertions: assertionCommands,
3777
+ screenshotPaths: matchScreenshotsToFlow(flowFile, artifacts.screenshotPaths),
3778
+ videoPath: matchVideoToFlow(flowFile, artifacts.videoPaths, recordingPath),
3779
+ aiDefects: allAiDefects,
3780
+ logEntries: [],
3781
+ failureMessage: testCase.failureMessage ?? testCase.errorMessage ?? null,
3782
+ failureType: testCase.failureType ?? testCase.errorType ?? null,
3783
+ subflowRefs: meta?.subflowRefs ?? [],
3784
+ metadata: meta ?? null
3785
+ });
3786
+ }
3787
+ }
3788
+ }
3789
+ if (flowResults.length === 0 && flowMetadataMap.size > 0) {
3790
+ for (const [, meta] of flowMetadataMap) {
3791
+ flowResults.push({
3792
+ flowName: meta.name ?? meta.filePath,
3793
+ flowFile: meta.filePath,
3794
+ appId: meta.appId,
3795
+ platform,
3796
+ deviceId: input.device,
3797
+ status: "passed",
3798
+ duration: 0,
3799
+ startedAt,
3800
+ completedAt: startedAt,
3801
+ tags: meta.tags,
3802
+ properties: meta.properties,
3803
+ commands: [],
3804
+ assertions: [],
3805
+ screenshotPaths: [],
3806
+ videoPath: null,
3807
+ aiDefects: [],
3808
+ logEntries: [],
3809
+ failureMessage: null,
3810
+ failureType: null,
3811
+ subflowRefs: meta.subflowRefs,
3812
+ metadata: meta
3813
+ });
3814
+ }
3815
+ }
3816
+ const timeline = buildTimeline(flowResults);
3817
+ const summary = buildSummary(timeline);
3818
+ const completedAt = (/* @__PURE__ */ new Date()).toISOString();
3819
+ const totalDuration = Date.now() - new Date(startedAt).getTime();
3820
+ const report = {
3821
+ schemaVersion: "1.0.0",
3822
+ testRunId,
3823
+ startedAt,
3824
+ completedAt,
3825
+ totalDuration,
3826
+ summary,
3827
+ ci: null,
3828
+ metadata: config.metadata ?? null,
3829
+ timeline,
3830
+ shardRunIds: null
3831
+ };
3832
+ (0, import_node_fs15.mkdirSync)((0, import_node_path13.dirname)((0, import_node_path13.resolve)(config.outputPath)), { recursive: true });
3833
+ (0, import_node_fs15.writeFileSync)((0, import_node_path13.resolve)(config.outputPath), JSON.stringify(report, null, 2), "utf-8");
3834
+ generateHtmlReport(report, allAiDefects, artifacts.screenshotPaths, (0, import_node_path13.resolve)(config.htmlReportPath));
3835
+ printConsoleSummary(summary, config.outputPath, config.htmlReportPath, config.quiet, allAiDefects);
3836
+ if (config.openReport) {
3837
+ openInBrowser((0, import_node_path13.resolve)(config.htmlReportPath));
3838
+ }
3839
+ if (config.cloud) {
3840
+ const cloudClient = new CloudClient(config.cloud);
3841
+ await cloudClient.initialize();
3842
+ const videoPathsToUpload = config.includeVideo ? artifacts.videoPaths : [];
3843
+ const videoArtifacts = [];
3844
+ if (videoPathsToUpload.length > 0) {
3845
+ for (const flow of flowResults) {
3846
+ const flowBase = (0, import_node_path13.basename)(flow.flowFile, (0, import_node_path13.extname)(flow.flowFile)).toLowerCase();
3847
+ const recordingPath = flowRecordingMap.get(flowBase) ?? null;
3848
+ const matched = matchVideoToFlow(flow.flowFile, videoPathsToUpload, recordingPath);
3849
+ if (matched) {
3850
+ const testId = `${flow.flowFile}::${flow.flowName}`;
3851
+ if (!videoArtifacts.some((va) => va.path === matched && va.testId === testId)) {
3852
+ videoArtifacts.push({ path: matched, testId });
3853
+ }
3854
+ }
3855
+ }
3856
+ if (videoPathsToUpload.length === 1) {
3857
+ const singleVideo = videoPathsToUpload[0];
3858
+ for (const flow of flowResults) {
3859
+ const testId = `${flow.flowFile}::${flow.flowName}`;
3860
+ if (!videoArtifacts.some((va) => va.testId === testId)) {
3861
+ videoArtifacts.push({ path: singleVideo, testId });
3862
+ }
3863
+ }
3864
+ }
3865
+ }
3866
+ const matchedPaths = new Set(videoArtifacts.map((va) => va.path));
3867
+ const unmatchedVideos = videoPathsToUpload.filter((v) => !matchedPaths.has(v));
3868
+ const testsForUpload = flowResults.map(flowToTestResult);
3869
+ await finalizeAndUpload(
3870
+ cloudClient,
3871
+ config.cloud,
3872
+ testRunId,
3873
+ report,
3874
+ completedAt,
3875
+ totalDuration,
3876
+ summary,
3877
+ config.includeScreenshots ? artifacts.screenshotPaths : [],
3878
+ unmatchedVideos,
3879
+ testsForUpload,
3880
+ videoArtifacts
3881
+ );
3882
+ }
3883
+ return { report, flowResults, aiDefects: allAiDefects, artifacts };
3884
+ }
3885
+
3886
+ // src/cli.ts
3887
+ function printUsage() {
3888
+ const usage = `
3889
+ testrelic-maestro \u2014 Maestro test analytics for TestRelic
3890
+
3891
+ Usage:
3892
+ testrelic-maestro test [options] <flow-paths...>
3893
+ testrelic-maestro report [options]
3894
+
3895
+ Commands:
3896
+ test Run Maestro tests and report results to TestRelic
3897
+ report Parse existing Maestro artifacts and report to TestRelic
3898
+
3899
+ Test Options:
3900
+ --api-key <key> TestRelic API key (or set TESTRELIC_API_KEY)
3901
+ --endpoint <url> TestRelic API endpoint
3902
+ --output-dir <dir> Output directory for reports
3903
+ --html-report <path> HTML report output path
3904
+ --no-open Don't auto-open the HTML report
3905
+ --analyze Enable Maestro AI analysis
3906
+ --platform <platform> Target platform (android, ios, web)
3907
+ --device <id> Device UDID
3908
+ --include-tags <tags> Comma-separated tags to include
3909
+ --exclude-tags <tags> Comma-separated tags to exclude
3910
+ --shards <n> Number of parallel shards
3911
+ --config <path> Maestro config.yaml path
3912
+ -e, --env <KEY=VALUE> Environment variable
3913
+ --quiet Suppress output
3914
+
3915
+ Report Options:
3916
+ --junit <path> Path to JUnit XML report
3917
+ --artifacts <dir> Path to Maestro test output directory
3918
+ --flows-dir <dir> Path to Maestro flow YAML files
3919
+ --output-dir <dir> Output directory for reports
3920
+ --html-report <path> HTML report output path
3921
+ --no-open Don't auto-open the HTML report
3922
+ --api-key <key> TestRelic API key
3923
+ --endpoint <url> TestRelic API endpoint
3924
+ --quiet Suppress output
3925
+ `;
3926
+ process.stdout.write(usage.trim() + "\n");
3927
+ }
3928
+ function parseArgs(args) {
3929
+ const options = {};
3930
+ const positional = [];
3931
+ let command = "";
3932
+ let i = 0;
3933
+ if (args.length > 0 && !args[0].startsWith("-")) {
3934
+ command = args[0];
3935
+ i = 1;
3936
+ }
3937
+ while (i < args.length) {
3938
+ const arg = args[i];
3939
+ if (arg.startsWith("--")) {
3940
+ const key = arg.slice(2);
3941
+ if (key === "no-open") {
3942
+ options["open"] = "false";
3943
+ } else if (i + 1 < args.length && !args[i + 1].startsWith("-")) {
3944
+ i++;
3945
+ if (key === "env" || key === "e") {
3946
+ const existing = options["env"];
3947
+ if (Array.isArray(existing)) {
3948
+ existing.push(args[i]);
3949
+ } else if (typeof existing === "string") {
3950
+ options["env"] = [existing, args[i]];
3951
+ } else {
3952
+ options["env"] = args[i];
3953
+ }
3954
+ } else {
3955
+ options[key] = args[i];
3956
+ }
3957
+ } else {
3958
+ options[key] = "true";
3959
+ }
3960
+ } else if (arg === "-e" && i + 1 < args.length) {
3961
+ i++;
3962
+ const existing = options["env"];
3963
+ if (Array.isArray(existing)) {
3964
+ existing.push(args[i]);
3965
+ } else if (typeof existing === "string") {
3966
+ options["env"] = [existing, args[i]];
3967
+ } else {
3968
+ options["env"] = args[i];
3969
+ }
3970
+ } else {
3971
+ positional.push(arg);
3972
+ }
3973
+ i++;
3974
+ }
3975
+ return { command, options, positional };
3976
+ }
3977
+ function parseEnvVars(raw) {
3978
+ const env = {};
3979
+ if (!raw) return env;
3980
+ const items = Array.isArray(raw) ? raw : [raw];
3981
+ for (const item of items) {
3982
+ const eqIdx = item.indexOf("=");
3983
+ if (eqIdx > 0) {
3984
+ env[item.slice(0, eqIdx)] = item.slice(eqIdx + 1);
3985
+ }
3986
+ }
3987
+ return env;
3988
+ }
3989
+ async function handleTest(options, positional) {
3990
+ if (positional.length === 0) {
3991
+ process.stderr.write("Error: No flow paths specified. Usage: testrelic-maestro test <flow-paths...>\n");
3992
+ process.exit(1);
3993
+ }
3994
+ const testOptions = {
3995
+ flowPaths: positional,
3996
+ apiKey: typeof options["api-key"] === "string" ? options["api-key"] : void 0,
3997
+ endpoint: typeof options["endpoint"] === "string" ? options["endpoint"] : void 0,
3998
+ outputDir: typeof options["output-dir"] === "string" ? options["output-dir"] : void 0,
3999
+ analyze: options["analyze"] === "true",
4000
+ platform: typeof options["platform"] === "string" ? options["platform"] : void 0,
4001
+ device: typeof options["device"] === "string" ? options["device"] : void 0,
4002
+ includeTags: typeof options["include-tags"] === "string" ? options["include-tags"] : void 0,
4003
+ excludeTags: typeof options["exclude-tags"] === "string" ? options["exclude-tags"] : void 0,
4004
+ shards: typeof options["shards"] === "string" ? parseInt(options["shards"], 10) : void 0,
4005
+ config: typeof options["config"] === "string" ? options["config"] : void 0,
4006
+ env: parseEnvVars(options["env"]),
4007
+ quiet: options["quiet"] === "true"
4008
+ };
4009
+ process.stderr.write("\u2139 TestRelic: Running Maestro tests...\n");
4010
+ const runResult = await runMaestro(testOptions);
4011
+ process.stderr.write(`\u2139 TestRelic: Maestro exited with code ${runResult.exitCode}. Parsing results...
4012
+ `);
4013
+ const config = resolveConfig({
4014
+ outputPath: typeof options["output-dir"] === "string" ? `${options["output-dir"]}/testrelic-maestro.json` : void 0,
4015
+ htmlReportPath: typeof options["html-report"] === "string" ? options["html-report"] : void 0,
4016
+ openReport: options["open"] !== "false",
4017
+ cloud: {
4018
+ apiKey: typeof options["api-key"] === "string" ? options["api-key"] : void 0,
4019
+ endpoint: typeof options["endpoint"] === "string" ? options["endpoint"] : void 0
4020
+ },
4021
+ quiet: options["quiet"] === "true",
4022
+ flowsDir: positional[0]
4023
+ });
4024
+ await orchestrateReport({
4025
+ junitPath: runResult.junitPath,
4026
+ testOutputDir: runResult.testOutputDir,
4027
+ debugOutputDir: runResult.debugOutputDir,
4028
+ flowsDir: positional[0],
4029
+ config
4030
+ });
4031
+ process.exit(runResult.exitCode);
4032
+ }
4033
+ async function handleReport(options) {
4034
+ const config = resolveConfig({
4035
+ outputPath: typeof options["output-dir"] === "string" ? `${options["output-dir"]}/testrelic-maestro.json` : void 0,
4036
+ htmlReportPath: typeof options["html-report"] === "string" ? options["html-report"] : void 0,
4037
+ openReport: options["open"] !== "false",
4038
+ cloud: {
4039
+ apiKey: typeof options["api-key"] === "string" ? options["api-key"] : void 0,
4040
+ endpoint: typeof options["endpoint"] === "string" ? options["endpoint"] : void 0
4041
+ },
4042
+ quiet: options["quiet"] === "true",
4043
+ flowsDir: typeof options["flows-dir"] === "string" ? options["flows-dir"] : void 0
4044
+ });
4045
+ process.stderr.write("\u2139 TestRelic: Parsing Maestro artifacts...\n");
4046
+ await orchestrateReport({
4047
+ junitPath: typeof options["junit"] === "string" ? options["junit"] : void 0,
4048
+ testOutputDir: typeof options["artifacts"] === "string" ? options["artifacts"] : void 0,
4049
+ flowsDir: typeof options["flows-dir"] === "string" ? options["flows-dir"] : void 0,
4050
+ config
4051
+ });
4052
+ }
4053
+ async function main() {
4054
+ const args = process.argv.slice(2);
4055
+ if (args.length === 0 || args.includes("--help") || args.includes("-h")) {
4056
+ printUsage();
4057
+ process.exit(0);
4058
+ }
4059
+ const { command, options, positional } = parseArgs(args);
4060
+ switch (command) {
4061
+ case "test":
4062
+ await handleTest(options, positional);
4063
+ break;
4064
+ case "report":
4065
+ await handleReport(options);
4066
+ break;
4067
+ default:
4068
+ process.stderr.write(`Unknown command: ${command}
4069
+ Run 'testrelic-maestro --help' for usage.
4070
+ `);
4071
+ process.exit(1);
4072
+ }
4073
+ }
4074
+ main().catch((err) => {
4075
+ process.stderr.write(`\u2717 TestRelic: ${err instanceof Error ? err.message : String(err)}
4076
+ `);
4077
+ process.exit(1);
4078
+ });