File size: 5,912 Bytes
fd2c364
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
#!/usr/bin/env node

import {
  copyFileSync,
  existsSync,
  lstatSync,
  mkdirSync,
  readFileSync,
  readdirSync,
  realpathSync,
  writeFileSync,
} from "node:fs";
import {
  dirname,
  extname,
  isAbsolute,
  join,
  relative,
  resolve,
} from "node:path";

function parseArgs(argv) {
  const args = {};
  for (let index = 0; index < argv.length; index += 1) {
    const arg = argv[index];
    if (!arg.startsWith("--")) {
      continue;
    }

    const [rawKey, inlineValue] = arg.slice(2).split("=", 2);
    const key = rawKey.replaceAll("-", "_");
    if (inlineValue !== undefined) {
      args[key] = inlineValue;
      continue;
    }

    const next = argv[index + 1];
    if (next && !next.startsWith("--")) {
      args[key] = next;
      index += 1;
    } else {
      args[key] = "";
    }
  }
  return args;
}

function assertWithinCwd(label, path) {
  const relativePath = relative(realpathSync(resolve(".")), path);
  if (relativePath.startsWith("..") || isAbsolute(relativePath)) {
    throw new Error(`${label} must be within the current working directory.`);
  }
}

function nearestExistingPath(path) {
  let currentPath = path;
  while (!existsSync(currentPath)) {
    const parentPath = dirname(currentPath);
    if (parentPath === currentPath) {
      throw new Error(`No existing parent found for ${path}`);
    }
    currentPath = parentPath;
  }
  return currentPath;
}

function resolveWithinCwd(label, filePath, options = {}) {
  const resolvedPath = resolve(filePath);
  assertWithinCwd(label, resolvedPath);

  if (existsSync(resolvedPath)) {
    assertWithinCwd(label, realpathSync(resolvedPath));
    return resolvedPath;
  }

  if (options.mustExist) {
    throw new Error(`${label} does not exist: ${resolvedPath}`);
  }

  const existingParent = nearestExistingPath(dirname(resolvedPath));
  const checkedPath = resolve(
    realpathSync(existingParent),
    relative(existingParent, resolvedPath),
  );
  assertWithinCwd(label, checkedPath);
  return resolvedPath;
}

function readJson(path) {
  if (!path || !existsSync(path)) {
    return null;
  }
  try {
    return JSON.parse(readFileSync(path, "utf8"));
  } catch (error) {
    return { error: error instanceof Error ? error.message : String(error) };
  }
}

function collectPlaywrightAttachments(results) {
  const attachments = [];

  function visitSuites(suites) {
    for (const suite of suites ?? []) {
      for (const spec of suite.specs ?? []) {
        for (const test of spec.tests ?? []) {
          for (const result of test.results ?? []) {
            attachments.push(...(result.attachments ?? []));
          }
        }
      }
      visitSuites(suite.suites);
    }
  }

  visitSuites(results?.suites);
  return attachments
    .map((attachment) => ({
      contentType: attachment.contentType || "",
      path: resolveExistingMediaPath("attachment", attachment.path || ""),
    }))
    .filter((attachment) => attachment.path);
}

function resolveExistingMediaPath(label, path) {
  if (!path) {
    return "";
  }

  try {
    return resolveWithinCwd(label, path, { mustExist: true });
  } catch {
    return "";
  }
}

function collectFiles(dir) {
  const safeDir = resolveExistingMediaPath("dir", dir);
  if (!safeDir) {
    return [];
  }

  const files = [];
  for (const entry of readdirSync(safeDir)) {
    const path = join(safeDir, entry);
    const stat = lstatSync(path);
    if (stat.isSymbolicLink()) {
      continue;
    }
    if (stat.isDirectory()) {
      files.push(...collectFiles(path));
    } else if (stat.isFile()) {
      files.push(path);
    }
  }
  return files;
}

function isImage(path, contentType = "") {
  return (
    contentType.startsWith("image/") || /\.(gif|jpe?g|png|svg)$/i.test(path)
  );
}

function isVideo(path, contentType = "") {
  return contentType.startsWith("video/") || /\.(mp4|mov|webm)$/i.test(path);
}

function copyMedia(sourcePath, outputDir, targetBase, fallbackExt) {
  if (!sourcePath) {
    return "";
  }

  const safeSourcePath = resolveWithinCwd("media source", sourcePath, {
    mustExist: true,
  });
  mkdirSync(outputDir, { recursive: true });
  const ext = extname(safeSourcePath) || fallbackExt;
  const targetPath = join(outputDir, `${targetBase}${ext}`);
  copyFileSync(safeSourcePath, targetPath);
  return targetPath;
}

function writeOutput(key, value) {
  const outputPath = process.env.GITHUB_OUTPUT;
  if (outputPath) {
    const escaped = String(value).replaceAll("\n", "%0A");
    writeFileSync(outputPath, `${key}=${escaped}\n`, { flag: "a" });
  }
  console.log(`${key}=${value}`);
}

async function main() {
  const args = parseArgs(process.argv.slice(2));
  const resultsPath = resolveWithinCwd(
    "results",
    args.results || "test-results-live/results.json",
  );
  const testResultsDir = resolveWithinCwd(
    "test-results-dir",
    args.test_results_dir || "test-results-live",
  );
  const outputDir = resolveWithinCwd(
    "output-dir",
    args.output_dir || "test-results-live/media",
  );
  const results = readJson(resultsPath);

  const attachments = collectPlaywrightAttachments(results);
  const files = collectFiles(testResultsDir).map((path) => ({
    contentType: "",
    path,
  }));
  const candidates = [...attachments, ...files];

  const screenshot = candidates.find((candidate) =>
    isImage(candidate.path, candidate.contentType),
  );
  const video = candidates.find((candidate) =>
    isVideo(candidate.path, candidate.contentType),
  );

  const screenshotPath = copyMedia(
    screenshot?.path,
    outputDir,
    "live-agent-response",
    ".png",
  );
  const videoPath = copyMedia(
    video?.path,
    outputDir,
    "live-agent-recording",
    ".webm",
  );

  writeOutput("screenshot_path", screenshotPath);
  writeOutput("video_path", videoPath);
}

main().catch((error) => {
  console.error(error instanceof Error ? error.message : String(error));
  process.exit(1);
});