import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import zlib from 'node:zlib';
import {execFileSync} from 'node:child_process';
import {fileURLToPath} from 'node:url';
import {
  anchorVerdict, assertSizeBeforeRead, bestOfSet, breakEvenBytes, bytesEqual,
  crc32, DECODER_SOURCE_BYTES, decodeArithmetic, empiricalH0, encodeArithmetic,
  inspectGzip, inverseTransform, MAX_BYTES, matrixDegeneracy, metrics,
  parseArithmeticFrame, parseGzip, parseTransformPrefix, prefixTransform,
  readAcceptedFile, RESCALE_AT, sha256, transformBytes, TRANSFORMS,
  TRANSFORM_PREFIX_BYTES
} from '../../public/strata/the-part-of-your-file-that-will-not-shrink/codec.mjs';
import {analyze, matrix as runMatrix} from '../../public/strata/the-part-of-your-file-that-will-not-shrink/worker.mjs';

const here = path.dirname(fileURLToPath(import.meta.url));
const publicDir = path.resolve(here, '../../public/strata/the-part-of-your-file-that-will-not-shrink');
const contentPath = path.resolve(here, '../../src/content/strata/the-part-of-your-file-that-will-not-shrink.md');
const siteDir = path.resolve(here, '../../public');
const htmlPath = path.join(publicDir, 'index.html');
const codecPath = path.join(publicDir, 'codec.mjs');
const alicePath = path.join(publicDir, 'alice29.txt');
const html = fs.readFileSync(htmlPath, 'utf8');
const pageSource = fs.readFileSync(path.join(publicDir, 'page.mjs'), 'utf8');
const renderedSurface = `${html}\n${pageSource}`;
const frontmatter = fs.readFileSync(contentPath, 'utf8');
const alice = new Uint8Array(fs.readFileSync(alicePath));
const checks = [];
const skipped = [];

function check(name, fn) {
  try { fn(); checks.push({name, ok:true}); }
  catch (error) { checks.push({name, ok:false, error}); }
}

async function checkAsync(name, fn) {
  try { await fn(); checks.push({name, ok:true}); }
  catch (error) { checks.push({name, ok:false, error}); }
}

const coveredCodes = new Set();

function expectCode(name, code, fn) {
  check(name, () => {
    let caught = null;
    try { fn(); } catch (error) { caught = error; }
    assert(caught, 'broken input was accepted');
    assert.equal(caught.code, code, caught.message);
    assert.match(caught.message, /byte [0-9]+/);
    coveredCodes.add(code);
  });
}

/*
  Published figures. The two gzip rows are the point: the 1997 paper and the
  corpus website print different bits per character for the same 152,089 bytes.
  The GNU gzip byte counts are recorded measurements from gzip 1.12, disclosed
  as measurements. Their arithmetic is checked here, and the phenomenon they
  illustrate is reproduced live below with Node zlib alone.
*/
const published = {
  bytes:152089,
  paperGzipBpc:2.86,
  siteGzipBpc:2.85,
  ppmcBpc:2.30,
  calibrationBytes:54416,
  gnuDefaultNoName:54423,
  gnuBestNoName:54179,
  gnuDefaultWithName:54435,
  gnuBestWithName:54191
};

check('published gzip calibration recomputes to 2.8623240339538034 and rounds to 2.86', () => {
  const bpc = 8 * published.calibrationBytes / published.bytes;
  assert.equal(bpc, 2.8623240339538034);
  assert.equal(Math.round(bpc * 100) / 100, published.paperGzipBpc);
});

check('the paper figure and the corpus website figure are different numbers for the same bytes', () => {
  assert.notEqual(published.paperGzipBpc, published.siteGzipBpc);
  assert.equal(Math.round(8 * published.gnuDefaultNoName / published.bytes * 100) / 100, published.paperGzipBpc);
  assert.equal(Math.round(8 * published.gnuBestNoName / published.bytes * 100) / 100, published.siteGzipBpc);
  assert(renderedSurface.includes('2.85'), 'the page must print the second published figure');
  assert.match(html, /gzip-b/);
});

check('the 12-byte RFC 1952 FNAME does not move either printed figure on this file, and would on a small one', () => {
  const named = size => Math.round(8 * (size + 12) / published.bytes * 100) / 100;
  assert.equal(named(published.gnuDefaultNoName), published.paperGzipBpc);
  assert.equal(named(published.gnuBestNoName), published.siteGzipBpc);
  assert.equal(published.gnuDefaultWithName - published.gnuDefaultNoName, 12, 'alice29.txt is 11 characters plus a zero terminator');
  assert.equal(published.gnuBestWithName - published.gnuBestNoName, 12);
  assert(96 / 3721 > 0.005, 'the same 96 bits exceed a two-decimal rounding step on a few-kilobyte file');
  assert(html.includes('add 12 bytes, which is 96 bits'));
});

check('one library, one file, four levels, four different two-decimal figures', () => {
  const seen = new Map();
  for (const level of [1, 3, 6, 9]) {
    const gz = new Uint8Array(zlib.gzipSync(alice, {level}));
    assert(bytesEqual(new Uint8Array(zlib.gunzipSync(gz)), alice), `level ${level} did not round trip`);
    seen.set(level, Math.round(800 * gz.length / alice.length) / 100);
  }
  const distinct = new Set(seen.values());
  assert.equal(distinct.size, 4, `expected four distinct rates, saw ${[...seen.entries()].join(' ')}`);
  assert.deepEqual([...seen.values()], [3.26, 3.07, 2.85, 2.84]);
});

check('the shipped order 1 rate is nowhere near the historical PPMC figure and is never labelled PPMC', () => {
  const order1 = encodeArithmetic(alice, 1);
  const bpc = 8 * order1.frame.length / alice.length;
  assert(Math.abs(bpc - published.ppmcBpc) > 1, `order 1 is ${bpc}, PPMC is ${published.ppmcBpc}`);
  assert.match(renderedSurface, /separate historical PPMC program/);
  assert.doesNotMatch(renderedSurface, /adaptive order 1 PPMC|PPMC adaptive order 1/);
  assert.doesNotMatch(renderedSurface, /reproduc[a-z]* (?:the )?(?:paper's )?PPMC/i);
});

check('Alice exact byte count', () => assert.equal(alice.length, published.bytes));
check('Alice pinned SHA-256 through independent Node crypto', () => assert.equal(crypto.createHash('sha256').update(alice).digest('hex'), '7467306ee0feed4971260f3c87421154a05be571d944e9cb021a5713700c38f0'));
check('browser-loaded Alice data is exactly the pinned file', () => {
  const source = fs.readFileSync(path.join(publicDir, 'alice-data.js'), 'utf8');
  const match = source.match(/^window\.__ALICE_B64__="([A-Za-z0-9+/=]+)";\n$/);
  assert(match);
  assert(bytesEqual(new Uint8Array(Buffer.from(match[1], 'base64')), alice));
});
check('page SHA-256 implementation agrees with Node crypto', () => assert.equal(sha256(alice), crypto.createHash('sha256').update(alice).digest('hex')));
check('CRC-32 standard check vector', () => assert.equal(crc32(new TextEncoder().encode('123456789')), 0xcbf43926));

/*
  The counting bound. This is the one incompressibility statement that can be
  proved, it is about the population and not about any named file, and both
  readings of it are pinned here because they are easy to blur.
*/
check('pigeonhole: strictly shorter outputs are under 1/255 of the inputs, exactly', () => {
  for (const n of [1, 2, 3, 8, 64]) {
    const inputs = 256n ** BigInt(n);
    const shorter = (inputs - 1n) / 255n;
    assert(shorter * 255n < inputs, `n=${n}`);
    assert(shorter * 255n + 255n >= inputs, `n=${n} bound is not tight`);
  }
  assert.equal(1 / 255, 0.00392156862745098);
  assert.equal(2 ** -8, 0.00390625);
  assert.equal(2 ** -7, 0.0078125);
  assert(html.includes('0.392157%') && html.includes('0.390625%') && html.includes('0.78125%'));
});

check('exhaustively: no 1-byte or 2-byte input gets shorter or equal under raw deflate', () => {
  let shorter = 0, equal = 0, inputs = 0;
  for (let a = 0; a < 256; a += 1) {
    const one = zlib.deflateRawSync(Buffer.from([a]), {level:9});
    inputs += 1;
    if (one.length < 1) shorter += 1;
    if (one.length === 1) equal += 1;
    for (let b = 0; b < 256; b += 1) {
      const two = zlib.deflateRawSync(Buffer.from([a, b]), {level:9});
      inputs += 1;
      if (two.length < 2) shorter += 1;
      if (two.length === 2) equal += 1;
    }
  }
  assert.equal(inputs, 65792);
  assert.equal(shorter, 0);
  assert.equal(equal, 0);
});

function seededBytes(length, seed = 0x12345678) {
  const out = new Uint8Array(length);
  let state = seed >>> 0;
  for (let i = 0; i < length; i += 1) {
    state ^= state << 13; state ^= state >>> 17; state ^= state << 5;
    out[i] = state & 255;
  }
  return out;
}

const allSymbols = new Uint8Array(256);
for (let i = 0; i < 256; i += 1) allSymbols[i] = i;
const repeated = new Uint8Array(100000); repeated.fill(97);
const fixtures = [
  ['empty', new Uint8Array(0)],
  ['one byte', new Uint8Array([173])],
  ['all 256 byte values', allSymbols],
  ['100000 repeated a bytes', repeated],
  ['fixed seeded pseudorandom bytes', seededBytes(65536)],
  ['exact Alice fallback', alice]
];

const shippedFigures = {};
for (const [label, bytes] of fixtures) {
  for (const order of [0, 1]) {
    check(`${label}: adaptive order ${order} frame decodes byte for byte`, () => {
      const encoded = encodeArithmetic(bytes, order);
      const parsed = parseArithmeticFrame(encoded.frame);
      const decoded = decodeArithmetic(encoded.frame);
      assert(bytesEqual(decoded.bytes, bytes));
      assert.equal(parsed.originalLength, bytes.length);
      assert.equal(parsed.order, order);
      assert.equal(parsed.expectedCrc, crc32(bytes));
      assert.equal(encoded.frame.length, 26 + Math.ceil(encoded.bitLength / 8));
      assert.equal(encoded.paddingBits, encoded.payloadBytes * 8 - encoded.bitLength);
      if (label === 'exact Alice fallback') shippedFigures[`order${order}`] = {bytes:encoded.frame.length, bitLength:encoded.bitLength, metrics:metrics(encoded.frame.length, bytes.length)};
    });
  }
}

/*
  An independent implementation of the coding rule the page publishes, written
  from that prose and not from the shipped coder: 257 symbols, every count
  starts at 1, the count is updated after the symbol is coded, and at total
  16383 every count becomes (count + 1) >> 1. It computes the ideal code length
  in bits and counts rescale events. It shares no code with the coder, so a
  mutually compatible violation of the published rule separates the two.
*/
function referenceCodeLength(bytes, order) {
  const contexts = order === 0 ? 1 : 257;
  const counts = Array.from({length:contexts}, () => new Array(257).fill(1));
  const totals = new Array(contexts).fill(257);
  let bits = 0;
  let rescales = 0;
  let context = 256;
  const code = symbol => {
    const c = order === 0 ? 0 : context;
    bits += -Math.log2(counts[c][symbol] / totals[c]);
    counts[c][symbol] += 1;
    totals[c] += 1;
    if (totals[c] >= 16383) {
      let running = 0;
      for (let s = 0; s < 257; s += 1) { counts[c][s] = (counts[c][s] + 1) >> 1; running += counts[c][s]; }
      totals[c] = running;
      rescales += 1;
    }
  };
  for (const byte of bytes) { code(byte); if (order === 1) context = byte; }
  code(256);
  return {bits, rescales};
}

/*
  The window is 30 to 40 bits and comes from the construction, not from the
  data: this coder writes 32 zero flush bits and at least one disambiguating
  bit, and the arithmetic coder's excess over the ideal code length is under
  two bits (Witten, Neal and Cleary 1987, section on the finite code value).
  Observed across these fixtures: 32.37 to 33.99 bits.
*/
const overheads = [];
for (const [label, bytes] of fixtures) {
  for (const order of [0, 1]) {
    check(`${label}: order ${order} payload length matches an independent model of the published rule`, () => {
      const encoded = encodeArithmetic(bytes, order);
      const reference = referenceCodeLength(bytes, order);
      const delta = encoded.bitLength - reference.bits;
      overheads.push(delta);
      assert(delta >= 30 && delta <= 40, `${label} order ${order}: coder ${encoded.bitLength} bits, independent ideal ${reference.bits.toFixed(3)} bits, difference ${delta.toFixed(3)}`);
    });
  }
}

check('rescaling is counted by the independent model, not inferred from input length', () => {
  assert.equal(RESCALE_AT, 16383);
  assert.equal(referenceCodeLength(repeated, 0).rescales, 11);
  assert.equal(referenceCodeLength(repeated, 1).rescales, 11);
  assert.equal(referenceCodeLength(alice, 0).rescales, 17);
  assert.equal(referenceCodeLength(alice, 1).rescales, 2);
  assert.equal(referenceCodeLength(new Uint8Array([1, 2, 3]), 0).rescales, 0);
  for (const order of [0, 1]) assert(bytesEqual(decodeArithmetic(encodeArithmetic(repeated, order).frame).bytes, repeated));
});

/*
  Independent implementations of the three non-identity transforms, written
  from the rule the page publishes. Paired transform and inverse functions from
  one module agree with each other whatever rule they implement, so the rule
  itself has to be checked against something written separately.
*/
function referenceReverse(input) {
  const out = new Uint8Array(input.length);
  for (let i = 0; i < input.length; i += 1) out[i] = input[input.length - 1 - i];
  return out;
}

function referenceDelta(input) {
  const out = new Uint8Array(input.length);
  for (let i = 0; i < input.length; i += 1) out[i] = i === 0 ? input[0] : (input[i] ^ input[i - 1]);
  return out;
}

function referencePermutation(input) {
  const index = new Uint32Array(input.length);
  for (let i = 0; i < input.length; i += 1) index[i] = i;
  let state = 0x6d2b79f5;
  for (let i = input.length - 1; i > 0; i -= 1) {
    state = (1664525 * state + 1013904223) % 4294967296;
    const j = Math.floor(state / 4294967296 * (i + 1));
    const swap = index[i]; index[i] = index[j]; index[j] = swap;
  }
  const out = new Uint8Array(input.length);
  for (let i = 0; i < input.length; i += 1) out[i] = input[index[i]];
  return out;
}

check('the three published transform rules agree with independent implementations', () => {
  const sample = seededBytes(4096, 0x2b1de5f1);
  assert(bytesEqual(transformBytes(sample, 1), referenceReverse(sample)));
  assert(bytesEqual(transformBytes(sample, 2), referenceDelta(sample)));
  assert(bytesEqual(transformBytes(sample, 3), referencePermutation(sample)));
  assert(bytesEqual(transformBytes(alice, 3), referencePermutation(alice)));
  const four = new Uint8Array([1, 2, 3, 4]);
  assert.deepEqual(Array.from(transformBytes(four, 1)), [4, 3, 2, 1]);
  assert.deepEqual(Array.from(transformBytes(four, 2)), [1, 3, 1, 7]);
  assert.deepEqual(Array.from(transformBytes(four, 3)), Array.from(referencePermutation(four)));
});

for (const [label, bytes] of fixtures) {
  for (const transform of TRANSFORMS) {
    check(`${label}: ${transform.label} exact inverse`, () => {
      const changed = transformBytes(bytes, transform.id);
      const restored = inverseTransform(changed, transform.id);
      assert(bytesEqual(restored, bytes));
      const prefixed = prefixTransform(changed, transform.id);
      assert.equal(prefixed.length, changed.length + TRANSFORM_PREFIX_BYTES);
      const parsed = parseTransformPrefix(prefixed);
      assert.equal(parsed.id, transform.id);
      assert(bytesEqual(parsed.payload, changed));
    });
  }
}

check('fixed position permutation preserves all 256 counts and H0 exactly on Alice', () => {
  const changed = transformBytes(alice, 3);
  const a = new Uint32Array(256), b = new Uint32Array(256);
  for (const x of alice) a[x] += 1;
  for (const x of changed) b[x] += 1;
  assert.deepEqual(a, b);
  assert.equal(empiricalH0(alice), empiricalH0(changed));
});

check('identity, reversal, and permutation preserve H0 on Alice', () => {
  const h = empiricalH0(alice);
  assert.equal(empiricalH0(transformBytes(alice, 0)), h);
  assert.equal(empiricalH0(transformBytes(alice, 1)), h);
  assert.equal(empiricalH0(transformBytes(alice, 3)), h);
});

check('H0 has its exact defined value on two inputs whose entropy is known without this code', () => {
  assert.equal(empiricalH0(allSymbols), 8);
  assert.equal(empiricalH0(new Uint8Array(64)), 0);
  assert.equal(empiricalH0(new Uint8Array(0)), 0);
  const half = new Uint8Array(1024);
  for (let i = 0; i < 512; i += 1) half[i] = 1;
  assert.equal(empiricalH0(half), 1);
});

/*
  From here the verifier drives the page's own worker functions rather than a
  parallel reimplementation, so every matrix total below is the length of a
  complete AWTX frame that was parsed and decoded on the way to the number.
*/
const aliceAnalysis = await analyze(alice);
const aliceMatrix = await runMatrix(alice);

await checkAsync('worker analyze returns three decoded rows whose digests match the specimen', async () => {
  assert.equal(aliceAnalysis.length, alice.length);
  assert.equal(aliceAnalysis.sha256, sha256(alice));
  assert.equal(aliceAnalysis.results.length, 3);
  for (const row of aliceAnalysis.results) {
    assert(!row.error, row.error);
    assert.equal(row.roundTrip, true);
    assert.equal(row.decodedSha, sha256(alice));
    assert.equal(row.decodedLength, alice.length);
  }
});

check('Alice transform matrix recomputes every displayed total from a parsed AWTX frame', () => {
  const figures = aliceMatrix.map(row => Object.fromEntries(row.codecs.map(c => [c.key, c.bytes])));
  assert.deepEqual(figures, [
    {gzip:54126, order0:87372, order1:71194},
    {gzip:54081, order0:87376, order1:71202},
    {gzip:64215, order0:112409, order1:88907},
    {gzip:93397, order0:87506, order1:92179}
  ]);
  for (const row of aliceMatrix) {
    assert.equal(row.codecs.length, 3);
    for (const codec of row.codecs) {
      assert.equal(codec.roundTrip, true);
      assert.equal(codec.framedId, row.id, 'the transform ID must come from the frame that was decoded');
      assert.equal(codec.restoredCrc, crc32(alice));
      assert.equal(codec.restoredLength, alice.length);
      assert.equal(codec.bytes, codec.streamBytes + TRANSFORM_PREFIX_BYTES);
    }
  }
});

check('every charged AWTX byte is load-bearing: corrupt any prefix field and the round trip refuses', () => {
  const stream = encodeArithmetic(alice.subarray(0, 4096), 0).frame;
  const good = prefixTransform(stream, 3);
  assert.equal(parseTransformPrefix(good).id, 3);
  for (const [offset, value, code] of [[0, 0x42, 'TRANSFORM_MAGIC'], [3, 0x42, 'TRANSFORM_MAGIC'], [4, 7, 'TRANSFORM_VERSION'], [5, 99, 'TRANSFORM_ID']]) {
    const broken = good.slice();
    broken[offset] = value;
    let caught = null;
    try { parseTransformPrefix(broken); } catch (error) { caught = error; }
    assert(caught, `byte ${offset} was ignored`);
    assert.equal(caught.code, code);
  }
  const wrongId = good.slice();
  wrongId[5] = 1;
  const opened = parseTransformPrefix(wrongId);
  const decoded = decodeArithmetic(opened.payload);
  assert(!bytesEqual(inverseTransform(decoded.bytes, opened.id), alice.subarray(0, 4096)), 'a swapped transform ID must not still restore the input');
});

check('the transform label costs 6 bytes and the coders move by far more than that', () => {
  const gzipTotals = aliceMatrix.map(row => row.codecs.find(c => c.key === 'gzip').bytes);
  const spread = Math.max(...gzipTotals) - Math.min(...gzipTotals);
  assert.equal(spread, 39316);
  assert(spread > 1000 * TRANSFORM_PREFIX_BYTES, `spread ${spread} against a ${TRANSFORM_PREFIX_BYTES} byte label`);
  const degeneracy = matrixDegeneracy(aliceMatrix);
  assert.equal(degeneracy.degenerate, false);
  assert.equal(degeneracy.distinctSequences, 4);
});

/*
  Specimens the builder cannot have seen. Reader files are uninterpreted bytes,
  so a malformed file is a legitimate specimen and must be described honestly
  rather than refused. Two of these are degenerate for the transform matrix and
  the page has to say so instead of showing four identical green rows.
*/
function fromHex(text) {
  const clean = text.replace(/\s+/g, '');
  const out = new Uint8Array(clean.length / 2);
  for (let i = 0; i < out.length; i += 1) out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);
  return out;
}

const truncatedPng = new Uint8Array(3000);
truncatedPng.set(fromHex('89504e470d0a1a0a0000000d49484452'), 0);
truncatedPng.set(seededBytes(2984, 0x51a7c3d9), 16);

const lyingArchive = new Uint8Array(1024);
lyingArchive.set(fromHex('415741430109ffffffffffffffff00000000000000000000'), 0);
lyingArchive.set(seededBytes(1000, 0x77abc123), 24);

const alreadyCompressed = new Uint8Array(zlib.gzipSync(Buffer.from(alice.subarray(0, 40000))));
const utf16Mess = fromHex('fffe4100d800000000000a002e2e2effff00000000dcff');
const zeros = new Uint8Array(4096);

const unseen = [
  ['truncated PNG header followed by high-entropy bytes', truncatedPng, {degenerate:false}],
  ['a file whose first bytes are a lying AWAC header', lyingArchive, {degenerate:false}],
  ['a gzip member of the first 40,000 Alice bytes, offered as the specimen', alreadyCompressed, {degenerate:false}],
  ['UTF-16 bytes with a lone surrogate and embedded NULs', utf16Mess, {degenerate:false}],
  ['4,096 zero bytes', zeros, {degenerate:true}],
  ['an empty file', new Uint8Array(0), {degenerate:true}]
];

for (const [label, bytes, expected] of unseen) {
  await checkAsync(`unseen specimen, ${label}: three decoded descriptions and twelve framed round trips`, async () => {
    const analysis = await analyze(bytes);
    assert.equal(analysis.length, bytes.length);
    assert.equal(analysis.sha256, sha256(bytes));
    assert.equal(analysis.crc32, crc32(bytes).toString(16).padStart(8, '0'));
    for (const row of analysis.results) {
      assert(!row.error, `${row.key}: ${row.error}`);
      assert.equal(row.decodedSha, sha256(bytes));
      assert.equal(row.decodedLength, bytes.length);
      const bpb = bytes.length === 0 ? null : 8 * row.bytes / bytes.length;
      assert.equal(row.bpb === undefined ? null : row.bpb, bpb);
    }
    const rows = await runMatrix(bytes);
    assert.equal(rows.length, 4);
    for (const row of rows) {
      for (const codec of row.codecs) {
        assert.equal(codec.roundTrip, true, `${label} ${row.key} ${codec.key}: ${codec.error}`);
        assert.equal(codec.framedId, row.id);
        assert.equal(codec.restoredCrc, crc32(bytes));
        assert.equal(codec.restoredLength, bytes.length);
      }
    }
    const degeneracy = matrixDegeneracy(rows);
    assert.equal(degeneracy.degenerate, expected.degenerate, `${label}: ${degeneracy.distinctSequences} distinct sequences`);
    if (expected.degenerate) {
      assert.equal(degeneracy.distinctSequences, 1);
      assert.equal(degeneracy.distinctTotals, 3, 'a degenerate specimen has one total per coder, repeated in every row');
    }
  });
}

check('the page detects and states the degenerate case rather than showing four identical rows', () => {
  assert.match(pageSource, /degeneracy\.degenerate/);
  assert.match(pageSource, /cannot demonstrate the comparison/);
  assert.match(html, /every total in the table is then equal by construction/);
  assert.match(pageSource, /state:'void'/);
});

/*
  The finite-set panel, driven through the same function the page calls.
*/
const setRows = aliceAnalysis.results;
check('best of set: adding a coder in one regime never worsens best, over every subset', () => {
  const keys = ['gzip', 'order0', 'order1'];
  for (let mask = 1; mask < 8; mask += 1) {
    const selected = keys.filter((_, i) => mask & (1 << i));
    for (const accounting of ['wire', 'source']) {
      const set = bestOfSet(setRows, selected, accounting, DECODER_SOURCE_BYTES);
      for (let i = 1; i < set.entries.length; i += 1) assert(set.entries[i].bestSoFar <= set.entries[i - 1].bestSoFar, `${selected} ${accounting}`);
      if (set.entries.length) assert.equal(set.best, Math.min(...set.entries.map(x => x.charged)));
      const growing = bestOfSet(setRows, keys, accounting, DECODER_SOURCE_BYTES);
      if (set.entries.length && growing.entries.length) assert(growing.best <= set.best, 'the full set cannot be worse than a subset');
    }
  }
});

check('one selected coder is reported as a single candidate, never as a best of set', () => {
  const single = bestOfSet(setRows, ['order1'], 'wire', DECODER_SOURCE_BYTES);
  assert.equal(single.comparison, 'single');
  assert.equal(single.best, setRows.find(x => x.key === 'order1').bytes);
  assert.equal(bestOfSet(setRows, [], 'wire', DECODER_SOURCE_BYTES).comparison, 'none');
  assert.equal(bestOfSet(setRows, ['gzip'], 'source', DECODER_SOURCE_BYTES).comparison, 'none');
  assert.equal(bestOfSet(setRows, ['gzip', 'order0'], 'wire', DECODER_SOURCE_BYTES).comparison, 'set');
  assert.match(pageSource, /Single candidate, no comparison/);
  assert.match(pageSource, /One coder is not a set and cannot have a best/);
});

check('the decoder charge is a constant and cannot reorder the coders it prices', () => {
  const priced = ['order0', 'order1'];
  const wire = bestOfSet(setRows, priced, 'wire', DECODER_SOURCE_BYTES);
  const source = bestOfSet(setRows, priced, 'source', DECODER_SOURCE_BYTES);
  assert.deepEqual(wire.entries.map(x => x.key), source.entries.map(x => x.key));
  const wireRank = [...wire.entries].sort((a, b) => a.charged - b.charged).map(x => x.key);
  const sourceRank = [...source.entries].sort((a, b) => a.charged - b.charged).map(x => x.key);
  assert.deepEqual(wireRank, sourceRank);
  for (const entry of source.entries) {
    const bare = wire.entries.find(x => x.key === entry.key);
    assert.equal(entry.charged - bare.charged, DECODER_SOURCE_BYTES);
  }
  assert.match(html, /it can never change which of them is shortest/);
});

check('the break-even length is where the decoder charge has content, and it is stated as an extrapolation', () => {
  const order1 = setRows.find(x => x.key === 'order1');
  const crossing = breakEvenBytes(order1.bytes, alice.length, DECODER_SOURCE_BYTES);
  const rate = order1.bytes / alice.length;
  assert.equal(crossing, DECODER_SOURCE_BYTES / (1 - rate));
  assert(crossing > alice.length / 8 && crossing < alice.length, `crossing ${crossing} should sit below this file's own length`);
  assert.equal(breakEvenBytes(500, 400, DECODER_SOURCE_BYTES), null, 'an expanding codec has no crossing');
  assert.equal(breakEvenBytes(400, 400, DECODER_SOURCE_BYTES), null, 'a codec that exactly ties has no crossing');
  assert.equal(breakEvenBytes(10, 0, DECODER_SOURCE_BYTES), null);
  assert.match(pageSource, /has no obligation to keep at other lengths/);
});

check('the anchor verdict function takes both branches from the numbers alone', () => {
  const nodeGzipBytes = zlib.gzipSync(alice).length;
  const live = anchorVerdict(nodeGzipBytes, alice.length, published.paperGzipBpc);
  assert.equal(live.rounded, 2.85);
  assert.equal(live.matches, false);
  const calibration = anchorVerdict(published.calibrationBytes, alice.length, published.paperGzipBpc);
  assert.equal(calibration.rounded, 2.86);
  assert.equal(calibration.matches, true);
  assert.equal(anchorVerdict(nodeGzipBytes, alice.length, published.siteGzipBpc).matches, true);
  assert.equal(anchorVerdict(10, 0, published.paperGzipBpc).matches, false);
  assert.match(renderedSurface, /Valid gzip, different implementation result/);
  assert.match(renderedSurface, /does not mandate one compressor strategy/);
});

check('decoder source accounting is exact UTF-8 file bytes', () => assert.equal(fs.statSync(codecPath).size, DECODER_SOURCE_BYTES));
check('Alice custom figures are recomputed, not fixtures', () => {
  assert.deepEqual(shippedFigures, {
    order0:{bytes:87366,bitLength:698716,metrics:{bpb:4.595519728579976,savings:42.5560033927503}},
    order1:{bytes:71188,bitLength:569292,metrics:{bpb:3.7445443128694382,savings:53.19319608913202}}
  });
});

const nodeGzip = new Uint8Array(zlib.gzipSync(alice));
const nodeGunzip = new Uint8Array(zlib.gunzipSync(nodeGzip));
check('current Node gzip complete decode and byte equality', () => assert(bytesEqual(nodeGunzip, alice)));
check('current Node gzip header, trailer CRC-32, and ISIZE', () => {
  const parsed = inspectGzip(nodeGzip, alice);
  assert.equal(parsed.isize, alice.length);
  assert.equal(parsed.actualCrc, crc32(alice));
  assert.equal(parsed.headerBytes + parsed.deflateBytes + parsed.trailerBytes, nodeGzip.length);
});
check('gzip optional header fields are parsed by flag, not assumed to be ten bytes', () => {
  const withName = new Uint8Array(zlib.gzipSync(Buffer.from('hi'), {level:9}));
  withName[3] |= 8;
  const named = new Uint8Array(withName.length + 12);
  named.set(withName.subarray(0, 10), 0);
  named.set(new TextEncoder().encode('alice29.txt'), 10);
  named[21] = 0;
  named.set(withName.subarray(10), 22);
  const parsed = parseGzip(named);
  assert.equal(parsed.headerBytes, 22);
  assert.equal(parsed.deflateBytes, named.length - 22 - 8);
  assert(bytesEqual(new Uint8Array(zlib.gunzipSync(Buffer.from(named))), new TextEncoder().encode('hi')));
});

check('gzip decode is independent of compressed chunk boundaries', () => {
  const pieces = [];
  for (let i = 0; i < nodeGzip.length; i += 37) pieces.push(nodeGzip.subarray(i, Math.min(nodeGzip.length, i + 37)));
  const joined = new Uint8Array(nodeGzip.length);
  let at = 0; for (const piece of pieces) { joined.set(piece, at); at += piece.length; }
  assert(bytesEqual(new Uint8Array(zlib.gunzipSync(joined)), alice));
});

const seedFrame = encodeArithmetic(new Uint8Array([0,1,2,3,4,255]), 0).frame;
expectCode('refusal: truncated arithmetic header', 'TRUNCATED_HEADER', () => parseArithmeticFrame(seedFrame.subarray(0, 12)));
const wrongMagic = seedFrame.slice(); wrongMagic[0] = 0;
expectCode('refusal: wrong arithmetic magic names byte 0', 'WRONG_MAGIC', () => parseArithmeticFrame(wrongMagic));
const wrongVersion = seedFrame.slice(); wrongVersion[4] = 2;
expectCode('refusal: unsupported arithmetic version names byte 4', 'UNSUPPORTED_VERSION', () => parseArithmeticFrame(wrongVersion));
const wrongOrder = seedFrame.slice(); wrongOrder[5] = 2;
expectCode('refusal: unsupported arithmetic order names byte 5', 'UNSUPPORTED_ORDER', () => parseArithmeticFrame(wrongOrder));
const lyingLength = seedFrame.slice(); new DataView(lyingLength.buffer).setUint32(14, 0xffffffff, true);
expectCode('refusal: lying arithmetic payload length names field byte 14', 'LYING_PAYLOAD_LENGTH', () => parseArithmeticFrame(lyingLength));
const lyingOriginal = seedFrame.slice(); new DataView(lyingOriginal.buffer).setUint32(6, 99, true);
expectCode('refusal: valid arithmetic header with lying original length', 'EARLY_EOF', () => decodeArithmetic(lyingOriginal));
const shortOriginal = seedFrame.slice(); new DataView(shortOriginal.buffer).setUint32(6, 2, true);
expectCode('refusal: declared length shorter than the coded stream', 'LENGTH_OVERRUN', () => decodeArithmetic(shortOriginal));
const brokenCrc = seedFrame.slice(); new DataView(brokenCrc.buffer).setUint32(22, 0xdeadbeef, true);
expectCode('refusal: arithmetic CRC-32 mismatch after a complete decode', 'CRC_MISMATCH', () => decodeArithmetic(brokenCrc));
const trailing = new Uint8Array(seedFrame.length + 1); trailing.set(seedFrame);
expectCode('refusal: trailing arithmetic byte names exact offset', 'TRAILING_BYTES', () => parseArithmeticFrame(trailing));
const tooShort = seedFrame.slice(0, 27); new DataView(tooShort.buffer).setUint32(14, 8, true); tooShort[26] = 0;
expectCode('refusal: arithmetic payload too short for the 32-bit code value', 'PAYLOAD_TOO_SHORT', () => parseArithmeticFrame(tooShort));
const nonzeroPadding = seedFrame.slice(); nonzeroPadding[nonzeroPadding.length - 1] |= 1;
expectCode('refusal: nonzero padding bits in the final payload byte', 'NONZERO_PADDING', () => parseArithmeticFrame(nonzeroPadding));
const overLimit = seedFrame.slice(); new DataView(overLimit.buffer).setUint32(6, MAX_BYTES + 1, true);
expectCode('refusal: declared original length above the instrument limit', 'DECLARED_LENGTH_LIMIT', () => parseArithmeticFrame(overLimit));
const outOfRange = seedFrame.slice(); new DataView(outOfRange.buffer).setUint32(10, 0x00200000, true);
expectCode('refusal: declared length outside the exact integer range', 'INTEGER_RANGE', () => parseArithmeticFrame(outOfRange));
check('refusal: a payload that runs out of bits names PAYLOAD_EXHAUSTED', () => {
  const frame = encodeArithmetic(seededBytes(600, 0x9e3779b9), 0).frame;
  const bits = Number(new DataView(frame.buffer).getUint32(14, true));
  const truncated = frame.slice(0, 26 + Math.ceil((bits - 400) / 8));
  new DataView(truncated.buffer).setUint32(14, bits - 400, true);
  const unused = (truncated.length - 26) * 8 - (bits - 400);
  if (unused) truncated[truncated.length - 1] &= 0xff << unused;
  let caught = null;
  try { decodeArithmetic(truncated); } catch (error) { caught = error; }
  assert(caught, 'a truncated payload was accepted');
  assert(['PAYLOAD_EXHAUSTED', 'MODEL_RANGE', 'EARLY_EOF', 'LENGTH_OVERRUN', 'CRC_MISMATCH'].includes(caught.code), caught.message);
  assert.match(caught.message, /byte [0-9]+/);
  coveredCodes.add('PAYLOAD_EXHAUSTED');
});

expectCode('refusal: truncated gzip member', 'GZIP_TRUNCATED', () => parseGzip(new Uint8Array([0x1f,0x8b,8])));
const gzMagic0 = nodeGzip.slice(); gzMagic0[0] = 0;
expectCode('refusal: wrong gzip first magic byte', 'GZIP_MAGIC_0', () => parseGzip(gzMagic0));
const gzMagic1 = nodeGzip.slice(); gzMagic1[1] = 0;
expectCode('refusal: wrong gzip second magic byte', 'GZIP_MAGIC_1', () => parseGzip(gzMagic1));
const gzMethod = nodeGzip.slice(); gzMethod[2] = 0;
expectCode('refusal: wrong gzip compression method', 'GZIP_METHOD', () => parseGzip(gzMethod));
const gzReserved = nodeGzip.slice(); gzReserved[3] |= 0x20;
expectCode('refusal: reserved gzip flags', 'GZIP_RESERVED_FLAGS', () => parseGzip(gzReserved));
const gzFilename = new Uint8Array(18); gzFilename.set([0x1f,0x8b,8,8], 0); gzFilename[10] = 65;
expectCode('refusal: unterminated gzip filename option', 'GZIP_UNTERMINATED_OPTION', () => parseGzip(gzFilename));
const gzExtra = new Uint8Array(20); gzExtra.set([0x1f,0x8b,8,4], 0); gzExtra[10] = 200; gzExtra[11] = 0;
expectCode('refusal: gzip optional field crossing the trailer', 'GZIP_TRUNCATED_OPTION', () => parseGzip(gzExtra));
const gzEmpty = new Uint8Array(19); gzEmpty.set([0x1f,0x8b,8,8], 0); gzEmpty[10] = 0;
expectCode('refusal: gzip member with no deflate payload', 'GZIP_EMPTY_DEFLATE', () => parseGzip(gzEmpty));
const badCrc = nodeGzip.slice(); badCrc[badCrc.length - 8] ^= 1;
expectCode('refusal: gzip trailer CRC mismatch', 'GZIP_CRC_MISMATCH', () => inspectGzip(badCrc, alice));
const badSize = nodeGzip.slice(); badSize[badSize.length - 4] ^= 1;
expectCode('refusal: gzip ISIZE mismatch', 'GZIP_ISIZE_MISMATCH', () => inspectGzip(badSize, alice));

const awtxFrame = prefixTransform(seedFrame, 2);
expectCode('refusal: AWTX frame truncated below its six bytes', 'TRANSFORM_TRUNCATED', () => parseTransformPrefix(awtxFrame.subarray(0, 5)));
const awtxMagic = awtxFrame.slice(); awtxMagic[1] = 0;
expectCode('refusal: wrong AWTX magic byte', 'TRANSFORM_MAGIC', () => parseTransformPrefix(awtxMagic));
const awtxVersion = awtxFrame.slice(); awtxVersion[4] = 9;
expectCode('refusal: unsupported AWTX version', 'TRANSFORM_VERSION', () => parseTransformPrefix(awtxVersion));
const awtxId = awtxFrame.slice(); awtxId[5] = 200;
expectCode('refusal: unknown AWTX transform ID', 'TRANSFORM_ID', () => parseTransformPrefix(awtxId));

check('refusal: over 8 MiB rejected before encoding', () => assert.throws(() => encodeArithmetic(new Uint8Array(MAX_BYTES + 1), 0), /exceeds/));
await checkAsync('refusal: an oversize file is refused before File.arrayBuffer() is reached', async () => {
  let reads = 0;
  const oversize = {size:MAX_BYTES + 1, arrayBuffer:async () => { reads += 1; return new ArrayBuffer(8); }};
  let caught = null;
  try { await readAcceptedFile(oversize); } catch (error) { caught = error; }
  assert(caught, 'an oversize file was accepted');
  assert.equal(caught.code, 'FILE_LIMIT');
  assert.match(caught.message, /byte 0/);
  coveredCodes.add('FILE_LIMIT');
  assert.equal(reads, 0, 'File.arrayBuffer() was called on a refused file');
  const atLimit = {size:MAX_BYTES, arrayBuffer:async () => { reads += 1; return new Uint8Array([1, 2, 3]).buffer; }};
  const bytes = await readAcceptedFile(atLimit);
  assert.equal(reads, 1, 'a file at exactly the limit must be read');
  assert.equal(bytes.length, 3);
  assert.throws(() => assertSizeBeforeRead({size:MAX_BYTES + 1}), /FILE_LIMIT/);
  assert.doesNotThrow(() => assertSizeBeforeRead({size:MAX_BYTES}));
});

/*
  MODEL_RANGE is the one code below that is not exercised by a fixture. It is a
  defensive guard inside the decoder, and the decoder's own interval invariant
  low <= value <= high makes the scaled cumulative value always smaller than
  the model total, so nothing outside the module can reach it. That claim is
  monitored rather than asserted from prose: 5,000 deterministic single-byte
  corruptions of a valid payload must all either decode or refuse with one of
  the four reachable codes.
*/
check('a deterministic corruption sweep never reaches the defensive model guard', () => {
  const base = encodeArithmetic(new Uint8Array([0, 1, 2, 3, 4, 255]), 0).frame;
  const seen = new Map();
  let state = 0x1234567;
  for (let trial = 0; trial < 5000; trial += 1) {
    const frame = base.slice();
    state = (Math.imul(1664525, state) + 1013904223) >>> 0;
    const at = 26 + (state % (frame.length - 26));
    state = (Math.imul(1664525, state) + 1013904223) >>> 0;
    frame[at] ^= (state & 255) || 1;
    const unused = (frame.length - 26) * 8 - new DataView(frame.buffer).getUint32(14, true);
    if (unused) frame[frame.length - 1] &= 0xff << unused;
    let code = 'decoded';
    try { decodeArithmetic(frame); } catch (error) { code = error.code || error.name; }
    seen.set(code, (seen.get(code) || 0) + 1);
  }
  const allowed = ['decoded', 'EARLY_EOF', 'LENGTH_OVERRUN', 'CRC_MISMATCH', 'PAYLOAD_EXHAUSTED'];
  const unexpected = [...seen.keys()].filter(x => !allowed.includes(x));
  assert.deepEqual(unexpected, [], `corruption sweep produced ${[...seen.entries()].join(' ')}`);
  assert(seen.get('EARLY_EOF') > 100 && seen.get('LENGTH_OVERRUN') > 100 && seen.get('CRC_MISMATCH') > 10, `the sweep must actually break things: ${[...seen.entries()].join(' ')}`);
});

check('every refusal code the parsers can raise is exercised, and the page states how many', () => {
  const expected = [
    'CRC_MISMATCH', 'DECLARED_LENGTH_LIMIT', 'EARLY_EOF', 'FILE_LIMIT',
    'GZIP_CRC_MISMATCH', 'GZIP_EMPTY_DEFLATE', 'GZIP_ISIZE_MISMATCH', 'GZIP_MAGIC_0',
    'GZIP_MAGIC_1', 'GZIP_METHOD', 'GZIP_RESERVED_FLAGS', 'GZIP_TRUNCATED',
    'GZIP_TRUNCATED_OPTION', 'GZIP_UNTERMINATED_OPTION', 'INTEGER_RANGE',
    'LENGTH_OVERRUN', 'LYING_PAYLOAD_LENGTH', 'NONZERO_PADDING', 'PAYLOAD_EXHAUSTED',
    'PAYLOAD_TOO_SHORT', 'TRAILING_BYTES', 'TRANSFORM_ID', 'TRANSFORM_MAGIC',
    'TRANSFORM_TRUNCATED', 'TRANSFORM_VERSION', 'TRUNCATED_HEADER',
    'UNSUPPORTED_ORDER', 'UNSUPPORTED_VERSION', 'WRONG_MAGIC'
  ];
  assert.deepEqual([...coveredCodes].sort(), expected);
  const declared = new Set(fs.readFileSync(codecPath, 'utf8').match(/new FormatError\('([A-Z_0-9]+)'/g).map(x => x.slice(17, -1)));
  declared.delete('MODEL_RANGE');
  assert(!coveredCodes.has('MODEL_RANGE'), 'MODEL_RANGE is exempt only because it is unreachable from outside the module');
  const missed = [...declared].filter(x => !coveredCodes.has(x));
  assert.deepEqual(missed, [], `refusal codes the codec can raise but nothing tests: ${missed}`);
  assert(html.includes(`${expected.length} named refusal codes`), `the page must state ${expected.length}`);
});

const requiredVisible = [
  '152,089-byte', '2.86 bits per character', '2.30', '2.85', '8 MiB', '16,383',
  '26-byte arithmetic header', 'six-byte AWTX', '0x6d2b79f5',
  '0xffffffff', '0x40000000', '0x80000000', '0xc0000000',
  'not the file\'s information content, randomness, or an incompressible core',
  'Best found in this finite set', 'undefined for empty input',
  "connect-src 'none'", '0 third-party resource origins'
];
for (const text of requiredVisible) check(`page text present, not a result: ${text}`, () => assert(renderedSurface.includes(text), text));

const dek = "Drop any file up to 8 MiB and this page attempts three named lossless descriptions entirely on your device, decodes every output it counts, and shows the byte-for-byte check first. On the shipped 152,089-byte alice29.txt it meets two published gzip figures for the same bytes, 2.86 bits per character in Arnold and Bell's paper and 2.85 on the corpus website, beside their separate 2.30 PPMC result. The concession is the result: these lengths are upper bounds under chosen codecs and decoder accounting, not the file's information content, randomness, or an incompressible core.";
const plain = "Choose any file and three lossless coders try to shorten it without sending it anywhere. Every output has to reconstruct every byte before the page counts it. The different answers belong to the coders as much as to the file, so none is labelled the file's true information or randomness.";
const seoTitle = 'How Much Can My File Be Compressed? Test It Locally';
check('frontmatter dek is character for character the meta description', () => { assert(frontmatter.includes(`dek: "${dek}"`)); assert(html.includes(`<meta name="description" content="${dek}"`)); });
check('frontmatter plain is character for character the aw-plain meta', () => { assert(frontmatter.includes(`plain: "${plain}"`)); assert(html.includes(`<meta name="aw-plain" content="${plain}"`)); });
check('SEO title is character for character the document title and JSON-LD name', () => { assert(frontmatter.includes(`seoTitle: "${seoTitle}"`)); assert(html.includes(`<title>${seoTitle}</title>`)); });
check('the dek promises an attempt, because gzip can be unavailable and then only refuses', () => {
  assert(dek.includes('attempts three named lossless descriptions'));
  assert(dek.includes('decodes every output it counts'));
  assert.match(fs.readFileSync(path.join(publicDir, 'worker.mjs'), 'utf8'), /No gzip result was manufactured/);
  assert(!dek.includes('runs three named lossless descriptions'));
});
check('frontmatter has binding seam, wave tags, four substantive edges, and publication flag', () => {
  assert.match(frontmatter, /seam: "number"/);
  for (const tag of ['immersive','interactive','show-the-check','the specimen is yours']) assert(frontmatter.includes(`"${tag}"`));
  assert.equal((frontmatter.match(/  - to:/g) || []).length, 4);
  assert.match(frontmatter, /draft: false/);
});

check('JSON-LD parses and carries required honest Article fields', () => {
  const match = html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/);
  assert(match);
  const data = JSON.parse(match[1]);
  assert.equal(data['@type'], 'Article');
  assert.equal(data.name, seoTitle);
  assert.equal(data.headline, 'The Part of Your File That Will Not Shrink');
  assert.equal(data.description, dek);
  assert.equal(data.datePublished, '2026-08-09T00:00:00Z');
  assert(data.author && data.publisher && data.url && data.image);
});

check('every claim in the social text is a number this run produced', () => {
  assert.match(html, /Three lossless coders disagree on your own bytes, and every result must decode before it counts/);
  const totals = aliceAnalysis.results.map(x => x.bytes);
  assert.equal(new Set(totals).size, 3, `the three coders must actually disagree: ${totals}`);
  // Distinctness alone would be close to a tautology, since container magic differs.
  // The claim is model dependence, so the spread has to be far larger than framing.
  const relative = (Math.max(...totals) - Math.min(...totals)) / Math.min(...totals);
  assert(relative > 0.5, `spread of ${(relative * 100).toFixed(1)}% is too small to be about models: ${totals}`);
  assert(Math.max(...totals) - Math.min(...totals) > 1000 * 26, 'the spread must dwarf the frame headers it is not about');
  for (const row of aliceAnalysis.results) assert.equal(row.decodedSha, sha256(alice), 'a counted row that did not decode');
  assert.match(html, /best-so-far description, not your file's information content/);
  const full = bestOfSet(aliceAnalysis.results, ['gzip','order0','order1'], 'wire', DECODER_SOURCE_BYTES);
  assert.equal(full.best, Math.min(...totals));
  assert.equal(full.comparison, 'set');
  assert.match(html, /verify every round trip, then move the supposed answer by changing the model/);
  const gzipTotals = aliceMatrix.map(row => row.codecs.find(c => c.key === 'gzip').bytes);
  assert(Math.max(...gzipTotals) > Math.min(...gzipTotals) + 30000, 'the model change must actually move the answer');
});

check('no third-party request target in any page-controlled file or its direct dependencies', () => {
  const allowedHosts = new Set(['artwaste.land']);
  const requestish = [
    /fetch\s*\(\s*["'`]([^"'`]+)/gi,
    /import\s*\(\s*["'`]([^"'`]+)/gi,
    /\.open\s*\(\s*["'][A-Z]+["']\s*,\s*["'`]([^"'`]+)/gi,
    /new\s+(?:WebSocket|EventSource|Worker|SharedWorker)\s*\(\s*["'`]([^"'`]+)/gi,
    /sendBeacon\s*\(\s*["'`]([^"'`]+)/gi,
    /\.src\s*=\s*["'`]([^"'`]+)/gi,
    /<(?:script|img|iframe|audio|video|source|embed)[^>]+src=["']([^"']+)/gi,
    /<link[^>]+href=["']([^"']+)/gi,
    /url\(\s*['"]?([^'")]+)/gi
  ];
  const files = [
    htmlPath,
    path.join(publicDir, 'page.mjs'),
    path.join(publicDir, 'worker.mjs'),
    path.join(publicDir, 'codec.mjs'),
    path.join(publicDir, 'alice-data.js'),
    path.join(siteDir, 'media/home-banner.js'),
    path.join(siteDir, 'media/plain-button.js'),
    path.join(siteDir, 'fonts/fonts.css')
  ];
  const offenders = [];
  for (const file of files) {
    const source = fs.readFileSync(file, 'utf8');
    for (const pattern of requestish) {
      pattern.lastIndex = 0;
      let match;
      while ((match = pattern.exec(source))) {
        const target = match[1];
        if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(target)) continue;
        let host = 'unparseable';
        try { host = new URL(target).host; } catch { host = 'unparseable'; }
        if (!allowedHosts.has(host)) offenders.push(`${path.basename(file)}: ${target}`);
      }
    }
  }
  assert.deepEqual(offenders, []);
  assert.equal(fs.readFileSync(path.join(siteDir, 'media/home-banner.js'), 'utf8').match(/\.src\s*=\s*'([^']+)'/)[1], '/media/plain-button.js');
});
check('the page audits every request construct it names, in its first executable script', () => {
  const inline = html.split('<script>')[1].split('</script>')[0];
  for (const api of ['fetch', 'XMLHttpRequest', 'WebSocket', 'EventSource', 'sendBeacon']) assert(inline.includes(api), api);
  assert(html.indexOf('<script>') < html.indexOf('alice-data.js'), 'the audit hook must be installed before any specimen script');
});
check('load-bearing closing tags exist in order', () => assert.match(html, /<script src="\/media\/home-banner\.js" defer><\/script>\s*<\/body>\s*<\/html>\s*$/));
check('horizontally scrolling tables are reachable by keyboard', () => {
  const regions = html.match(/<div class="scroll"[^>]*>/g) || [];
  assert.equal(regions.length, 2);
  for (const region of regions) {
    assert.match(region, /tabindex="0"/);
    assert.match(region, /role="region"/);
    assert.match(region, /aria-label="[^"]+"/);
  }
});
check('the check panel does not present a decorative line as a passing check', () => {
  assert.match(pageSource, /state:'note'/);
  assert.match(pageSource, /measurements that are not checks/);
  assert.doesNotMatch(pageSource, /pass:true/);
});
check('no forbidden dash or ellipsis characters in authored text and code', () => {
  const forbidden = new RegExp('[\\u2014\\u2013\\u2026]', 'u');
  const files = ['index.html','page.mjs','worker.mjs','codec.mjs','alice-data.js'];
  for (const file of files) assert.doesNotMatch(fs.readFileSync(path.join(publicDir,file),'utf8'), forbidden, file);
  assert.doesNotMatch(frontmatter, forbidden);
  assert.doesNotMatch(fs.readFileSync(fileURLToPath(import.meta.url),'utf8'), forbidden);
});

/*
  Opportunistic, and reported as a skip rather than a pass when the tool is
  absent, because a check that silently passes when it did not run is exactly
  the kind of decoration this page is about.
*/
try {
  const measure = args => execFileSync('gzip', args, {input:Buffer.from(alice), maxBuffer:1 << 26}).length;
  const version = execFileSync('gzip', ['--version'], {encoding:'utf8'}).split('\n')[0];
  check(`recorded GNU gzip byte counts re-measured here (${version})`, () => {
    assert.equal(measure(['-c', '-n']), published.gnuDefaultNoName);
    assert.equal(measure(['-9', '-c', '-n']), published.gnuBestNoName);
  });
} catch (error) {
  skipped.push(`GNU gzip not runnable here, so the recorded 54,423 and 54,179 byte counts were not re-measured: ${error.message.split('\n')[0]}`);
}

for (const item of checks) {
  if (item.ok) console.log(`PASS ${item.name}`);
  else console.error(`FAIL ${item.name}\n  ${item.error.stack || item.error}`);
}
for (const note of skipped) console.log(`SKIP ${note}`);
const passed = checks.filter(x => x.ok).length;
console.log(`\n${passed}/${checks.length} checks pass, ${skipped.length} skipped`);
console.log(`Alice: ${alice.length} bytes; SHA-256 ${sha256(alice)}`);
console.log(`Current Node gzip: ${nodeGzip.length} bytes; ${(8 * nodeGzip.length / alice.length).toFixed(12)} bits per input byte; rounds to ${(Math.round(800 * nodeGzip.length / alice.length) / 100).toFixed(2)}`);
console.log(`Adaptive order 0: ${shippedFigures.order0.bytes} bytes; ${shippedFigures.order0.metrics.bpb.toFixed(12)} bits per input byte`);
console.log(`Adaptive order 1: ${shippedFigures.order1.bytes} bytes; ${shippedFigures.order1.metrics.bpb.toFixed(12)} bits per input byte`);
console.log(`Coder overhead against the independent model of the published rule: ${Math.min(...overheads).toFixed(3)} to ${Math.max(...overheads).toFixed(3)} bits, window 30 to 40`);
if (passed !== checks.length) process.exitCode = 1;
