verify-download-site.mjs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. /** Local-only regression checks for the standalone download website. */
  2. import assert from 'node:assert/strict';
  3. import { createServer } from 'node:http';
  4. import { mkdir, readFile, writeFile } from 'node:fs/promises';
  5. import { dirname, resolve } from 'node:path';
  6. import { fileURLToPath, pathToFileURL } from 'node:url';
  7. import { chromium } from 'playwright';
  8. const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
  9. const site = resolve(root, 'prototypes/fmode-download-20261120');
  10. const output = resolve(root, 'test-results/download-site');
  11. const html = await readFile(resolve(site, 'index.html'), 'utf8');
  12. const source = await readFile(resolve(site, 'site.js'), 'utf8');
  13. const configPattern = /const FMODE_SITE = (\{[^\n]+\});/;
  14. const config = Function('return (' + source.match(configPattern)[1] + ')')();
  15. const errors = [];
  16. const checks = [];
  17. await mkdir(output, { recursive: true });
  18. const variants = new Map();
  19. function variant(name, apkUrl, extra = {}) {
  20. variants.set('/' + name + '/', html.replace(configPattern, () => 'const FMODE_SITE = ' + JSON.stringify({ ...config, apkUrl, ...extra }) + ';'));
  21. }
  22. variant('missing', '');
  23. variant('unsafe', 'javascript:alert(1)');
  24. variant('insecure', 'http://example.com/fmode.apk');
  25. variant('protocol-relative', '//example.com/fmode.apk');
  26. variant('relative', '/download/future.apk');
  27. variant('new-release', 'https://example.com/fmode-v2.apk?signature=a%2Fb&v=2', { version: '2.0', fileSize: '12 MB', channel: '正式版' });
  28. variants.set('/qr-error/', html.replace('const qr = qrcodegen.QrCode.encodeText', 'const qr = missingQrEncoder.encodeText'));
  29. const server = createServer((request, response) => {
  30. const pathname = new URL(request.url, 'http://localhost').pathname;
  31. if (pathname.endsWith('.apk')) {
  32. response.writeHead(200, { 'Content-Type': 'application/vnd.android.package-archive', 'Content-Disposition': 'attachment; filename="Fmode.apk"' });
  33. response.end('download smoke-test fixture');
  34. return;
  35. }
  36. const content = pathname === '/download/' ? html : variants.get(pathname);
  37. response.writeHead(content ? 200 : 404, { 'Content-Type': 'text/html; charset=utf-8' });
  38. response.end(content || 'Not found');
  39. });
  40. await new Promise((done) => server.listen(0, '127.0.0.1', done));
  41. const base = 'http://127.0.0.1:' + server.address().port;
  42. const browser = await chromium.launch({ headless: true, executablePath: chromium.executablePath() });
  43. const context = await browser.newContext({ reducedMotion: 'reduce', permissions: ['clipboard-read', 'clipboard-write'] });
  44. await context.route('https://ai.fmode.cn/download/*.apk', (route) => route.fulfill({
  45. status: 200,
  46. headers: { 'Content-Type': 'application/vnd.android.package-archive', 'Content-Disposition': 'attachment; filename="Fmode.apk"' },
  47. body: 'download smoke-test fixture',
  48. }));
  49. const page = await context.newPage();
  50. page.on('pageerror', (error) => errors.push(error.message));
  51. page.on('request', (request) => {
  52. if (!request.url().startsWith(base) && !request.url().startsWith('data:') && request.url() !== config.apkUrl) errors.push('Unexpected external request: ' + request.url());
  53. });
  54. async function open(path = '/download/') {
  55. await page.goto(base + path);
  56. await page.evaluate(() => document.fonts.ready);
  57. }
  58. async function noOverflow(label) {
  59. const sizes = await page.evaluate(() => ({ scroll: document.documentElement.scrollWidth, viewport: window.innerWidth }));
  60. assert(sizes.scroll <= sizes.viewport, label + ': horizontal overflow ' + JSON.stringify(sizes));
  61. }
  62. async function screenshot(name, locator, fullPage = false) {
  63. const options = { path: resolve(output, name + '.png'), animations: 'disabled' };
  64. if (locator) await locator.screenshot({ ...options, style: '.site-header, .mobile-download-bar { visibility: hidden !important; }' });
  65. else await page.screenshot({ ...options, fullPage });
  66. }
  67. async function downloadFrom(selector) {
  68. const event = page.waitForEvent('download');
  69. await page.locator(selector).click();
  70. const download = await event;
  71. assert.equal(download.url(), config.apkUrl);
  72. await download.cancel();
  73. }
  74. try {
  75. for (const width of [320, 360, 375, 390, 430, 650, 760, 768, 1024, 1440, 1920]) {
  76. await page.setViewportSize({ width, height: width <= 760 ? 844 : 960 });
  77. await open();
  78. await noOverflow('viewport ' + width);
  79. for (const scene of ['workbench', 'deliverables', 'conversation']) {
  80. await page.locator('#tab-' + scene).click();
  81. assert.equal(await page.locator('#scene-' + scene).isVisible(), true);
  82. await noOverflow(width + ' / ' + scene);
  83. }
  84. const sizes = await page.locator('.hero-actions .button').evaluateAll((buttons) => buttons.map((button) => ({ height: button.getBoundingClientRect().height, font: parseFloat(getComputedStyle(button).fontSize) })));
  85. assert(sizes.every((size) => size.height >= 44 && size.font >= 12), 'Small hero buttons at ' + width);
  86. const isMobile = width <= 760;
  87. assert.equal(await page.locator('.mobile-download-bar').isVisible(), isMobile);
  88. if (isMobile) {
  89. await page.locator('#menuToggle').click();
  90. assert.equal(await page.locator('#menuToggle').getAttribute('aria-expanded'), 'true');
  91. await page.locator('#navLinks a[href="#download"]').click();
  92. assert.equal(await page.locator('#menuToggle').getAttribute('aria-expanded'), 'false');
  93. }
  94. await page.evaluate(() => window.scrollTo(0, 0));
  95. if ([320, 390, 1440].includes(width)) {
  96. await screenshot('hero-' + width);
  97. await screenshot('full-' + width, null, true);
  98. await screenshot('download-' + width, page.locator('.download-card'));
  99. }
  100. await page.locator('.hero-actions [data-show-qr]').click();
  101. assert.equal(await page.locator('#downloadDialog').evaluate((dialog) => dialog.open), true);
  102. assert.equal(await page.locator('#dialogQr').isVisible(), true);
  103. await noOverflow('QR dialog ' + width);
  104. if ([390, 1440].includes(width)) await screenshot('qr-dialog-' + width);
  105. await page.keyboard.press('Escape');
  106. assert.equal(await page.locator('#downloadDialog').evaluate((dialog) => dialog.open), false);
  107. assert.equal(await page.evaluate(() => document.activeElement.matches('.hero-actions [data-show-qr]')), true);
  108. checks.push('Responsive layout, tabs, menu, QR dialog and focus at ' + width + 'px');
  109. }
  110. await page.setViewportSize({ width: 1440, height: 960 });
  111. await open();
  112. const targets = await page.locator('[data-download]').evaluateAll((links) => links.map((link) => link.href));
  113. assert(targets.length >= 4 && targets.every((url) => url === config.apkUrl));
  114. await downloadFrom('.hero-actions [data-download]');
  115. await downloadFrom('.nav-actions [data-download]');
  116. await downloadFrom('#apkButton');
  117. await page.locator('.hero-actions [data-show-qr]').click();
  118. await downloadFrom('[data-dialog-download]');
  119. await page.locator('.dialog-actions [data-copy-link]').click();
  120. assert.match(await page.locator('#dialogCopyStatus').textContent(), /已复制/);
  121. await page.locator('#dialogClose').click();
  122. await page.locator('.download-qr [data-copy-link]').click();
  123. assert.equal(await page.evaluate(() => navigator.clipboard.readText()), config.apkUrl);
  124. const qrImage = await page.locator('.download-qr [data-qr-image]').getAttribute('src');
  125. assert(qrImage.startsWith('data:image/png;base64,'));
  126. await writeFile(resolve(output, 'download-qr.png'), Buffer.from(qrImage.split(',')[1], 'base64'));
  127. checks.push('Header / hero / section / dialog links share URL; real download events; clipboard; QR exported');
  128. await page.setViewportSize({ width: 390, height: 844 });
  129. await open();
  130. await downloadFrom('.mobile-download-bar [data-download]');
  131. await page.locator('.mobile-download-bar [data-show-qr]').click();
  132. await page.keyboard.press('Tab');
  133. assert.equal(await page.evaluate(() => document.getElementById('downloadDialog').contains(document.activeElement)), true);
  134. await page.keyboard.press('Escape');
  135. await page.locator('#menuToggle').click();
  136. await page.keyboard.press('Escape');
  137. assert.equal(await page.evaluate(() => document.activeElement.id), 'menuToggle');
  138. await page.locator('#faq details').first().locator('summary').click();
  139. assert.equal(await page.locator('#faq details').first().getAttribute('open'), '');
  140. checks.push('Mobile sticky download, focus containment, menu Esc, FAQ');
  141. for (const [width, height] of [[320, 568], [390, 600], [760, 420]]) {
  142. await page.setViewportSize({ width, height });
  143. await open();
  144. await page.locator('.hero-actions [data-show-qr]').click();
  145. const bounds = await page.locator('#downloadDialog').boundingBox();
  146. assert(bounds.y >= 0 && bounds.y + bounds.height <= height, 'Dialog fits short viewport');
  147. await page.locator('#dialogConfirm').click();
  148. assert.equal(await page.locator('#downloadDialog').evaluate((dialog) => dialog.open), false);
  149. }
  150. checks.push('QR dialogs scroll and close in 320×568, 390×600 and 760×420 viewports');
  151. for (const name of ['missing', 'unsafe', 'insecure', 'protocol-relative']) {
  152. await open('/' + name + '/');
  153. assert.equal(await page.locator('.download-qr [data-qr-image]').isVisible(), false);
  154. assert.equal(await page.locator('.download-qr [data-copy-link]').isDisabled(), true);
  155. await page.locator('.hero-actions [data-download]').click();
  156. assert.match(await page.locator('#dialogTitle').textContent(), /准备/);
  157. assert.equal(await page.locator('[data-dialog-download]').isVisible(), false);
  158. await page.keyboard.press('Escape');
  159. }
  160. await open('/relative/');
  161. assert.equal(await page.locator('#apkButton').getAttribute('href'), base + '/download/future.apk');
  162. await open('/new-release/');
  163. assert.match(await page.locator('#releaseMeta').textContent(), /2\.0.*12 MB/);
  164. assert.equal(await page.locator('#apkButton').getAttribute('href'), 'https://example.com/fmode-v2.apk?signature=a%2Fb&v=2');
  165. const newQrImage = await page.locator('.download-qr [data-qr-image]').getAttribute('src');
  166. assert.notEqual(qrImage, newQrImage);
  167. await writeFile(resolve(output, 'download-qr-new-release.png'), Buffer.from(newQrImage.split(',')[1], 'base64'));
  168. await open('/qr-error/');
  169. assert.match(await page.locator('[data-qr-placeholder]').textContent(), /不可用/);
  170. assert.equal(await page.locator('#apkButton').getAttribute('href'), config.apkUrl);
  171. await page.locator('.hero-actions [data-show-qr]').click();
  172. assert.equal(await page.locator('[data-dialog-download]').isVisible(), true);
  173. checks.push('Missing / unsafe URLs; relative URL; release changes update QR; QR failure keeps direct download');
  174. for (const [name, userAgent, expected] of [
  175. ['ios', 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 Version/18.0 Mobile/15E148 Safari/604.1', /Android 版/],
  176. ['wechat', 'Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 Chrome/130.0.0.0 Mobile Safari/537.36 MicroMessenger/8.0', /浏览器/],
  177. ]) {
  178. const mobileContext = await browser.newContext({ viewport: { width: 390, height: 844 }, userAgent, isMobile: true, hasTouch: true, reducedMotion: 'reduce' });
  179. const mobile = await mobileContext.newPage();
  180. mobile.on('pageerror', (error) => errors.push(error.message));
  181. await mobile.goto(base + '/download/');
  182. await mobile.locator('.mobile-download-bar [data-download]').click();
  183. assert.match(await mobile.locator('#dialogTitle').textContent(), expected);
  184. assert.equal(await mobile.locator('[data-dialog-download]').isVisible(), false);
  185. await mobile.screenshot({ path: resolve(output, 'device-' + name + '.png'), animations: 'disabled' });
  186. await mobileContext.close();
  187. }
  188. checks.push('iOS compatibility message; WeChat browser instructions');
  189. await page.close();
  190. const fallbackContext = await browser.newContext({ reducedMotion: 'reduce' });
  191. const fallback = await fallbackContext.newPage();
  192. await fallback.addInitScript(() => { Object.defineProperty(navigator, 'clipboard', { value: undefined }); });
  193. await fallback.goto(base + '/download/');
  194. await fallback.locator('.download-qr [data-copy-link]').click();
  195. assert.equal(await fallback.locator('#manualCopy').isVisible(), true);
  196. assert.equal(await fallback.locator('#downloadLink').inputValue(), config.apkUrl);
  197. await fallbackContext.close();
  198. checks.push('Clipboard unavailable: selected, manually copyable URL');
  199. const offline = await context.newPage();
  200. await context.setOffline(true);
  201. await offline.goto(pathToFileURL(resolve(site, 'index.html')).href);
  202. assert.equal(await offline.locator('.download-qr [data-qr-image]').isVisible(), true);
  203. await context.setOffline(false);
  204. await offline.close();
  205. checks.push('Standalone file renders QR fully offline');
  206. assert.deepEqual(errors, [], 'Browser errors or unexpected external resources');
  207. await writeFile(resolve(output, 'results.json'), JSON.stringify({ success: true, checks, errors }, null, 2));
  208. console.log(JSON.stringify({ success: true, checks, screenshots: output }, null, 2));
  209. } finally {
  210. await browser.close();
  211. await new Promise((done) => server.close(done));
  212. }