import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { createServer } from 'node:http';
import { readFile, readdir } from 'node:fs/promises';
import { dirname, extname, join, resolve, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
import { chromium } from 'playwright';
import chardet from '../../public/strata/the-encoding-your-text-file-admits-to/chardet-2.2.0.mjs';
import {
  DETECTOR_CANDIDATES,
  FALLBACK_BYTES,
  FALLBACK_DECLARED_BYTES,
  FFFD_VECTORS,
  MAX_BYTES,
  SINGLE_BYTE_INDEXES,
  STRICT_CANDIDATES,
  UTF8_PROBES,
  UTF8_ROWS,
  UTF8_ROW_TABLE,
  UTF8_VECTORS,
  VENDOR_CP1252_UNDEFINED,
  bytesEqual,
  compareReadings,
  decodeAll,
  decodeSingle,
  decodeUtf16,
  decodeUtf32,
  detectBom,
  encodeSingle,
  formatRow,
  mojibakeChain,
  prefixLengths,
  scalarsToString,
  spansTile,
  substituteUtf8,
  totalityReport,
  validateUtf8,
} from '../../public/strata/the-encoding-your-text-file-admits-to/engine.mjs';

const here = dirname(fileURLToPath(import.meta.url));
const root = resolve(here, '../..');
const publicDir = join(root, 'public/strata/the-encoding-your-text-file-admits-to');
const htmlPath = join(publicDir, 'index.html');
const pagePath = join(publicDir, 'page.js');
const enginePath = join(publicDir, 'engine.mjs');
const fallbackPath = join(publicDir, 'fallback/the-same-bytes.txt');
const markdownPath = join(root, 'src/content/strata/the-encoding-your-text-file-admits-to.md');
const readmePath = join(here, 'README.md');

let checks = 0;
function check(condition, message) {
  checks += 1;
  assert.ok(condition, message);
  console.log(`PASS ${String(checks).padStart(3, '0')} ${message}`);
}

function equal(actual, expected, message) {
  checks += 1;
  assert.deepEqual(actual, expected, message);
  console.log(`PASS ${String(checks).padStart(3, '0')} ${message}`);
}

function sha(bytes) {
  return createHash('sha256').update(bytes).digest('hex');
}

function fatalPlatform(bytes) {
  try {
    new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
    return true;
  } catch {
    return false;
  }
}

const [html, pageJs, engineJs, fallbackBuffer, markdown, readme, license] = await Promise.all([
  readFile(htmlPath, 'utf8'),
  readFile(pagePath, 'utf8'),
  readFile(enginePath, 'utf8'),
  readFile(fallbackPath),
  readFile(markdownPath, 'utf8'),
  readFile(readmePath, 'utf8'),
  readFile(join(publicDir, 'CHARDET-LICENSE.txt'), 'utf8'),
]);

console.log('Published anchor');
equal(UTF8_ROWS, [
  '00..7F',
  'C2..DF 80..BF',
  'E0 A0..BF 80..BF',
  'E1..EC 80..BF 80..BF',
  'ED 80..9F 80..BF',
  'EE..EF 80..BF 80..BF',
  'F0 90..BF 80..BF 80..BF',
  'F1..F3 80..BF 80..BF 80..BF',
  'F4 80..8F 80..BF 80..BF',
], 'all nine Unicode Table 3-7 forms are exact');

equal(UTF8_ROWS, UTF8_ROW_TABLE.map(formatRow), 'the nine printed row strings are rendered from the same table the validator reads, not typed a second time');

for (const vector of UTF8_VECTORS) {
  const bytes = Uint8Array.from(vector.bytes);
  const local = validateUtf8(bytes);
  equal(local.valid, vector.expected, `${vector.label} state-machine verdict reproduces ${vector.printed}`);
  equal(fatalPlatform(bytes), vector.expected, `${vector.label} independent fatal TextDecoder reproduces ${vector.printed}`);
}
equal(validateUtf8(Uint8Array.from([0xf4, 0x80, 0x83, 0x92])).scalars[0].cp, 0x1000d2, 'published valid vector emits U+1000D2');

// How many distinct characters the nine rows admit, counted from the ranges rather than quoted.
// Chapter 2 prints 1,114,112 code points in the codespace and 2,048 surrogate code points; their
// difference is a derived figure, not a printed one, and this is the derivation.
const perLength = [0, 0, 0, 0];
for (const row of UTF8_ROW_TABLE) {
  const width = row.cont.length + 1;
  perLength[width - 1] += (row.lead[1] - row.lead[0] + 1) * row.cont.reduce((n, [lo, hi]) => n * (hi - lo + 1), 1);
}
equal(perLength, [128, 1920, 61440, 1048576], 'the nine rows admit 128, 1,920, 61,440 and 1,048,576 characters at one through four bytes');
equal(perLength.reduce((a, b) => a + b, 0), 1114112 - 2048, 'and 1,112,064 in total, which is the printed 1,114,112 codespace minus the printed 2,048 surrogates');
// Which byte values never occur anywhere in a well-formed sequence, derived by enumeration.
const usable = new Set();
for (const row of UTF8_ROW_TABLE) {
  for (let b = row.lead[0]; b <= row.lead[1]; b += 1) usable.add(b);
  for (const [lo, hi] of row.cont) for (let b = lo; b <= hi; b += 1) usable.add(b);
}
const disallowed = Array.from({ length: 256 }, (_, i) => i).filter((b) => !usable.has(b));
equal(disallowed, [0xc0, 0xc1, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff],
  'exactly thirteen byte values never appear anywhere in a well-formed sequence, which is the printed C0, C1 and F5..FF');
for (const byte of disallowed) check(!validateUtf8(Uint8Array.of(byte)).valid && !validateUtf8(Uint8Array.of(0x41, byte, 0x41)).valid, `byte ${byte.toString(16).toUpperCase()} is refused both alone and inside ASCII text`);
check(html.includes('1,112,064'), 'the derived character count is printed for the reader and labelled as derived');

console.log('Derived boundary probes');
equal(UTF8_PROBES.length, 10, 'ten boundary probes are derived from the row limits');
for (const probe of UTF8_PROBES) {
  const bytes = Uint8Array.from(probe.bytes);
  equal(validateUtf8(bytes).valid, probe.expected, `probe ${probe.label} state machine says ${probe.expected ? 'well-formed' : 'ill-formed'}`);
  equal(fatalPlatform(bytes), probe.expected, `probe ${probe.label} fatal TextDecoder agrees`);
}
equal(validateUtf8(Uint8Array.from([0xed, 0x9f, 0xbf])).scalars[0].cp, 0xd7ff, 'the scalar below the surrogate block is U+D7FF');
equal(validateUtf8(Uint8Array.from([0xf4, 0x8f, 0xbf, 0xbf])).scalars[0].cp, 0x10ffff, 'the highest well-formed sequence is U+10FFFF');
equal(validateUtf8(Uint8Array.from([0xef, 0xbf, 0xbe])).scalars[0].cp, 0xfffe, 'U+FFFE is a noncharacter and still well-formed, so the validator must accept it');
equal(validateUtf8(Uint8Array.from([0xed, 0xa0, 0xbd, 0xed, 0xb9, 0x82])).reason, 'surrogate-range sequence', 'a CESU-8 surrogate pair refuses as a surrogate-range sequence');
equal(validateUtf8(Uint8Array.from([0xed, 0xa0, 0xbd, 0xed, 0xb9, 0x82])).offset, 1, 'the CESU-8 refusal names byte 1');

console.log('Exact visible refusal detail strings');
const details = [
  [validateUtf8(Uint8Array.from([0xc0, 0xaf])), 'overlong lead byte', 'byte C0 cannot begin any Table 3-7 row'],
  [validateUtf8(Uint8Array.from([0xe0, 0x9f, 0x80])), 'overlong three-byte sequence', 'byte 9F is outside A0..BF for row 3'],
  [validateUtf8(Uint8Array.from([0xed, 0xa0, 0x80])), 'surrogate-range sequence', 'byte A0 is outside 80..9F for row 5'],
  [validateUtf8(Uint8Array.from([0xc2])), 'missing continuation byte', 'file ends after byte 0; row 2 needs 2 bytes'],
  [validateUtf8(Uint8Array.from([0xff])), 'byte value never used by any UTF-8 form', 'byte FF cannot begin any Table 3-7 row'],
  [validateUtf8(Uint8Array.from([0xf8])), 'lead byte from the withdrawn five and six byte forms', 'byte F8 cannot begin any Table 3-7 row'],
  [decodeUtf16(Uint8Array.from([0x61]), true), 'odd byte count', 'UTF-16 needs pairs; byte 0 has no partner'],
  [decodeUtf16(Uint8Array.from([0x00, 0xd8, 0x41, 0x00]), true), 'high surrogate not followed by low surrogate', 'U+D800 is followed by U+0041'],
  [decodeUtf32(Uint8Array.from([0xff, 0xfe, 0x00, 0x00, 0x41]), true), 'length is not divisible by four', '1 trailing byte begins at offset 4'],
  [decodeUtf32(Uint8Array.from([0x00, 0x00, 0x11, 0x00]), true), 'value above U+10FFFF', 'U+110000 occupies bytes 0..3'],
  [decodeSingle(Uint8Array.of(0xae), 'iso-8859-7'), 'undefined mapping', 'AE has a null entry in the iso-8859-7 index'],
];
for (const [result, reason, detail] of details) {
  equal(result.reason, reason, `refusal class is exact: ${reason}`);
  equal(result.detail, detail, `refusal detail sentence is exact: ${detail}`);
}
const refusedChain = mojibakeChain(Uint8Array.from([0xd2, 0x80]), 'windows-1253');
equal([refusedChain.ok, refusedChain.stage, refusedChain.detail], [false, 'decode as single-byte text', 'D2 has a null entry in the windows-1253 index'],
  'the workbench refusal names its stage and the undefined byte exactly');
const acceptedChain = mojibakeChain(Uint8Array.from([0xd2, 0x80]), 'windows-1252');
check(acceptedChain.ok && acceptedChain.finalEqual, 'the same two bytes make a reversible chain through windows-1252, so the refusal above is about the table and not the bytes');

console.log('U+FFFD substitution against the four printed Unicode tables');
const lenient = new TextDecoder('utf-8', { fatal: false, ignoreBOM: true });
const codePointsOf = (text) => Array.from(text, (c) => c.codePointAt(0));
for (const vector of FFFD_VECTORS) {
  const bytes = Uint8Array.from(vector.bytes);
  equal(substituteUtf8(bytes).scalars, vector.output, `${vector.table} maximal-subpart output reproduces the printed row`);
  equal(codePointsOf(lenient.decode(bytes)), vector.output, `${vector.table} browser replacement decoder reproduces the printed row`);
}
const table311 = FFFD_VECTORS.find((v) => v.table === 'Table 3-11');
equal(table311.output.filter((cp) => cp === 0xfffd).length, 4, 'Table 3-11 prints four U+FFFD, which is the count that separates maximal-subpart from per-byte substitution');
equal(table311.bytes.length - 1, 8, 'per-byte substitution would have printed eight U+FFFD for the same nine bytes');
// The substitution routine and the browser decoder are separate implementations of one rule. Run
// every byte string of length one, two and three through both.
let substitutionMismatches = 0;
const triple = new Uint8Array(3);
for (let a = 0; a < 256; a += 1) {
  for (let b = 0; b < 256; b += 1) {
    for (let c = 0; c < 256; c += 1) {
      triple[0] = a; triple[1] = b; triple[2] = c;
      const mine = substituteUtf8(triple).scalars;
      const theirs = codePointsOf(lenient.decode(triple));
      if (mine.length !== theirs.length || mine.some((cp, i) => cp !== theirs[i])) substitutionMismatches += 1;
    }
  }
}
equal(substitutionMismatches, 0, 'all 16,777,216 byte strings of length three substitute identically in the local routine and the browser decoder');

console.log('Falsifiability: six corruptions of Table 3-7');
const corruptions = [
  ['row 3 lower limit A0 becomes 80, admitting overlong three-byte forms', (t) => { t[2].cont[0][0] = 0x80; }],
  ['row 5 upper limit 9F becomes BF, admitting surrogates', (t) => { t[4].cont[0][1] = 0xbf; }],
  ['row 7 lower limit 90 becomes 80, admitting overlong four-byte forms', (t) => { t[6].cont[0][0] = 0x80; }],
  ['row 9 upper limit 8F becomes BF, admitting values above U+10FFFF', (t) => { t[8].cont[0][1] = 0xbf; }],
  ['row 2 lead C2 becomes C0, admitting overlong two-byte forms', (t) => { t[1].lead[0] = 0xc0; }],
  ['row 1 lead 00..7F becomes 00..80, admitting a lone continuation byte', (t) => { t[0].lead[1] = 0x80; }],
];
const cloneTable = () => UTF8_ROW_TABLE.map((r) => ({ lead: [...r.lead], cont: r.cont.map((c) => [...c]), lowFail: r.lowFail, highFail: r.highFail }));
const printedOnly = UTF8_VECTORS.map((v) => ({ bytes: v.bytes, expected: v.expected }));
const printedAndProbes = [...printedOnly, ...UTF8_PROBES.map((v) => ({ bytes: v.bytes, expected: v.expected }))];
const noise = Uint8Array.from({ length: 256 }, (_, i) => i);
let caughtByPrinted = 0;
let caughtByProbes = 0;
let caughtByFffd = 0;
let caughtByLegacySucceeded = 0;
for (const [name, corrupt] of corruptions) {
  const table = cloneTable();
  corrupt(table);
  const noticed = (set) => set.some((v) => validateUtf8(Uint8Array.from(v.bytes), table).valid !== v.expected);
  const fffdNoticed = FFFD_VECTORS.some((v) => {
    const out = substituteUtf8(Uint8Array.from(v.bytes), table).scalars;
    return out.length !== v.output.length || out.some((cp, i) => cp !== v.output[i]);
  });
  if (noticed(printedOnly)) caughtByPrinted += 1;
  if (noticed(printedAndProbes)) caughtByProbes += 1;
  if (fffdNoticed) caughtByFffd += 1;
  // The negative control: an assertion that the legacy reading decoded. windows-1252 is total, so
  // this is true under every corruption and under random noise. It is the check that cannot fail.
  if (!decodeSingle(noise, 'windows-1252').valid) caughtByLegacySucceeded += 1;
  check(noticed(printedAndProbes), `the anchor panel turns red under the corruption: ${name}`);
}
equal(caughtByPrinted, 2, 'the three printed vectors alone catch only two of the six corruptions, which is why the derived probes exist');
equal(caughtByProbes, 6, 'the printed vectors plus the ten derived probes catch all six corruptions');
equal(caughtByFffd, 6, 'comparing the U+FFFD output against the four printed tables also catches all six corruptions');
equal(caughtByLegacySucceeded, 0, 'the negative control catches zero of six: an assertion that the windows-1252 decoding succeeded cannot fail, because that table accepts all 256 byte values');

console.log('Fallback specimen');
const declared = Uint8Array.from([
  0x54, 0x68, 0x65, 0x79, 0x20, 0x70, 0x61, 0x69, 0x64, 0x20,
  0xe2, 0x82, 0xac, 0x39, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x63,
  0x61, 0x66, 0xc3, 0xa9, 0x2e, 0x0d, 0x0a,
]);
equal(fallbackBuffer.length, 27, 'fallback has exactly 27 bytes');
equal(FALLBACK_DECLARED_BYTES, fallbackBuffer.length, 'the fallback byte count the live check panel compares against is stated apart from the byte array and still agrees with the file');
check(pageJs.includes('FALLBACK_DECLARED_BYTES'), 'the page checks the fallback buffer against that declared count rather than against its own array length');
check(bytesEqual(fallbackBuffer, declared), 'fallback file equals its independent byte declaration');
check(bytesEqual(FALLBACK_BYTES, declared), 'browser fallback constant equals the independent declaration');
equal(sha(fallbackBuffer), 'fc276fcca5bc6b9a9531171119715f65b736d423a74eaac0c6ef26e9dc16b741', 'fallback SHA-256 is fixed');
const fallbackUtf8 = validateUtf8(fallbackBuffer);
check(fallbackUtf8.valid, 'fallback is well-formed UTF-8');
equal(fallbackUtf8.scalars.length, 24, 'fallback UTF-8 emits 24 Unicode scalars');
equal(fallbackUtf8.rowCounts, [22, 1, 0, 1, 0, 0, 0, 0, 0], 'fallback Table 3-7 row counts cover every scalar');
equal(scalarsToString(fallbackUtf8.scalars), 'They paid €9 for café.\r\n', 'fallback UTF-8 reading is exact');
const fallback1252 = decodeSingle(fallbackBuffer, 'windows-1252');
check(fallback1252.valid, 'fallback is a valid windows-1252 byte string');
equal(scalarsToString(fallback1252.scalars), 'They paid â‚¬9 for cafÃ©.\r\n', 'fallback windows-1252 reading is exact');
check(scalarsToString(fallback1252.scalars) !== scalarsToString(fallbackUtf8.scalars), 'fallback accepted readings are different');

console.log('Refusal paths');
const utf8Failures = [
  { bytes: [0x80], offset: 0, reason: 'unexpected continuation byte' },
  { bytes: [0xc0, 0xaf], offset: 0, reason: 'overlong lead byte' },
  { bytes: [0xf5, 0x80, 0x80, 0x80], offset: 0, reason: 'lead byte would exceed U+10FFFF' },
  { bytes: [0xc2], offset: 1, reason: 'missing continuation byte' },
  { bytes: [0xf1, 0x80, 0x80], offset: 3, reason: 'missing continuation byte' },
  { bytes: [0xe0, 0x9f, 0x80], offset: 1, reason: 'overlong three-byte sequence' },
  { bytes: [0xed, 0xa0, 0x80], offset: 1, reason: 'surrogate-range sequence' },
  { bytes: [0xf0, 0x8f, 0xbf, 0xbf], offset: 1, reason: 'overlong four-byte sequence' },
  { bytes: [0xf4, 0x90, 0x80, 0x80], offset: 1, reason: 'value above U+10FFFF' },
  { bytes: [0xe2, 0x28, 0xa1], offset: 1, reason: 'invalid continuation byte' },
];
for (const specimen of utf8Failures) {
  const result = validateUtf8(Uint8Array.from(specimen.bytes));
  check(!result.valid, `${specimen.reason} specimen refuses`);
  equal(result.offset, specimen.offset, `${specimen.reason} reports exact zero-based byte`);
  equal(result.oneBased, specimen.offset + 1, `${specimen.reason} reports exact one-based byte`);
  equal(result.reason, specimen.reason, `${specimen.reason} names the refusal class`);
}

const utf16Failures = [
  { bytes: [0x61], little: true, offset: 0, reason: 'odd byte count' },
  { bytes: [0x00, 0xdc], little: true, offset: 0, reason: 'isolated low surrogate' },
  { bytes: [0x00, 0xd8], little: true, offset: 0, reason: 'unpaired high surrogate' },
  { bytes: [0x00, 0xd8, 0x41, 0x00], little: true, offset: 2, reason: 'high surrogate not followed by low surrogate' },
  { bytes: [0xdc, 0x00], little: false, offset: 0, reason: 'isolated low surrogate' },
];
for (const specimen of utf16Failures) {
  const result = decodeUtf16(Uint8Array.from(specimen.bytes), specimen.little);
  check(!result.valid, `UTF-16 ${specimen.reason} refuses`);
  equal(result.offset, specimen.offset, `UTF-16 ${specimen.reason} exact byte offset`);
  equal(result.reason, specimen.reason, `UTF-16 ${specimen.reason} exact class`);
}

const utf32Failures = [
  { bytes: [0xff, 0xfe, 0x00, 0x00, 0x41], little: true, offset: 4, reason: 'length is not divisible by four' },
  { bytes: [0x00, 0xd8, 0x00, 0x00], little: true, offset: 0, reason: 'surrogate code point' },
  { bytes: [0x00, 0x00, 0x11, 0x00], little: true, offset: 0, reason: 'value above U+10FFFF' },
  { bytes: [0x00, 0x11, 0x00, 0x00], little: false, offset: 0, reason: 'value above U+10FFFF' },
];
for (const specimen of utf32Failures) {
  const result = decodeUtf32(Uint8Array.from(specimen.bytes), specimen.little);
  check(!result.valid, `UTF-32 ${specimen.reason} refuses`);
  equal(result.offset, specimen.offset, `UTF-32 ${specimen.reason} exact byte offset`);
  equal(result.reason, specimen.reason, `UTF-32 ${specimen.reason} exact class`);
}
const nullSingle = decodeSingle(Uint8Array.of(0xae), 'iso-8859-7');
check(!nullSingle.valid, 'single-byte null index entry refuses');
equal(nullSingle.offset, 0, 'single-byte null index reports exact byte offset');
equal(nullSingle.reason, 'undefined mapping', 'single-byte null index names refusal class');

console.log('BOM ordering and header-like input');
equal(detectBom(Uint8Array.from([0xff, 0xfe, 0x00, 0x00, 0x41, 0x00, 0x00, 0x00])).name, 'UTF-32LE', 'UTF-32LE signature wins over its UTF-16LE prefix');
equal(detectBom(Uint8Array.from([0x00, 0x00, 0xfe, 0xff])).name, 'UTF-32BE', 'UTF-32BE signature detected');
equal(detectBom(Uint8Array.from([0xef, 0xbb, 0xbf])).name, 'UTF-8', 'UTF-8 signature detected');
equal(detectBom(Uint8Array.from([0xfe, 0xff])).name, 'UTF-16BE', 'UTF-16BE signature detected');
equal(detectBom(Uint8Array.from([0xff, 0xfe])).name, 'UTF-16LE', 'UTF-16LE signature detected');
equal(detectBom(Uint8Array.from([0x00, 0x00, 0xfe, 0x00])), null, 'near-magic UTF-32 prefix is not mislabeled as a BOM');
const lyingHeader = decodeUtf32(Uint8Array.from([0xff, 0xfe, 0x00, 0x00, 0x41]), true);
equal(lyingHeader.offset, 4, 'BOM-like UTF-32 input with lying trailing length refuses at byte 4');
// A BOM is a convention, not a fact in the bytes. Measure how far it actually narrows the field.
const bomOnly = decodeAll(Uint8Array.from([0xef, 0xbb, 0xbf])).filter((r) => r.valid);
equal(bomOnly.length, 8, 'the UTF-8 BOM on its own is accepted by eight of the twelve candidates');
equal(new Set(bomOnly.map((r) => r.text)).size, 7, 'and yields seven distinct readings, so it selects nothing by itself');
check(html.includes("accepted by 8 of this page's 12 candidates and produce 7 distinct readings"), 'the page prints that measurement beside the BOM readout');

console.log('Candidate set and complete comparisons');
equal(Object.keys(SINGLE_BYTE_INDEXES).length, 7, 'seven WHATWG single-byte indexes ship');
for (const [name, index] of Object.entries(SINGLE_BYTE_INDEXES)) equal(index.length, 128, `${name} index has 128 pointers`);
equal(STRICT_CANDIDATES.length, 12, 'strict instrument has twelve named candidates');
equal(DETECTOR_CANDIDATES, [
  'UTF-8', 'UTF-16LE', 'UTF-16BE', 'UTF-32LE', 'UTF-32BE',
  'Shift_JIS', 'Big5', 'EUC-JP', 'EUC-KR', 'GB18030',
  'ISO-2022-JP', 'ISO-2022-KR', 'ISO-2022-CN',
  'ISO-8859-1 or windows-1252', 'ISO-8859-2 or windows-1250',
  'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7 or windows-1253',
  'ISO-8859-8 or windows-1255', 'ISO-8859-9 or windows-1254',
  'windows-1251', 'windows-1256', 'windows-1257', 'windows-1258',
  'windows-874', 'KOI8-R', 'ASCII',
], 'detector roster mirrors all twenty-seven recognizer objects in the vendored entry point');
check(html.includes('The scouting specification listed 30 labels and omitted those four recognizers.'), 'page discloses the corrected detector roster');
check(readme.includes('The binding specification\'s detector list was overruled'), 'research notes disclose why the detector roster overruled the specification');
const fallbackResults = decodeAll(fallbackBuffer);
equal(fallbackResults.filter((r) => r.valid).length, 8, 'fallback strictly decodes under eight candidates');
equal(fallbackResults.filter((r) => !r.valid).length, 4, 'fallback refuses under four Unicode width and byte-order candidates');
const fallbackPairs = compareReadings(fallbackResults);
equal(fallbackPairs.length, 66, 'twelve strict candidates produce sixty-six pair comparisons');
equal(fallbackPairs.filter((p) => p.kind === 'different').length, 28, 'fallback has twenty-eight pairs with distinct readings');
equal(fallbackPairs.filter((p) => p.kind === 'rejected').length, 38, 'fallback has thirty-eight pairs with at least one rejection');
const utf8vs1252 = fallbackPairs.find((p) => p.a === 'UTF-8' && p.b === 'windows-1252');
equal(utf8vs1252.scalarOffset, 10, 'UTF-8 and windows-1252 first differ at scalar 10');
equal(utf8vs1252.aSpan, [10, 13], 'UTF-8 divergence traces bytes 10 through 12');
equal(utf8vs1252.bSpan, [10, 11], 'windows-1252 divergence traces byte 10');
equal([utf8vs1252.aCp, utf8vs1252.bCp], [0x20ac, 0x00e2], 'divergent scalars are U+20AC and U+00E2');

const ascii = new TextEncoder().encode('same ASCII bytes');
const asciiReadings = [
  scalarsToString(validateUtf8(ascii).scalars),
  ...Object.keys(SINGLE_BYTE_INDEXES).map((id) => scalarsToString(decodeSingle(ascii, id).scalars)),
];
equal(asciiReadings.length, 8, 'ASCII witness enters eight ASCII-compatible candidates');
check(asciiReadings.every((text) => text === 'same ASCII bytes'), 'all eight ASCII witness readings are identical');

console.log('Mojibake byte certificate');
const chain = mojibakeChain(fallbackBuffer, 'windows-1252');
check(chain.ok, 'fallback windows-1252 mojibake chain is defined');
equal(chain.wrongText, 'They paid â‚¬9 for cafÃ©.\r\n', 'chain prints exact intermediate mojibake text');
equal(chain.repairedText, 'They paid €9 for café.\r\n', 'chain prints exact repaired UTF-8 text');
check(chain.intermediateEqual, 'single-byte re-encoding reconstructs original bytes');
check(chain.finalEqual, 'repaired UTF-8 re-encoding reconstructs original bytes');
equal(sha(chain.finalBytes), sha(fallbackBuffer), 'original and reconstructed SHA-256 match');
const undef = encodeSingle('🙂', 'windows-1252');
check(!undef.ok, 'undefined single-byte repair refuses instead of replacing');
equal(undef.cp, 0x1f642, 'undefined repair names the unencodable scalar');

console.log('Prefix history and detector');
equal(prefixLengths(27), [1, 2, 4, 8, 16, 27], '27-byte specimen uses powers of two plus full length');
equal(prefixLengths(16), [1, 2, 4, 8, 16], 'power-of-two full length is not duplicated');
equal(prefixLengths(1), [1], 'one-byte specimen has one full-length row');
equal(prefixLengths(0), [0], 'empty specimen has an explicit full-length row');
const detectorFull = chardet.analyse(fallbackBuffer);
check(Array.isArray(detectorFull) && detectorFull.length > 0, 'vendored chardet analyzes the complete fallback');
check(detectorFull.every((m, i, a) => i === 0 || a[i - 1].confidence >= m.confidence), 'detector ranking is sorted from high score to low score');
for (const n of prefixLengths(27)) check(Array.isArray(chardet.analyse(fallbackBuffer.subarray(0, n))), `detector runs on ${n}-byte diagnostic prefix`);

console.log('Published detector table arithmetic');
const fullTable = [
  ['utf-8', 60.2, 100.0, 56.9, 95.8, 54.6, 100.0, 68.5, 100.0, 54.2, 100.0, 63.0, 100.0],
  ['windows-1250', 32.2, 100.0, 0.3, null, 0.1, null, 0.2, null, 0.0, null, 0.1, null],
  ['windows-1252', 0.4, null, 9.4, 97.5, 6.5, 97.3, 3.1, 75.8, 7.1, 95.7, 7.0, 97.4],
  ['windows-1253', 0.0, null, 0.0, null, 0.0, null, 14.3, 99.3, 0.0, null, 0.0, null],
  ['iso-8859-1', 1.0, 89.5, 32.8, 90.9, 37.1, 85.8, 1.7, 71.2, 37.9, 85.1, 29.3, 88.2],
  ['iso-8859-2', 6.0, 99.6, 0.0, null, 0.1, null, 0.0, null, 0.1, null, 0.1, null],
  ['iso-8859-7', 0.0, null, 0.0, null, 0.0, null, 12.0, 97.2, 0.0, null, 0.0, null],
  ['iso-8859-15', 0.0, null, 0.0, null, 1.2, 85.6, 0.0, null, 0.0, null, 0.4, null],
];
for (const row of fullTable) {
  const cells = row.slice(1).map((value) => `<td>${value == null ? 'n/a' : value.toFixed(1) + '%'}</td>`).join('');
  check(html.includes(`<tr><td>${row[0]}</td>${cells}</tr>`), `complete Table 1 row ${row[0]} is transcribed exactly`);
}
check(html.includes('<tr><td>training docs</td><td colspan="2">801</td><td colspan="2">668</td><td colspan="2">773</td><td colspan="2">879</td><td colspan="2">771</td><td colspan="2">740</td></tr>'), 'complete Table 1 training-document row is exact');
check(html.includes('<tr><td>w. avg accuracy</td><td colspan="2">99.2%</td><td colspan="2">93.5%</td><td colspan="2">93.7%</td><td colspan="2">97.9%</td><td colspan="2">93.3%</td><td colspan="2">95.7%</td></tr>'), 'complete Table 1 weighted-average row is exact');
const paperRows = [
  ['Czech', 801, 99.2, 0.8],
  ['English', 668, 93.5, 6.5],
  ['German', 773, 93.7, 6.3],
  ['Greek', 879, 97.9, 2.1],
  ['Italian', 771, 93.3, 6.7],
  ['Norwegian', 740, 95.7, 4.3],
];
for (const [language, documents, accuracy, shownError] of paperRows) {
  equal(Number((100 - accuracy).toFixed(1)), shownError, `${language} error rate is 100 minus printed accuracy`);
  check(html.includes(`<td>${language}</td><td>${documents}</td><td>${accuracy.toFixed(1)}%</td><td>${shownError.toFixed(1)}%</td>`), `${language} visible table row is exact`);
}
for (const cell of ['71.2% for Greek', '85.1% for Italian', '85.8% for German']) check(html.includes(cell), `visible low cell ${cell} is present`);
for (const phrase of ['five-fold cross-validation', 'language already known', 'evaluation preliminary', 'did not compare against other systems']) check(html.includes(phrase), `paper limitation is visible: ${phrase}`);

console.log('Shareable surfaces and visible wording');
const expectedTitle = "How to Check a Text File's Encoding From Its Bytes";
const expectedDek = "Drop a text file and the browser reads every byte locally, reproduces Unicode 17.0's strict UTF-8 test, lists the distinct readings its finite set admits, and certifies reversible mojibake repairs byte for byte. A statistical favorite is shown separately because valid bytes cannot establish which encoding an author intended.";
const expectedPlain = "A file can be perfectly valid under more than one character encoding. This page checks your complete file without uploading it, shows every reading in its named set, and keeps a detector's guess separate from facts about the bytes.";
check(html.includes(`<title>${expectedTitle}</title>`), 'search title is exact and checked');
check(html.includes(`<meta name="description" content="${expectedDek}" />`), 'meta description is exact and checked');
check(html.includes(`"description":"${expectedDek}"`), 'JSON-LD description is exact and checked');
check(markdown.includes(`dek: "${expectedDek}"`), 'frontmatter dek matches checked meta claim');
check(markdown.includes(`plain: "${expectedPlain}"`), 'frontmatter plain matches checked instrument');
check(markdown.includes(`seoTitle: "${expectedTitle}"`), 'frontmatter SEO title matches checked page title');
check(html.includes(`content="${expectedPlain}"`), 'aw-plain meta matches checked frontmatter plain');
for (const surface of [
  'A statistical favorite is shown separately because valid bytes cannot establish which encoding an author intended.',
  'A standards validator reports what its bytes permit within a named set of 12 encodings; a separate heuristic guesses; a reversible repair earns one byte-equality certificate.',
  'shows which readings survive within its named 12-encoding set',
  "keeps a detector's guess separate from facts about the bytes",
]) check(html.includes(surface), `shareable concession is present: ${surface}`);
// The share card must not promise a certificate per branch. There is one certificate and it belongs
// to the repair chain, not to any candidate reading.
const ogAlt = html.match(/<meta property="og:image:alt" content="([^"]+)"/)[1];
check(!/each with a byte certificate/i.test(ogAlt) && !/certificate/i.test(ogAlt), `og:image:alt assigns no certificate to a candidate reading: ${ogAlt}`);
check(/intent unresolved/i.test(ogAlt), 'og:image:alt says the intent between the two readings is unresolved');
const ogDescription = html.match(/<meta property="og:description" content="([^"]+)"/)[1];
const twitterDescription = html.match(/<meta name="twitter:description" content="([^"]+)"/)[1];
for (const [label, text] of [['og:description', ogDescription], ['twitter:description', twitterDescription]]) {
  check(/12/.test(text), `${label} names the size of the finite candidate set instead of implying every encoding`);
}
check(!/detects? the (true|actual|intended) encoding/i.test(html + markdown), 'no shareable surface claims to detect true encoding');
check(!/encoding (is|was) undecidable/i.test(html + markdown), 'page does not mislabel underdetermination as undecidability');
check(html.includes('underdetermination, not undecidability'), 'the corrected finite-set framing is visible');

const jsonLdMatch = html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/);
check(Boolean(jsonLdMatch), 'JSON-LD block exists');
const jsonLd = JSON.parse(jsonLdMatch[1]);
equal(jsonLd['@type'], 'Article', 'JSON-LD type is Article');
equal(jsonLd.name, expectedTitle, 'JSON-LD name is search title');
equal(jsonLd.headline, 'The Encoding Your Text File Admits To', 'JSON-LD headline is poetic title');
equal(jsonLd.datePublished, '2026-08-09T00:00:00Z', 'JSON-LD published date is exact');
check(Boolean(jsonLd.author && jsonLd.publisher && jsonLd.url && jsonLd.image), 'JSON-LD required Article fields exist');

for (const phrase of [
  '3 of 3 published vectors, ${probes.length} of ${probes.length} derived boundary probes',
  '27-byte fallback',
  '1,200 scalars',
  'UTF-8 and all seven supported ASCII-compatible single-byte tables',
  'powers of two plus full length',
  "scores are opaque ranks, not probabilities",
  'No normalization is performed',
  "connect-src 'none'",
]) check(html.includes(phrase) || pageJs.includes(phrase) || readme.includes(phrase), `reader-facing numeric or methodological claim is checked: ${phrase}`);

console.log('Totality: which acceptance carries information');
const totality = totalityReport();
const everyByteValue = Uint8Array.from({ length: 256 }, (_, i) => i);
equal(totality.length, 7, 'the totality report covers all seven shipped single-byte tables');
equal(totality.filter((r) => r.total).map((r) => r.id), ['windows-1250', 'windows-1251', 'windows-1252', 'iso-8859-2', 'koi8-r'],
  'five shipped tables have an entry for all 256 byte values and therefore cannot refuse any file');
equal(totality.filter((r) => !r.total).map((r) => [r.id, r.undefinedBytes]), [['windows-1253', [0xd2, 0xff]], ['iso-8859-7', [0xae, 0xd2, 0xff]]],
  'only windows-1253 and ISO-8859-7 have undefined entries, at exactly these byte values');
for (const row of totality) equal(decodeSingle(everyByteValue, row.id).valid, row.total, `${row.id} decoding the all-256-byte probe matches its declared totality`);
check(decodeSingle(everyByteValue, 'windows-1252').valid, 'the all-256-byte probe decodes as windows-1252, so "these bytes are also valid windows-1252" is true of every file that exists');
check(html.includes('is a valid windows-1252 string'), 'the page states in prose that every byte string is a valid windows-1252 string');
check(html.includes('An assertion that cannot be false is not evidence'), 'the page names the vacuity rather than relying on the reader to spot it');
equal(VENDOR_CP1252_UNDEFINED, [0x81, 0x8d, 0x8f, 0x90, 0x9d], 'the Microsoft vendor cp1252 table leaves exactly five byte values undefined');
for (const byte of VENDOR_CP1252_UNDEFINED) check(SINGLE_BYTE_INDEXES['windows-1252'][byte - 0x80] != null, `the shipped WHATWG index defines ${byte.toString(16).toUpperCase()}, which the vendor table does not`);
check(html.includes('CP1252.TXT'), 'the page cites the vendor table whose disagreement decides whether windows-1252 is total');
// The vendor disagreement changes whether windows-1252 is total. It does not change this page's
// shipped demonstration, because none of those five byte values occurs in the fallback.
check(Array.from(fallbackBuffer).every((b) => !VENDOR_CP1252_UNDEFINED.includes(b)),
  'the fallback contains none of the five disputed byte values, so its windows-1252 reading holds under either published table');

console.log('Three specimens constructed after the page was built');
// Chosen at reconcile time, so no part of the instrument can have been tuned to them. One is a
// witness where both readings are ordinary letters, one is deliberately malformed, one is binary.
const witness = Uint8Array.from([0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0xc5, 0xa3, 0x21]);
const witnessResults = decodeAll(witness);
const witnessOf = (name) => witnessResults.find((r) => r.candidate.name === name);
check(witnessOf('UTF-8').valid, 'constructed witness is well-formed UTF-8');
equal(witnessOf('UTF-8').text, 'Hello, ţ!', 'constructed witness reads as a Romanian letter under UTF-8');
equal(witnessOf('koi8-r').text, 'Hello, её!', 'the same bytes read as an ordinary Russian word under KOI8-R');
check(witnessOf('UTF-8').text !== witnessOf('koi8-r').text, 'both readings are letters and they disagree, which is the form of the claim that survives a total encoding');
equal(compareReadings(witnessResults).find((p) => p.a === 'UTF-8' && p.b === 'koi8-r').scalarOffset, 7, 'the grid puts their first divergence at scalar 7');

const malformed = Uint8Array.from([0xff, 0xfe, 0x41, 0x00, 0x3d, 0xd8, 0x21]);
equal(detectBom(malformed).name, 'UTF-16LE', 'the malformed specimen carries a UTF-16LE signature');
const malformedResults = decodeAll(malformed);
const malformedOf = (name) => malformedResults.find((r) => r.candidate.name === name);
equal([malformedOf('UTF-8').valid, malformedOf('UTF-8').reason, malformedOf('UTF-8').offset], [false, 'byte value never used by any UTF-8 form', 0], 'malformed specimen refuses as UTF-8 at byte 0');
equal([malformedOf('UTF-16LE').valid, malformedOf('UTF-16LE').reason, malformedOf('UTF-16LE').offset], [false, 'odd byte count', 6], 'the signature promises UTF-16LE and the body refuses it at byte 6');
equal([malformedOf('UTF-32LE').valid, malformedOf('UTF-32LE').reason], [false, 'length is not divisible by four'], 'both UTF-32 candidates refuse the same specimen for a different reason');
equal([malformedOf('windows-1253').valid, malformedOf('windows-1253').reason], [false, 'undefined mapping'], 'a non-total single-byte table refuses the malformed specimen at its undefined entry');
check(malformedOf('windows-1252').valid, 'and a total table still accepts it, which is exactly why that acceptance is not evidence');
equal(substituteUtf8(malformed).replacements, 3, 'the malformed specimen costs three maximal-subpart replacements');

const binary = Uint8Array.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d]);
const binaryResults = decodeAll(binary);
const binaryOf = (name) => binaryResults.find((r) => r.candidate.name === name);
equal([binaryOf('UTF-8').valid, binaryOf('UTF-8').reason, binaryOf('UTF-8').offset], [false, 'unexpected continuation byte', 0], 'a PNG signature refuses as UTF-8 at byte 0');
equal([binaryOf('UTF-32BE').valid, binaryOf('UTF-32BE').reason, binaryOf('UTF-32BE').detail], [false, 'value above U+10FFFF', 'U+89504E47 occupies bytes 0..3'],
  'the same bytes read as UTF-32BE name the exact out-of-range value');
equal(binaryResults.filter((r) => r.valid).length, 9, 'nine of the twelve candidates accept a PNG header, which is the point about byte validity and text');
for (const specimen of [witness, malformed, binary]) {
  for (const result of decodeAll(specimen).filter((r) => r.valid)) {
    const tiling = spansTile(result.scalars, specimen.length);
    check(tiling.ok, `${result.candidate.name} spans tile the ${specimen.length}-byte constructed specimen: ${tiling.detail}`);
  }
  equal(substituteUtf8(specimen).replacements, codePointsOf(lenient.decode(specimen)).filter((cp) => cp === 0xfffd).length,
    `local and browser replacement counts agree on the ${specimen.length}-byte constructed specimen`);
}

console.log('Empty specimen, where the certificates would otherwise be vacuous');
const empty = new Uint8Array(0);
equal(decodeAll(empty).filter((r) => r.valid).length, 12, 'a zero-byte file is accepted by all twelve candidates, so no candidate is distinguished');
equal(compareReadings(decodeAll(empty)).filter((p) => p.kind === 'same').length, 66, 'and all 66 pairs report as identical, which is a statement about nothing');
const emptyChain = mojibakeChain(empty, 'windows-1252');
check(emptyChain.ok && emptyChain.finalEqual, 'the engine chain over zero bytes is trivially byte-equal, which is why the page must refuse to certify it');
check(pageJs.includes('there are no bytes to distinguish or to repair'), 'the page refuses to issue a certificate over an empty specimen');
check(pageJs.includes('VACUOUS'), 'the page labels the empty equivalence grid vacuous rather than reporting perfect agreement');
check(html.includes('A zero-byte specimen is accepted by every candidate'), 'the empty-specimen behaviour is disclosed among the free choices');

console.log('Measured size ceiling');
equal(MAX_BYTES, 262144, 'the ceiling is 262,144 bytes');
check(pageJs.includes('file.size > MAX_BYTES'), 'the ceiling is enforced against File.size before any byte is read');
check(pageJs.indexOf('file.size > MAX_BYTES') < pageJs.indexOf('await file.arrayBuffer()'), 'and the size gate stands before the arrayBuffer call, not after it');
check(html.includes('262,144 bytes'), 'the ceiling is printed for the reader in the byte count it is enforced in');
check(html.includes('added after measurement rather than designed in'), 'the page discloses that this rule was added after seeing measurements, not designed in advance');
for (const measurement of ['109 MB and 263 ms', '349 MB and 1,029 ms', '2,510 MB and 7,686 ms', '16,777,216 bytes crashed the renderer']) {
  check(html.includes(measurement), `the measurement behind the ceiling is printed: ${measurement}`);
}

console.log('Detector roster derived from the vendored source');
const chardetSource = await readFile(join(publicDir, 'chardet-2.2.0.mjs'), 'utf8');
const rosterBlock = chardetSource.match(/var recognisers = \[([\s\S]*?)\];/);
check(Boolean(rosterBlock), 'the vendored entry point still constructs its recognizers in one array');
const constructed = Array.from(rosterBlock[1].matchAll(/new\s+([A-Za-z0-9_.]+)\s*\(/g)).map((m) => m[1]);
equal(constructed.length, 27, 'the vendored source constructs exactly twenty-seven recognizer objects');
// sjis is the only constructor whose identifier is not the label chardet reports for it.
const canonical = (name) => name.replace(/^.*\./, '').replace(/_?default$/, '').replace(/[^A-Za-z0-9]/g, '').toUpperCase() || name.split('.')[0].replace(/_\d+$/, '').toUpperCase();
const constructorNames = new Set(constructed.map((name) => {
  const tail = name.split('.').pop();
  const base = tail === 'default' ? name.split('.')[0].replace(/_\d+$/, '') : tail;
  return canonical(base) === 'SJIS' ? 'SHIFTJIS' : canonical(base);
}));
const rosterNames = new Set(DETECTOR_CANDIDATES.map((label) => canonical(label.split(' or ')[0])));
equal([...rosterNames].sort(), [...constructorNames].sort(), 'the printed roster is the set of recognizers the vendored source actually constructs');

console.log('Privacy, structure and drift guards');
const csp = html.match(/<meta http-equiv="Content-Security-Policy" content="([^"]+)"/);
check(Boolean(csp), 'inline Content Security Policy exists');
for (const directive of ["default-src 'self'", "connect-src 'none'", "media-src 'none'", "object-src 'none'", "frame-src 'none'", "worker-src 'none'", "form-action 'none'", "base-uri 'none'"]) check(csp[1].includes(directive), `CSP contains ${directive}`);
check(!/\b(fetch|XMLHttpRequest|WebSocket|sendBeacon)\s*\(/.test(pageJs), 'instrument code has no network-sending call');
check(!/localStorage|sessionStorage|indexedDB/.test(pageJs), 'instrument code has no storage call');
for (const match of html.matchAll(/<(script|img)[^>]+src="([^"]+)"/g)) check(match[2].startsWith('/') || match[2].startsWith('./'), `runtime ${match[1]} source is same-origin: ${match[2]}`);
for (const match of html.matchAll(/<link[^>]+rel="stylesheet"[^>]+href="([^"]+)"/g)) check(match[1].startsWith('/'), `stylesheet is same-origin: ${match[1]}`);
check(pageJs.includes("new PerformanceObserver"), 'Resource Timing observer is implemented');
check(html.includes('Open your browser\'s Network panel'), 'independent browser Network panel check is invited');
check(html.endsWith('</html>\n'), 'load-bearing HTML closing tag exists');
check(html.includes('<script type="module" src="./page.js"></script>\n</body>\n</html>'), 'module, body and HTML close in load-bearing order');
check(html.includes('@media (prefers-reduced-motion:reduce)'), 'reduced-motion preference is respected');
check(html.includes(':focus-visible'), 'visible keyboard focus style exists');
check(html.includes('role="status"') && html.includes('aria-live="polite"'), 'live readouts expose accessible status semantics');
// These two are drift guards on the stylesheet, not evidence about layout. Hiding overflow can also
// conceal it, so the actual document width is measured in a real browser further down.
check(html.includes('overflow-x:hidden'), 'stylesheet still declares the body overflow guard (drift guard, not a layout measurement)');
check(html.includes('overflow-x:auto'), 'stylesheet still declares scroll wrappers for wide tables (drift guard, not a layout measurement)');

const allowedFiles = [];
async function walk(dir) {
  for (const entry of await readdir(dir, { withFileTypes: true })) {
    const path = join(dir, entry.name);
    if (entry.isDirectory()) await walk(path);
    else allowedFiles.push(path);
  }
}
await walk(publicDir);
await walk(here);
allowedFiles.push(markdownPath);
for (const path of allowedFiles) {
  const bytes = await readFile(path);
  check(!bytes.toString('utf8').includes(String.fromCodePoint(0x2014)), `${path.slice(root.length + 1)} contains no em dash`);
}
check(license.includes('Copyright (C) 2024 Dmitry Shirokov'), 'vendored chardet MIT copyright is retained');
check(license.includes('Permission is hereby granted, free of charge'), 'vendored chardet MIT permission is retained');
check(readme.includes('undertermined') === false, 'research wording contains no misspelled central framing');

console.log('Live browser pass: visible refusals, real layout, and the repair race');

// The rendered sequences whose order this page asserts, derived here rather than read off the
// screen: the analyser's own ranking of the shipped fallback, the three vectors in the order the
// standard prints them, and the four U+FFFD tables in their published numbering.
const expectedDetectorNames = detectorFull.map((match) => match.name);
const expectedDetectorScores = detectorFull.map((match) => Number(match.confidence).toFixed(1));
const expectedAnchorLabels = UTF8_VECTORS.map((vector) => vector.label);
const expectedFffdTables = FFFD_VECTORS.map((vector) => vector.table);

function contentType(pathname) {
  return ({ '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.png': 'image/png', '.woff2': 'font/woff2', '.txt': 'text/plain; charset=utf-8' })[extname(pathname)] || 'application/octet-stream';
}

async function browserPass() {
  const publicRoot = resolve(root, 'public');
  const server = createServer(async (request, response) => {
    try {
      const url = new URL(request.url, 'http://localhost');
      let pathname = decodeURIComponent(url.pathname);
      if (pathname.endsWith('/')) pathname += 'index.html';
      const target = resolve(publicRoot, `.${pathname}`);
      if (!(target === publicRoot || target.startsWith(publicRoot + sep))) throw new Error('outside public');
      const body = await readFile(target);
      response.writeHead(200, { 'content-type': contentType(target), 'cache-control': 'no-store' });
      response.end(body);
    } catch {
      response.writeHead(404);
      response.end('not found');
    }
  });
  await new Promise((listening) => server.listen(0, '127.0.0.1', listening));
  const port = server.address().port;
  const browser = await chromium.launch({ headless: true });
  try {
    for (const width of [390, 768, 1440]) {
      const page = await browser.newPage({ viewport: { width, height: 900 } });
      const pageErrors = [];
      const requests = [];
      page.on('pageerror', (error) => pageErrors.push(error.message));
      page.on('console', (message) => { if (message.type() === 'error') pageErrors.push(message.text()); });
      page.on('request', (request) => requests.push(request.url()));
      const response = await page.goto(`http://127.0.0.1:${port}/strata/the-encoding-your-text-file-admits-to/`, { waitUntil: 'load' });
      equal(response.status(), 200, `${width}px page responds 200`);
      await page.waitForFunction(() => document.documentElement.dataset.ready === 'true', null, { timeout: 30000 });
      const initial = await page.evaluate(() => ({
        anchor: document.querySelector('#anchor-status').textContent,
        score: document.querySelector('#check-score').textContent,
        failing: window.__encodingInstrument.state.checks.filter((c) => !c.pass).map((c) => c.text),
        total: window.__encodingInstrument.state.checks.length,
        scroll: document.documentElement.scrollWidth,
        viewport: window.innerWidth,
        cert: document.querySelector('#mojibake-cert').textContent,
        totality: document.querySelector('#totality-summary').textContent,
      }));
      equal(initial.failing, [], `${width}px live check panel has no failing line`);
      check(initial.total >= 40, `${width}px live check panel runs ${initial.total} lines`);
      equal(initial.score, `${initial.total} of ${initial.total} live checks pass.`, `${width}px printed score equals the panel it summarizes`);
      check(initial.anchor.startsWith('3 of 3 published vectors, 10 of 10 derived boundary probes and 4 of 4 printed U+FFFD tables'), `${width}px anchor line reports all three anchor families: ${initial.anchor.slice(0, 60)}`);
      check(initial.cert.startsWith('BYTE-EQUALITY CERTIFICATE'), `${width}px shipped fallback earns its byte-equality certificate`);
      check(initial.totality.startsWith('5 of 7 shipped single-byte tables are total'), `${width}px page tells the reader which acceptances cannot fail`);
      // Measured, not inferred from a stylesheet declaration.
      check(initial.scroll <= initial.viewport, `${width}px document width ${initial.scroll} does not exceed the ${initial.viewport}px viewport`);
      equal(pageErrors, [], `${width}px page raises no script error`);
      check(requests.every((url) => new URL(url).origin === `http://127.0.0.1:${port}`), `${width}px page requests nothing off-origin`);

      // ARRANGEMENT IS A CLAIM. A ranking says nothing with its values that it does not also say
      // with their sequence: reverse the rows of the detector table and every score is still the
      // score the analyser computed, still beside its own candidate name, and the page is now
      // telling the reader that ASCII is the favorite. An assertion of the form "windows-1252
      // appears with score 81.0" passes on that upside-down page, so a value assertion cannot see
      // a reversed list and no number of them adds up to one that can. These read the rendered DOM
      // in document order and assert the sequence itself: the visible rank column, the direction
      // the ordering column moves, and the identity of the first and last row, each compared
      // against an expectation derived above from the same analyser and the same published tables
      // the page renders from.
      const rendered = await page.evaluate(() => {
        const rowsOf = (id) => Array.from(document.querySelectorAll(`#${id} > tr`))
          .map((tr) => Array.from(tr.children).map((cell) => cell.textContent.trim()));
        return { detector: rowsOf('detector-body'), anchor: rowsOf('anchor-body'), fffd: rowsOf('fffd-body') };
      });

      equal(rendered.detector.length, expectedDetectorNames.length, `${width}px the rendered ranking has one row per analyser result`);
      equal(rendered.detector.map((cells) => cells[0]), rendered.detector.map((_, i) => String(i + 1)),
        `${width}px the visible rank column counts 1 to ${expectedDetectorNames.length} down the page, in document order`);
      const renderedScores = rendered.detector.map((cells) => Number(cells[2]));
      check(renderedScores.every((score, i) => i === 0 || renderedScores[i - 1] >= score),
        `${width}px the visible opaque scores never rise from one row to the next: ${renderedScores.join(' >= ')}`);
      equal(rendered.detector.map((cells) => cells[1]), expectedDetectorNames,
        `${width}px the candidate column reads top to bottom in the order the vendored analyser ranked them`);
      equal(rendered.detector.map((cells) => cells[2]), expectedDetectorScores,
        `${width}px and the score column reads down the page in that same ranked order`);
      equal([rendered.detector[0][1], rendered.detector[rendered.detector.length - 1][1]],
        [expectedDetectorNames[0], expectedDetectorNames[expectedDetectorNames.length - 1]],
        `${width}px the first rendered row is ${expectedDetectorNames[0]} and the last is ${expectedDetectorNames[expectedDetectorNames.length - 1]}, which is where the ranking put them`);
      check(expectedDetectorNames.join('|') !== [...expectedDetectorNames].reverse().join('|'),
        `${width}px the ranking is not its own reverse, so asserting its order is a falsifiable assertion rather than a vacuous one`);

      equal(rendered.anchor.map((cells) => cells[0]), expectedAnchorLabels,
        `${width}px the three published vectors are rendered in the order the standard prints them`);
      const anchorWidths = rendered.anchor.map((cells) => cells[0].split(' ').length);
      check(anchorWidths.every((count, i) => i === 0 || anchorWidths[i - 1] < count),
        `${width}px the printed-vector rows grow strictly in byte width down the page: ${anchorWidths.join(' < ')}`);
      equal([rendered.anchor[0][0], rendered.anchor[rendered.anchor.length - 1][0]],
        [expectedAnchorLabels[0], expectedAnchorLabels[expectedAnchorLabels.length - 1]],
        `${width}px the anchor table opens on ${expectedAnchorLabels[0]} and closes on ${expectedAnchorLabels[expectedAnchorLabels.length - 1]}`);

      equal(rendered.fffd.map((cells) => cells[0]), expectedFffdTables,
        `${width}px the four printed U+FFFD tables are rendered in their published numbering`);
      const fffdNumbers = rendered.fffd.map((cells) => Number(cells[0].replace('Table 3-', '')));
      check(fffdNumbers.every((number, i) => i === 0 || fffdNumbers[i - 1] < number),
        `${width}px the printed table numbers rise strictly down the page: ${fffdNumbers.join(' < ')}`);

      if (width === 768) {
        const status = () => page.textContent('#file-status');

        // Over the ceiling: refused before a byte is read, and it names both numbers.
        await page.setInputFiles('#file-picker', { name: 'too-big.log', mimeType: 'text/plain', buffer: Buffer.alloc(MAX_BYTES + 1, 0x41) });
        await page.waitForFunction(() => document.querySelector('#file-status').textContent.startsWith('Refused'), null, { timeout: 20000 });
        const oversize = await status();
        check(oversize.includes('262,145 bytes offered') && oversize.includes('262,144 bytes is the ceiling'), `over-limit refusal names the file size and the limit: ${oversize.slice(0, 110)}`);
        const oversizeBody = await page.textContent('#refusal-box');
        check(oversizeBody.includes('The refusal is the result') && oversizeBody.includes('Nothing was read'), 'the over-limit refusal is the visible result and says nothing was read');
        equal(await page.evaluate(() => window.__encodingInstrument.state.bytes), null, 'no byte array survives an over-limit refusal');
        equal(await page.evaluate(() => document.querySelector('#results').hidden), true, 'the previous specimen panels are hidden behind the refusal rather than left standing');
        // A refusal must not disable the instrument. Everything the painters look up by id has to
        // survive it, which an earlier version of this page did not manage.
        equal(await page.evaluate(() => Boolean(document.querySelector('#byte-count') && document.querySelector('#check-list') && document.querySelector('#mojibake-cert'))), true,
          'the result panels still exist in the document after a refusal, so the next file can be analyzed');

        // Exactly at the ceiling: accepted and analyzed in full.
        await page.setInputFiles('#file-picker', { name: 'exactly-at-the-ceiling.txt', mimeType: 'text/plain', buffer: Buffer.alloc(MAX_BYTES, 0x41) });
        await page.waitForFunction(() => document.querySelector('#file-status').textContent.includes('bytes read and analyzed in full'), null, { timeout: 60000 });
        const boundary = await page.evaluate(() => ({
          count: document.querySelector('#byte-count').textContent,
          failing: window.__encodingInstrument.state.checks.filter((c) => !c.pass).map((c) => c.text),
          declared: window.__encodingInstrument.state.declaredSize,
        }));
        equal(boundary.count, '262,144', 'the boundary specimen is analyzed in full at exactly the ceiling');
        equal(boundary.declared, MAX_BYTES, 'and the buffer length is checked against the size the File object reported');
        equal(boundary.failing, [], 'the boundary specimen leaves no failing check');

        // Empty: accepted by everything, therefore certified by nothing.
        await page.setInputFiles('#file-picker', { name: 'empty.txt', mimeType: 'text/plain', buffer: Buffer.alloc(0) });
        await page.waitForFunction(() => document.querySelector('#file-status').textContent.includes('zero bytes read'), null, { timeout: 20000 });
        const emptyView = await page.evaluate(() => ({
          verdict: document.querySelector('#utf8-verdict').textContent,
          summary: document.querySelector('#equivalence-summary').textContent,
          cert: document.querySelector('#mojibake-cert').textContent,
          failing: window.__encodingInstrument.state.checks.filter((c) => !c.pass).map((c) => c.text),
        }));
        check(emptyView.verdict.startsWith('EMPTY SPECIMEN'), `the empty file gets its own verdict rather than a green well-formed banner: ${emptyView.verdict.slice(0, 60)}`);
        check(emptyView.summary.startsWith('VACUOUS'), 'the empty equivalence grid is labelled vacuous rather than reporting 66 agreements');
        check(!emptyView.cert.includes('BYTE-EQUALITY CERTIFICATE') && emptyView.cert.includes('true by construction'), `no certificate is issued over zero bytes: ${emptyView.cert.slice(0, 80)}`);
        equal(emptyView.failing, [], 'the empty specimen still leaves no failing check');

        // Malformed, and then the repair race on the same specimen.
        await page.setInputFiles('#file-picker', { name: 'malformed.bin', mimeType: 'application/octet-stream', buffer: Buffer.from([0xff, 0xfe, 0x41, 0x00, 0x3d, 0xd8, 0x21]) });
        await page.waitForFunction(() => document.querySelector('#file-status').textContent.includes('7 bytes read'), null, { timeout: 20000 });
        const malformedView = await page.evaluate(() => ({
          verdict: document.querySelector('#utf8-verdict').textContent,
          bom: document.querySelector('#bom-name').textContent,
          candidates: document.querySelector('#candidate-list').textContent,
          failing: window.__encodingInstrument.state.checks.filter((c) => !c.pass).map((c) => c.text),
        }));
        check(malformedView.verdict.includes('ILL-FORMED UTF-8') && malformedView.verdict.includes('zero-based byte 0'), `the malformed specimen prints an ill-formed verdict at an exact byte: ${malformedView.verdict.slice(0, 80)}`);
        equal(malformedView.bom, 'UTF-16LE', 'and its BOM signature is still reported, unstripped');
        check(malformedView.candidates.includes('odd byte count at zero-based byte 6'), 'the UTF-16LE candidate card shows the exact refusal the signature invited');
        check(malformedView.candidates.includes('FF has a null entry in the windows-1253 index'), 'a non-total single-byte table shows its undefined-mapping refusal');
        equal(malformedView.failing, [], 'the malformed specimen leaves no failing check');

        // Finding 3 of the audit, as a regression test. The specimen matters: 41 D2 80 42 is
        // well-formed UTF-8, makes a complete reversible chain through windows-1252, and refuses
        // immediately under windows-1253 because D2 has no entry there. So the windows-1252 painter
        // reaches its two hash awaits while the windows-1253 painter finishes synchronously. Fire
        // both in one tick, newest last, and require the newest to be the one still standing.
        await page.setInputFiles('#file-picker', { name: 'divergent.txt', mimeType: 'text/plain', buffer: Buffer.from([0x41, 0xd2, 0x80, 0x42]) });
        await page.waitForFunction(() => document.querySelector('#file-status').textContent.includes('4 bytes read'), null, { timeout: 20000 });
        check((await page.textContent('#mojibake-cert')).startsWith('BYTE-EQUALITY CERTIFICATE'), 'the race specimen does earn a certificate under windows-1252, so the slow path is really taken');
        await page.evaluate(() => {
          const select = document.getElementById('mojibake-label');
          select.value = 'windows-1252';
          select.dispatchEvent(new Event('change'));
          select.value = 'windows-1253';
          select.dispatchEvent(new Event('change'));
        });
        await page.waitForTimeout(400);
        const raced = await page.evaluate(() => ({
          selected: document.getElementById('mojibake-label').value,
          cert: document.querySelector('#mojibake-cert').textContent,
          steps: document.querySelector('#mojibake-steps').textContent,
        }));
        equal(raced.selected, 'windows-1253', 'the selected table after the race is windows-1253');
        check(raced.cert.startsWith('No byte certificate'), `a slower earlier repair does not overwrite the newer refusal: ${raced.cert.slice(0, 70)}`);
        check(raced.steps.includes('D2 has a null entry in the windows-1253 index'), 'and the printed chain is the one belonging to the selected table');

        // The witness both readings are real text, selected as a file rather than constructed inline.
        await page.setInputFiles('#file-picker', { name: 'witness.txt', mimeType: 'text/plain', buffer: Buffer.from([0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0xc5, 0xa3, 0x21]) });
        await page.waitForFunction(() => document.querySelector('#file-status').textContent.includes('10 bytes read'), null, { timeout: 20000 });
        const witnessView = await page.evaluate(() => ({
          candidates: document.querySelector('#candidate-list').textContent,
          failing: window.__encodingInstrument.state.checks.filter((c) => !c.pass).map((c) => c.text),
          resources: document.querySelector('#privacy-count').textContent,
        }));
        check(witnessView.candidates.includes('Hello, ţ!') && witnessView.candidates.includes('Hello, её!'), 'both surviving readings are rendered, and both are ordinary letters');
        equal(witnessView.failing, [], 'the witness specimen leaves no failing check');
        equal(witnessView.resources, '0', 'no resource request begins while five files are analyzed in turn');
        check(requests.every((url) => new URL(url).origin === `http://127.0.0.1:${port}`), 'no file selection produced an off-origin request');
      }
      await page.close();
    }
  } finally {
    await browser.close();
    server.close();
  }
}

await browserPass();

console.log(`\n${checks} checks passed.`);
