Spaces:
Runtime error
Runtime error
File size: 13,786 Bytes
cd8bd0a | 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 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 | #!/usr/bin/env node
import { chromium, devices } from "@playwright/test";
import { promises as fs } from "node:fs";
import path from "node:path";
const ROOT = process.cwd();
const REPORTS_DIR = path.join(ROOT, "docs", "reports");
const DATE = new Date().toISOString().slice(0, 10);
const BASE_URL = process.env.QA_BASE_URL || "http://localhost:20128";
const REPORT_SUFFIX = process.env.QA_REPORT_SUFFIX ? `-${process.env.QA_REPORT_SUFFIX}` : "";
const DEFAULT_LOCALES = ["es", "fr", "de", "ja", "ar"];
const RTL_LOCALES = new Set(["ar", "he"]);
const ROUTES = [
"/dashboard/analytics",
"/dashboard/api-manager",
"/dashboard/audit-log",
"/dashboard/cli-tools",
"/dashboard/combos",
"/dashboard/costs",
"/dashboard/endpoint",
"/dashboard/health",
"/dashboard/limits",
"/dashboard/logs",
"/dashboard/providers",
"/dashboard/settings",
"/dashboard/settings/pricing",
"/dashboard/translator",
"/dashboard/usage",
];
function parseRouteList(raw) {
if (!raw) {
return null;
}
const list = raw
.split(",")
.map((value) => value.trim())
.filter(Boolean)
.map((value) => (value.startsWith("/") ? value : `/${value}`));
return list.length > 0 ? list : null;
}
const customRoutes = parseRouteList(process.env.QA_ROUTES);
const ACTIVE_ROUTES = customRoutes || ROUTES;
function parseLocaleList(raw) {
if (!raw) {
return null;
}
const list = raw
.split(",")
.map((value) => value.trim())
.filter(Boolean);
return list.length > 0 ? list : null;
}
const customLocales = parseLocaleList(process.env.QA_LOCALES);
const ACTIVE_LOCALES = customLocales || DEFAULT_LOCALES;
const VIEWPORTS = [
{
name: "desktop",
viewport: { width: 1440, height: 900 },
userAgent: devices["Desktop Chrome"].userAgent,
},
{
name: "mobile",
viewport: devices["iPhone 13"].viewport,
userAgent: devices["iPhone 13"].userAgent,
isMobile: true,
hasTouch: true,
deviceScaleFactor: devices["iPhone 13"].deviceScaleFactor,
},
];
function safeRoute(route) {
return route === "/"
? "root"
: route.replace(/^\//, "").replace(/\//g, "__").replace(/\[|\]/g, "");
}
function classifyResult(item) {
if (item.error && !item.error.startsWith("screenshot-error:")) {
return "Ajuste necessario";
}
if (item.redirectedToLogin && item.route !== "/login") {
return "Ajuste necessario";
}
if (item.rtlMismatch) {
return "Ajuste necessario";
}
if (item.overflowCount > 8 || item.clippedCount > 6) {
return "Revisar";
}
if (item.error && item.error.startsWith("screenshot-error:")) {
return "Revisar";
}
return "OK";
}
async function ensureLoggedIn(page) {
await page.goto(`${BASE_URL}/dashboard`, { waitUntil: "domcontentloaded", timeout: 120000 });
if (!page.url().includes("/login")) {
return true;
}
const password = process.env.INITIAL_PASSWORD || "123456";
const input = page.locator('input[type="password"]');
if ((await input.count()) === 0) {
return false;
}
await input.first().fill(password);
const submit = page.locator('button[type="submit"]');
if ((await submit.count()) === 0) {
return false;
}
await submit.first().click();
await page.waitForTimeout(700);
try {
await page.waitForURL(/\/dashboard(\/.*)?/, { timeout: 30000 });
} catch {
// Keep going, final URL check below.
}
return !page.url().includes("/login");
}
async function evaluatePageHealth(page, locale) {
return page.evaluate(
({ locale, expectRtl }) => {
const hasHorizontalScrollContext = (el) => {
let current = el;
while (current) {
if (!(current instanceof HTMLElement)) {
break;
}
const cls = typeof current.className === "string" ? current.className : "";
if (
cls.includes("overflow-x-auto") ||
cls.includes("overflow-auto") ||
cls.includes("overflow-scroll")
) {
return true;
}
const style = window.getComputedStyle(current);
if (style.overflowX === "auto" || style.overflowX === "scroll") {
return true;
}
current = current.parentElement;
}
return false;
};
const isVisible = (el) => {
const style = window.getComputedStyle(el);
if (
style.display === "none" ||
style.visibility === "hidden" ||
Number(style.opacity) === 0
) {
return false;
}
const rect = el.getBoundingClientRect();
return rect.width > 0 && rect.height > 0;
};
const nodes = Array.from(document.querySelectorAll("*"));
let overflowCount = 0;
let clippedCount = 0;
const samples = [];
for (const el of nodes) {
if (!(el instanceof HTMLElement)) {
continue;
}
if (!isVisible(el)) {
continue;
}
const text = (el.innerText || "").trim().replace(/\s+/g, " ");
if (!text || text.length < 12) {
continue;
}
if (text === "Skip to content") {
continue;
}
const cls = el.className || "";
const classString = typeof cls === "string" ? cls : "";
if (
classString.includes("monaco-") ||
el.closest(".monaco-editor") ||
el.closest(".monaco-scrollable-element")
) {
continue;
}
if (el.tagName === "HTML" || el.tagName === "BODY") {
continue;
}
const overW = el.scrollWidth > el.clientWidth + 1;
if (!overW) {
continue;
}
if (hasHorizontalScrollContext(el)) {
continue;
}
// Decorative absolute layers often exceed bounds by design and should not
// be treated as localization regressions.
const style = window.getComputedStyle(el);
if (style.position === "absolute" && el.getAttribute("aria-hidden") === "true") {
continue;
}
overflowCount += 1;
const looksClipped =
classString.includes("truncate") ||
classString.includes("line-clamp-") ||
style.overflowX === "hidden" ||
style.overflowY === "hidden" ||
style.textOverflow === "ellipsis";
if (looksClipped) {
clippedCount += 1;
}
if (samples.length < 10 && looksClipped) {
samples.push({
tag: el.tagName.toLowerCase(),
className: classString.slice(0, 120),
text: text.slice(0, 140),
});
}
}
const dir = document.documentElement.getAttribute("dir") || "";
const lang = document.documentElement.getAttribute("lang") || "";
const rtlMismatch = expectRtl ? dir !== "rtl" : dir === "rtl";
return {
locale,
dir,
lang,
rtlMismatch,
overflowCount,
clippedCount,
clippedSamples: samples,
};
},
{ locale, expectRtl: RTL_LOCALES.has(locale) }
);
}
async function run() {
await fs.mkdir(REPORTS_DIR, { recursive: true });
const screenshotRoot = path.join(REPORTS_DIR, `i18n-qa-screenshots-${DATE}`);
await fs.mkdir(screenshotRoot, { recursive: true });
const browser = await chromium.launch({ headless: true });
const allResults = [];
for (const viewportSpec of VIEWPORTS) {
const context = await browser.newContext({
viewport: viewportSpec.viewport,
userAgent: viewportSpec.userAgent,
isMobile: viewportSpec.isMobile,
hasTouch: viewportSpec.hasTouch,
deviceScaleFactor: viewportSpec.deviceScaleFactor,
});
const page = await context.newPage();
const logged = await ensureLoggedIn(page);
console.log(`[qa] ${viewportSpec.name} login state: ${logged ? "ok" : "not-authenticated"}`);
for (const locale of ACTIVE_LOCALES) {
await context.addCookies([
{
name: "NEXT_LOCALE",
value: locale,
domain: "localhost",
path: "/",
},
]);
for (const route of ACTIVE_ROUTES) {
const started = Date.now();
const result = {
route,
locale,
viewport: viewportSpec.name,
finalUrl: "",
durationMs: 0,
status: "OK",
redirectedToLogin: false,
rtlMismatch: false,
overflowCount: 0,
clippedCount: 0,
clippedSamples: [],
dir: "",
lang: "",
error: "",
screenshot: "",
};
try {
await page.goto(`${BASE_URL}${route}`, {
waitUntil: "domcontentloaded",
timeout: 120000,
});
await page.waitForTimeout(500);
result.finalUrl = page.url();
result.redirectedToLogin = result.finalUrl.includes("/login");
const metrics = await evaluatePageHealth(page, locale);
result.rtlMismatch = metrics.rtlMismatch;
result.overflowCount = metrics.overflowCount;
result.clippedCount = metrics.clippedCount;
result.clippedSamples = metrics.clippedSamples;
result.dir = metrics.dir;
result.lang = metrics.lang;
} catch (error) {
result.error = String(error?.message || error);
}
result.durationMs = Date.now() - started;
const localeDir = path.join(screenshotRoot, viewportSpec.name, locale);
await fs.mkdir(localeDir, { recursive: true });
const screenshotPath = path.join(localeDir, `${safeRoute(route)}.png`);
try {
await page.screenshot({ path: screenshotPath, fullPage: true, timeout: 120000 });
result.screenshot = path.relative(ROOT, screenshotPath).replaceAll("\\", "/");
} catch (error) {
if (!result.error) {
result.error = `screenshot-error: ${String(error?.message || error)}`;
}
}
result.status = classifyResult(result);
allResults.push(result);
console.log(
`[qa] ${viewportSpec.name} ${locale} ${route} -> ${result.status}` +
`${result.redirectedToLogin ? " (redirected-login)" : ""}` +
`${result.rtlMismatch ? " (rtl-mismatch)" : ""}` +
`${result.clippedCount ? ` (clipped=${result.clippedCount})` : ""}`
);
}
}
await context.close();
}
await browser.close();
const jsonPath = path.join(REPORTS_DIR, `i18n-visual-qa-${DATE}${REPORT_SUFFIX}.json`);
await fs.writeFile(jsonPath, `${JSON.stringify(allResults, null, 2)}\n`, "utf8");
const aggregate = new Map();
const aggregateByLocale = new Map();
for (const item of allResults) {
const key = item.route;
if (!aggregate.has(key)) {
aggregate.set(key, {
route: key,
ok: 0,
review: 0,
adjust: 0,
clipped: 0,
loginRedirects: 0,
rtlMismatch: 0,
});
}
const slot = aggregate.get(key);
if (item.status === "OK") slot.ok += 1;
if (item.status === "Revisar") slot.review += 1;
if (item.status === "Ajuste necessario") slot.adjust += 1;
slot.clipped += item.clippedCount;
if (item.redirectedToLogin) slot.loginRedirects += 1;
if (item.rtlMismatch) slot.rtlMismatch += 1;
const localeKey = item.locale;
if (!aggregateByLocale.has(localeKey)) {
aggregateByLocale.set(localeKey, {
locale: localeKey,
ok: 0,
review: 0,
adjust: 0,
clipped: 0,
loginRedirects: 0,
rtlMismatch: 0,
});
}
const localeSlot = aggregateByLocale.get(localeKey);
if (item.status === "OK") localeSlot.ok += 1;
if (item.status === "Revisar") localeSlot.review += 1;
if (item.status === "Ajuste necessario") localeSlot.adjust += 1;
localeSlot.clipped += item.clippedCount;
if (item.redirectedToLogin) localeSlot.loginRedirects += 1;
if (item.rtlMismatch) localeSlot.rtlMismatch += 1;
}
const lines = [
"# Relatorio QA Visual i18n",
"",
`Data: ${DATE}`,
`Base URL: ${BASE_URL}`,
`Locales: ${ACTIVE_LOCALES.join(", ")}`,
`Viewports: ${VIEWPORTS.map((v) => v.name).join(", ")}`,
"",
"## Resumo por rota",
"",
"| Rota | OK | Revisar | Ajuste necessario | Clipped total | Redirect login | RTL mismatch |",
"|---|---:|---:|---:|---:|---:|---:|",
...Array.from(aggregate.values()).map(
(row) =>
`| \`${row.route}\` | ${row.ok} | ${row.review} | ${row.adjust} | ${row.clipped} | ${row.loginRedirects} | ${row.rtlMismatch} |`
),
"",
"## Resumo por locale",
"",
"| Locale | OK | Revisar | Ajuste necessario | Clipped total | Redirect login | RTL mismatch |",
"|---|---:|---:|---:|---:|---:|---:|",
...Array.from(aggregateByLocale.values())
.sort((a, b) => a.locale.localeCompare(b.locale))
.map(
(row) =>
`| \`${row.locale}\` | ${row.ok} | ${row.review} | ${row.adjust} | ${row.clipped} | ${row.loginRedirects} | ${row.rtlMismatch} |`
),
"",
"## Artefatos",
"",
`- JSON detalhado: \`${path.relative(ROOT, jsonPath)}\``,
`- Screenshots: \`${path.relative(ROOT, screenshotRoot)}\``,
"",
"## Observacoes",
"",
"- Status `Revisar` e `Ajuste necessario` sao heuristicas automaticas (overflow/clipping/RTL/redirect).",
"- A validacao final de UX deve ser confirmada manualmente nas rotas sinalizadas.",
];
const mdPath = path.join(REPORTS_DIR, `i18n-visual-qa-${DATE}${REPORT_SUFFIX}.md`);
await fs.writeFile(mdPath, `${lines.join("\n")}\n`, "utf8");
console.log(mdPath);
console.log(jsonPath);
}
run().catch((error) => {
console.error(error);
process.exit(1);
});
|