const path = require('path'); const fs = require('fs'); const { pathToFileURL } = require('url'); const { chromium } = require('playwright'); const ACTION_TIMEOUT_MS = 5_000; const CASE_TIMEOUT_MS = 15_000; const GALLERY_IMAGES = '[data-testid="image-list"] img, img[data-testid="uploaded-image"]'; const PREVIEW_IMAGES = '[data-testid="image-preview"] img'; process.env.HARBOR_TEST_SEED = '58001'; const PNG = Buffer.from( 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFgwJ/luznTQAAAABJRU5ErkJggg==', 'base64' ); function assert(condition, message) { if (!condition) throw new Error(message); } async function within(ms, label, work) { let timer; try { return await Promise.race([ work(), new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms); }), ]); } finally { clearTimeout(timer); } } async function freshPage(browser) { const context = await browser.newContext({ offline: true, serviceWorkers: 'block' }); const page = await context.newPage(); page.setDefaultTimeout(ACTION_TIMEOUT_MS); page.setDefaultNavigationTimeout(ACTION_TIMEOUT_MS); await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded', timeout: ACTION_TIMEOUT_MS, }); return { context, page }; } async function capture(page, name) { fs.mkdirSync('/logs/verifier/visual-audit', {recursive: true}); await page.screenshot({path: `/logs/verifier/visual-audit/${name}.png`, fullPage: true}); } async function upload(page, names) { const files = names.map(name => ({ name, mimeType: 'image/png', buffer: PNG })); await page.locator('[data-testid="image-upload"]').setInputFiles(files, { timeout: ACTION_TIMEOUT_MS }); return originalDataUrls(files); } async function rasterSamples(browser) { const fixturePage = await browser.newPage({ offline: true }); try { const samples = await fixturePage.evaluate(() => { const canvas = document.createElement('canvas'); canvas.width = 12; canvas.height = 8; const context = canvas.getContext('2d'); return [ { name: 'photo.jpg', mimeType: 'image/jpeg', color: 'navy' }, { name: 'illustration.webp', mimeType: 'image/webp', color: 'gold' }, ].map(({ name, mimeType, color }) => { context.fillStyle = color; context.fillRect(0, 0, canvas.width, canvas.height); return { name, mimeType, dataUrl: canvas.toDataURL(mimeType) }; }); }); return samples.map(({ name, mimeType, dataUrl }) => { const prefix = 'data:' + mimeType + ';base64,'; assert(dataUrl.startsWith(prefix), 'test browser failed to encode ' + mimeType); return { name, mimeType, buffer: Buffer.from(dataUrl.slice(prefix.length), 'base64') }; }); } finally { await fixturePage.close(); } } async function assertPickerAllows(input, files) { const accept = await input.getAttribute('accept'); if (!accept || !accept.trim()) return; const tokens = accept.toLowerCase().split(',').map(token => token.trim()); for (const { name, mimeType } of files) { const suffix = path.extname(name).toLowerCase(); assert( tokens.includes(mimeType) || tokens.includes('image/*') || tokens.includes(suffix), 'the file picker excludes the supported image format ' + mimeType ); } } function originalDataUrls(files) { return files.map(({ mimeType, buffer }) => 'data:' + mimeType + ';base64,' + buffer.toString('base64')); } async function fixturePixels(page, sources) { const fixturePage = await page.context().newPage(); try { return await fixturePage.evaluate(urls => { const canvas = new OffscreenCanvas(16, 16); const context = canvas.getContext('2d', { willReadFrequently: true }); return Promise.all(urls.map(async url => { const image = new Image(); image.src = url; await image.decode(); context.clearRect(0, 0, canvas.width, canvas.height); context.drawImage(image, 0, 0, canvas.width, canvas.height); return [...context.getImageData(0, 0, canvas.width, canvas.height).data]; })); }, sources); } finally { await fixturePage.close(); } } async function waitForRenderedImages(page, selector, sources, ordered) { // Decode trusted fixtures in a blank page so application CSP cannot affect them. const expected = await fixturePixels(page, sources); const result = await page.waitForFunction(({ selector, expected, ordered }) => { const images = [...document.querySelectorAll(selector)]; if (ordered && images.length !== expected.length) return false; const isVisibleImage = image => image.complete && image.naturalWidth > 0 && image.naturalHeight > 0 && image.checkVisibility({ opacityProperty: true, visibilityProperty: true }) && image.getBoundingClientRect().width > 0 && image.getBoundingClientRect().height > 0; if (!images.some(isVisibleImage)) return false; const canvas = document.createElement('canvas'); canvas.width = canvas.height = 16; const context = canvas.getContext('2d', { willReadFrequently: true }); const sample = image => { context.clearRect(0, 0, canvas.width, canvas.height); context.drawImage(image, 0, 0, canvas.width, canvas.height); return context.getImageData(0, 0, canvas.width, canvas.height).data; }; const matches = (image, pixels) => { if (!isVisibleImage(image)) return false; const source = image.currentSrc || image.src; if (!source.startsWith('data:') && !source.startsWith('blob:')) return false; // The decoded bitmap remains available even after its object URL is revoked. const actual = sample(image); let difference = 0; for (let index = 0; index < pixels.length; index += 1) difference += Math.abs(actual[index] - pixels[index]); return difference / pixels.length <= 5; }; if (ordered) return images.every((image, index) => matches(image, expected[index])); // A truthy one-based index lets the zoom check measure the matching image. return images.findIndex(image => matches(image, expected[0])) + 1; }, { selector, expected, ordered }, { timeout: ACTION_TIMEOUT_MS }); try { return await result.jsonValue(); } finally { await result.dispose(); } } async function waitForDecodedGallery(page, expected) { await waitForRenderedImages(page, GALLERY_IMAGES, expected, true).catch(error => { throw new Error('the gallery did not decode all selected images in order', { cause: error }); }); } async function waitForPreviewImage(page, expected) { const index = await waitForRenderedImages(page, PREVIEW_IMAGES, [expected], false).catch(error => { throw new Error('preview should visibly show the uploaded image that was clicked', { cause: error }); }); return page.locator(PREVIEW_IMAGES).nth(index - 1); } // ENHANCED_CASE_1: mixed browser-decodable formats retain original bytes, MIME types and order. async function caseMultipleUpload(browser) { const { context, page } = await freshPage(browser); try { const input = page.locator('[data-testid="image-upload"]'); assert(await input.getAttribute('type') === 'file', 'image-upload must be a file input'); assert(await input.getAttribute('multiple') !== null, 'image-upload must allow multiple files'); const files = [{ name: 'graphic.png', mimeType: 'image/png', buffer: PNG }, ...await rasterSamples(browser)]; await assertPickerAllows(input, files); await input.setInputFiles(files); const expected = originalDataUrls(files); await waitForDecodedGallery(page, expected); const saved = await page.evaluate(() => window.__getImageStore()); assert(JSON.stringify(saved) === JSON.stringify(expected), 'store must preserve PNG, JPEG and WebP uploads byte-for-byte in selection order'); await upload(page, ['fourth.png']); expected.push(expected[0]); await waitForDecodedGallery(page, expected); const more = await page.evaluate(() => window.__getImageStore()); assert(JSON.stringify(more) === JSON.stringify(expected), 'a later upload must append without changing earlier images'); } finally { await context.close(); } } // ENHANCED_CASE_2: clicking an uploaded image opens a preview of that exact image. async function casePreview(browser) { const { context, page } = await freshPage(browser); try { const [expected] = await upload(page, ['preview-source.png']); await waitForDecodedGallery(page, [expected]); await page.locator(GALLERY_IMAGES).first().click(); await waitForPreviewImage(page, expected); } finally { await context.close(); } } async function previewArea(image) { const box = await image.boundingBox(); assert(box, 'preview should visibly show the selected image'); return box.width * box.height; } // ENHANCED_CASE_3: preview controls provide observable enlargement and reduction. async function caseZoomBothDirections(browser) { const { context, page } = await freshPage(browser); try { const [expected] = await upload(page, ['zoom-source.png']); await waitForDecodedGallery(page, [expected]); const image = page.locator(GALLERY_IMAGES).first(); await image.click(); const preview = page.locator('[data-testid="image-preview"]'); let previewImage = await waitForPreviewImage(page, expected); assert(await preview.getByTestId('zoom-button').count() > 0, 'required zoom control is missing'); let previous = await previewArea(previewImage); let enlarged = false; let reduced = false; const buttons = preview.locator('button, [role="button"]'); const count = await buttons.count(); for (let round = 0; round < 3 && !(enlarged && reduced); round += 1) { for (let i = 0; i < count && !(enlarged && reduced); i += 1) { const button = buttons.nth(i); if (!(await button.isVisible())) continue; await button.click({ timeout: ACTION_TIMEOUT_MS }); await page.waitForTimeout(220); if (!(await preview.isVisible())) { await image.click({ timeout: ACTION_TIMEOUT_MS }); previewImage = await waitForPreviewImage(page, expected); previous = await previewArea(previewImage); continue; } const current = await previewArea(previewImage); const tolerance = Math.max(0.001, previous * 0.001); enlarged ||= current > previous + tolerance; reduced ||= current < previous - tolerance; previous = current; } } assert(enlarged, 'a preview control should enlarge the uploaded image'); assert(reduced, 'a preview control should reduce the uploaded image'); } finally { await context.close(); } } // ENHANCED_CASE_4: distinct uploads retain selection order and reject non-image data. async function caseOrderedStoreAndFileType(browser) { const { context, page } = await freshPage(browser); try { const colors = ['red', 'green', 'blue']; const inputs = colors.map((color, index) => { const bytes = Buffer.from(``); return { name: `unique-${index}.svg`, mimeType: 'image/svg+xml', buffer: bytes }; }); const input = page.locator('[data-testid="image-upload"]'); await assertPickerAllows(input, inputs); await input.setInputFiles(inputs); const expected = originalDataUrls(inputs); await waitForDecodedGallery(page, expected); const saved = await page.evaluate(() => window.__getImageStore()); assert(JSON.stringify(saved) === JSON.stringify(expected), 'store must preserve the selected distinct-image order'); const copied = await page.evaluate(() => { const exposed = window.__getImageStore(); exposed.splice(0, exposed.length, 'corrupted'); return window.__getImageStore(); }); assert(JSON.stringify(copied) === JSON.stringify(expected), 'observer must return a copy, not a mutable store reference'); await capture(page, 'ordered-gallery'); const status = page.locator('[data-testid="status"], [role="status"], [role="alert"]').first(); const previousStatus = await status.innerText(); await page.locator('[data-testid="image-upload"]').setInputFiles({ name: 'not-an-image.txt', mimeType: 'text/plain', buffer: Buffer.from('not image pixels') }); await page.waitForFunction(previous => { const status = document.querySelector('[data-testid="status"], [role="status"], [role="alert"]'); return status && status.innerText.trim() && status.innerText !== previous; }, previousStatus); const after = await page.evaluate(() => window.__getImageStore()); assert(JSON.stringify(after) === JSON.stringify(expected), 'non-image files must not be saved as images'); assert(await status.isVisible(), 'invalid upload needs a visible new status'); await capture(page, 'invalid-file-feedback'); const images = page.locator(GALLERY_IMAGES); assert(await images.count() === expected.length, 'non-image files must not change the gallery'); await images.nth(1).click(); await waitForPreviewImage(page, expected[1]); await capture(page, 'second-image-preview'); } finally { await context.close(); } } const enhancedCases = { ENHANCED_CASE_1: caseMultipleUpload, ENHANCED_CASE_2: casePreview, ENHANCED_CASE_3: caseZoomBothDirections, ENHANCED_CASE_4: caseOrderedStoreAndFileType, }; (async () => { const requested = process.argv[2]; assert(!requested || enhancedCases[requested], `unknown enhanced case: ${requested}`); const browser = await chromium.launch({ headless: true, timeout: ACTION_TIMEOUT_MS }); try { const entries = requested ? [[requested, enhancedCases[requested]]] : Object.entries(enhancedCases); for (const [caseId, run] of entries) await within(CASE_TIMEOUT_MS, caseId, () => run(browser)); console.log(`task 58 enhanced cases passed (${entries.length}/${entries.length})`); } finally { await browser.close(); } })().catch((err) => { console.error(err && err.stack || err); process.exit(1); });