File size: 14,238 Bytes
ef987bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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(`<svg xmlns="http://www.w3.org/2000/svg" width="120" height="90"><rect width="120" height="90" fill="${color}"/></svg>`);
      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);
});