import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { readFile, readdir } from 'node:fs/promises';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { analyzePdf, DEFAULT_LIMITS, PdfRefusal, refusalRecord } from '../../public/strata/what-your-pdf-still-remembers/pdf-core.mjs';

const here = dirname(fileURLToPath(import.meta.url));
const root = resolve(here, '../..');
const publicDir = join(root, 'public/strata/what-your-pdf-still-remembers');
const pdfPath = join(publicDir, 'append-page-content.pdf');
const htmlPath = join(publicDir, 'index.html');
const markdownPath = join(root, 'src/content/strata/what-your-pdf-still-remembers.md');
const expectedHash = '2a70474d0185222b0cb22089de654f8f2a4d207b7f61b646a030b1e563da837b';
const expectedDek = 'Drop a PDF and follow only the incremental update sections its own cross-reference data can validate, entirely inside your browser. The shipped qpdf fixture reproduces three linked revisions and recovers Potato 0 before object 33 0 is replaced by Potato 0 new. A missing chain does not mean a file was never edited, a present chain is not a human edit log, and this instrument does not certify safe redaction.';
const expectedPlain = 'Some PDF software saves changes by appending new bytes and linking back to the earlier cross-reference section. This page reads your own file locally and opens any earlier byte slices it can validate, while making clear that no chain does not mean no editing and recovered bytes do not certify safe redaction.';
const expectedSeo = 'How to Find Previous Versions in a PDF Locally';
const forbiddenDash = String.fromCodePoint(0x2014);
let checks = 0;

function check(value, message) {
  assert.ok(value, message);
  checks += 1;
}

function equal(actual, expected, message) {
  assert.deepEqual(actual, expected, message);
  checks += 1;
}

function bytes(source) {
  return new TextEncoder().encode(source);
}

// A refusal is only useful if it names what failed and where. Message length proves neither,
// so every constructed refusal must also carry a byte offset and the literal number or token
// that made it fail.
async function refusal(input, code, options = {}, expect = {}) {
  try {
    await analyzePdf(input, options);
    assert.fail(`Expected ${code}, parser accepted the constructed input`);
  } catch (error) {
    check(error instanceof PdfRefusal, `${code} must be a typed parser refusal`);
    equal(error.code, code, `constructed refusal code ${code}`);
    check(typeof error.message === 'string' && error.message.length > 20, `${code} explains the byte-level reason`);
    check(Number.isInteger(error.offset), `${code} reports an integer byte offset`);
    if (expect.offset !== undefined) equal(error.offset, expect.offset, `${code} reports byte ${expect.offset}`);
    for (const fragment of expect.names || []) check(error.message.includes(fragment), `${code} message names ${JSON.stringify(fragment)}`);
    return error;
  }
}

function classicPdf({ flexible = false, prevSelf = false, encrypt = false } = {}) {
  const prefix = '%PDF-1.4\n1 0 obj\n<< /Type /Catalog >>\nendobj\n';
  const offset = prefix.length;
  const row0 = flexible ? '0 65535 f\n' : '0000000000 65535 f \n';
  const row1 = flexible ? `${prefix.indexOf('1 0 obj')} 0 n\n` : `${String(prefix.indexOf('1 0 obj')).padStart(10, '0')} 00000 n \n`;
  const trailer = `trailer << /Size 2${prevSelf ? ` /Prev ${offset}` : ''}${encrypt ? ' /Encrypt 9 0 R' : ''} >>\n`;
  return bytes(`${prefix}xref\n0 2\n${row0}${row1}${trailer}startxref\n${offset}\n%%EOF\n`);
}

function classicCrLfPdf() {
  const prefix = '%PDF-1.4\r\n1 0 obj\r\n<< /Type /Catalog >>\r\nendobj\r\n';
  const offset = prefix.length;
  const row0 = '0000000000 65535 f\r\n';
  const row1 = `${String(prefix.indexOf('1 0 obj')).padStart(10, '0')} 00000 n\r\n`;
  return bytes(`${prefix}xref\r\n0 2\r\n${row0}${row1}trailer << /Size 2 >>\r\nstartxref\r\n${offset}\r\n%%EOF\r\n`);
}

function xrefStreamPdf(length = 14) {
  const prefix = bytes('%PDF-1.5\n');
  const offset = prefix.length;
  const record = new Uint8Array([
    0, 0, 0, 0, 0, 255, 255,
    1, 0, 0, 0, offset, 0, 0
  ]);
  const before = bytes(`1 0 obj\n<< /Type /XRef /Size 2 /W [1 4 2] /Length ${length} >>\nstream\n`);
  const after = bytes(`\nendstream\nendobj\nstartxref\n${offset}\n%%EOF\n`);
  const result = new Uint8Array(prefix.length + before.length + record.length + after.length);
  result.set(prefix, 0);
  result.set(before, prefix.length);
  result.set(record, prefix.length + before.length);
  result.set(after, prefix.length + before.length + record.length);
  return result;
}

function contentPdf(content) {
  const prefix = '%PDF-1.4\n';
  const objectOffset = prefix.length;
  const object = `1 0 obj\n<< /Length ${content.length} >>\nstream\n${content}\nendstream\nendobj\n`;
  const xrefOffset = prefix.length + object.length;
  const xref = `xref\n0 2\n0000000000 65535 f \n${String(objectOffset).padStart(10, '0')} 00000 n \ntrailer << /Size 2 >>\nstartxref\n${xrefOffset}\n%%EOF\n`;
  return bytes(prefix + object + xref);
}

function metaContent(html, selector) {
  const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  const match = html.match(new RegExp(`<meta[^>]+${escaped}[^>]+content="([^"]*)"[^>]*>`, 'i'));
  return match ? match[1].replaceAll('&quot;', '"').replaceAll('&amp;', '&') : null;
}

const pdf = await readFile(pdfPath);
equal(pdf.length, 17370, 'fallback file length');
equal(createHash('sha256').update(pdf).digest('hex'), expectedHash, 'fallback SHA-256');
const fallbackModule = await readFile(join(publicDir, 'fallback-data.mjs'), 'utf8');
const embedded = Buffer.from(fallbackModule.match(/FALLBACK_BASE64 = '([^']+)'/)[1], 'base64');
equal(embedded.length, pdf.length, 'embedded fallback byte count matches shipped PDF');
equal(createHash('sha256').update(embedded).digest('hex'), expectedHash, 'embedded fallback hash matches shipped PDF');
equal(Buffer.compare(embedded, pdf), 0, 'embedded fallback is byte-for-byte identical to shipped PDF');

const result = await analyzePdf(pdf);
equal(result.fileLength, 17370, 'parser sees every fallback byte');
equal(result.version, '1.3', 'fallback PDF version');
equal(result.sections.map(section => section.offset), [13801, 16059, 16940], 'classic xref offsets');
equal(result.sections.map(section => section.kind), ['classic', 'classic', 'classic'], 'anchor xref kinds');
equal(result.sections.map(section => section.prev), [null, 13801, 16059], 'literal Prev chain');
equal(result.sections.map(section => section.size), [108, 108, 108], 'literal Size values');
equal(result.sections.map(section => section.entryCount), [108, 2, 17], 'entries parsed from every subsection');
equal(result.revisions.map(revision => revision.startxrefToken), [16012, 16162, 17348], 'accepted startxref token offsets');
equal(result.revisions.map(revision => revision.eofStart), [16028, 16178, 17364], 'matching EOF marker starts');
equal(result.revisions.map(revision => revision.eofEnd), [16033, 16183, 17369], 'matching EOF marker ends');
equal(result.revisions.map(revision => revision.sliceEnd), [16034, 16184, 17370], 'renderable slice ends include one trailing line ending');
equal(result.revisions.map(revision => revision.appendStart), [0, 16034, 16184], 'appended span starts');
equal(result.revisions.map(revision => revision.appendBytes), [16034, 150, 1186], 'appended span byte counts');

function winner(revision, object) {
  return revision.winners.find(entry => entry.object === object);
}

equal([winner(result.revisions[0], 1).offset, winner(result.revisions[2], 1).offset], [25, 16648], 'object 1 0 definitions');
equal([winner(result.revisions[0], 33).offset, winner(result.revisions[2], 33).offset], [6748, 16817], 'object 33 0 definitions');
equal(winner(result.revisions[1], 107), { object: 107, offset: 0, generation: 1, type: 0, source: 'table', resolved: null }, 'revision 2 marks object 107 free');
equal(winner(result.revisions[2], 107).offset, 16227, 'revision 3 reuses object 107 1');
equal(winner(result.revisions[2], 107).generation, 1, 'reused object generation');
equal(result.revisions[2].changes.find(change => change.object === 1).action, 'superseded', 'same-generation object 1 classification');
equal(result.revisions[2].changes.find(change => change.object === 33).action, 'superseded', 'same-generation object 33 classification');
equal(result.revisions[2].changes.filter(change => change.action === 'deleted').map(change => change.object), [34, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106], 'revision 3 deleted object set');
equal(result.revisions[2].changes.filter(change => change.action === 'deleted').map(change => change.generation), Array(13).fill(1), 'all revision 3 deletions have generation 1');
check(result.revisions[0].text.some(item => item.object === 33 && item.text === 'Potato 0' && item.raw === '(Potato 0)'), 'revision 1 decodes raw Potato 0 operator');
check(result.revisions[1].text.some(item => item.object === 33 && item.text === 'Potato 0'), 'revision 2 retains the earlier object 33 winner');
check(result.revisions[2].text.some(item => item.object === 33 && item.text === 'Potato 0 new' && item.raw === '(Potato 0 new)'), 'revision 3 decodes replacement text');
check(!result.revisions[2].text.some(item => item.object === 33 && item.text === 'Potato 0'), 'newest winner does not mistake superseded object 33 for active content');
equal(result.revisions.map(revision => revision.covers.length), [0, 0, 0], 'fallback has no qualifying later-paint candidates');

equal(result.choices.newestValidEofSearchWindow, 65536, 'EOF search window');
// A disclosed choice that nothing reads is decoration. Every ceiling named in the choices
// list has to change the parser's behaviour when it is moved, and each is exercised below
// or in the refusal table. Two that were named and never read at all have been removed.
await refusal(pdf, 'NO_STARTXREF', { choices: { startxrefWindow: 8 } }, { names: ['8 bytes'] });
equal((await analyzePdf(pdf, { choices: { startxrefWindow: 64 } })).choices.newestValidEofSearchWindow, 64, 'the disclosed window is the one in force');
equal(Object.keys(DEFAULT_LIMITS).filter(key => key === 'pages' || key === 'renderPixels'), [], 'no ceiling is disclosed that nothing enforces');
equal(result.choices.malformedChainRecovery, false, 'strict recovery default');
equal(result.choices.acceptedStreamFilters, ['FlateDecode', 'ASCIIHexDecode'], 'stream filter allowlist');
equal(result.choices.decompressionByteCeiling, DEFAULT_LIMITS.decodedBytes, 'decoded stream ceiling');
equal(result.choices.objectCeiling, DEFAULT_LIMITS.objects, 'object ceiling');
equal(result.choices.recursionCeiling, DEFAULT_LIMITS.nesting, 'dictionary nesting ceiling');
equal(result.choices.xobjectRecursionDepth, DEFAULT_LIMITS.xobjectDepth, 'disclosed XObject recursion ceiling');
equal(result.choices.opacityCutoff, 0.95, 'disclosed opacity cutoff');
equal(result.choices.opacityTreatment, 'default alpha 1; fills after unresolved ExtGState gs are excluded', 'disclosed unresolved-opacity treatment');
equal(result.choices.fillDarknessCutoff, 0.35, 'disclosed darkness cutoff');
equal(result.choices.rectangleGlyphOverlap, 0.5, 'disclosed overlap cutoff');
equal(result.choices.invisibleOcrText, false, 'invisible OCR treatment');
equal(result.choices.annotationsIncluded, false, 'annotation treatment');

await refusal(bytes('%PDF-1.4'), 'TOO_SHORT');
await refusal(bytes('not-a-pdf-at-all\nstartxref\n0\n%%EOF\n'), 'BAD_MAGIC');
await refusal(bytes('%PDF-1.4\nstartxref\nbanana\n%%EOF\n'), 'BAD_STARTXREF_NUMBER');
await refusal(bytes('%PDF-1.4\nstartxref\n999\n%%EOF\n'), 'STARTXREF_OUT_OF_RANGE');
await refusal(bytes('%PDF-1.4\nhello\nstartxref\n9\n%%EOF\n'), 'STARTXREF_TARGET');
await refusal(classicPdf({ flexible: true }), 'XREF_ENTRY');
const recovered = await analyzePdf(classicPdf({ flexible: true }), { recovery: true });
equal(recovered.revisions.length, 1, 'explicit recovery accepts flexible xref spacing');
equal(recovered.choices.malformedChainRecovery, true, 'recovery result remains labelled');
equal((await analyzePdf(classicCrLfPdf())).revisions.length, 1, 'strict mode accepts conforming 20-byte CRLF xref rows');
await refusal(classicPdf({ prevSelf: true }), 'PREV_CYCLE');
await refusal(classicPdf({ encrypt: true }), 'ENCRYPTED');
await refusal(xrefStreamPdf(999), 'STREAM_LENGTH');
const streamResult = await analyzePdf(xrefStreamPdf());
equal(streamResult.sections.map(section => section.kind), ['stream'], 'valid xref stream path succeeds');
equal(streamResult.sections[0].w, [1, 4, 2], 'xref stream W array');
equal(streamResult.sections[0].entryCount, 2, 'xref stream record count');

const coveredPdf = contentPdf('BT /F1 12 Tf 10 10 Td (secret) Tj ET 0 g 8 8 50 16 re f');
const covered = await analyzePdf(coveredPdf);
equal(covered.revisions[0].covers.length, 1, 'later dark rectangle crossing the text box is detected');
equal(covered.revisions[0].covers[0].text, 'secret', 'paint candidate preserves decoded text');
check(covered.revisions[0].covers[0].overlap > 0.9, 'paint candidate recomputes substantial overlap');
equal((await analyzePdf(contentPdf('BT /F1 12 Tf 10 10 Td (secret) Tj ET 0 g 200 200 50 16 re f'))).revisions[0].covers.length, 0, 'non-overlapping dark paint is a negative control');
equal((await analyzePdf(contentPdf('BT /F1 12 Tf 10 10 Td 3 Tr (secret) Tj ET 0 g 8 8 50 16 re f'))).revisions[0].covers.length, 0, 'invisible text is excluded by default');
equal((await analyzePdf(contentPdf('BT /F1 12 Tf 10 10 Td (secret) Tj ET /GS1 gs 0 g 8 8 50 16 re f'))).revisions[0].covers.length, 0, 'unresolved ExtGState alpha fails closed');
equal((await analyzePdf(coveredPdf, { choices: { darkness: -0.01 } })).revisions[0].covers.length, 0, 'darkness threshold can reject the positive control');
equal((await analyzePdf(coveredPdf, { choices: { overlap: 0.99 } })).revisions[0].covers.length, 0, 'overlap threshold can reject the positive control');
equal((await analyzePdf(coveredPdf, { choices: { opacity: 1.01 } })).revisions[0].covers.length, 0, 'opacity threshold can reject the positive control');

// ---------------------------------------------------------------------------
// Specimens the builder did not have. Everything below this line was added by the
// reconcile stage from an adversarial audit, a blinded independent re-derivation,
// and files run through the parser for the first time.
// ---------------------------------------------------------------------------

// The boundary a section is closed by has to be the one that sits after that section's
// own syntax. This specimen carries a syntactically perfect startxref, integer and %%EOF
// inside a later object's content stream. Before the boundary rule was bound to the
// grammar, revision 1 ended at byte 223, sixty-three bytes into the second update and
// inside its stream. The correct ends are 160 and 344.
const eofTrapBase64 = 'JVBERi0xLjcKMSAwIG9iago8PCAvTGVuZ3RoIDEyID4+CnN0cmVhbQpCVCAob2xkKSBUagplbmRzdHJlYW0KZW5kb2JqCnhyZWYKMCAyCjAwMDAwMDAwMDAgNjU1MzUgZiAKMDAwMDAwMDAwOSAwMDAwMCBuIAp0cmFpbGVyIDw8IC9TaXplIDIgPj4Kc3RhcnR4cmVmCjcwCiUlRU9GCjIgMCBvYmoKPDwgL0xlbmd0aCAzMCA+PgpzdHJlYW0KQlQgKG5ldykgVGoKc3RhcnR4cmVmCjcwCiUlRU9GCmVuZHN0cmVhbQplbmRvYmoKeHJlZgowIDEKMDAwMDAwMDAwMCA2NTUzNSBmIAoyIDEKMDAwMDAwMDE2MCAwMDAwMCBuIAp0cmFpbGVyIDw8IC9TaXplIDMgL1ByZXYgNzAgPj4Kc3RhcnR4cmVmCjI0MAolJUVPRgo=';
const eofTrap = Buffer.from(eofTrapBase64, 'base64');
equal(eofTrap.length, 344, 'in-stream EOF trap specimen length');
equal(eofTrap.toString('latin1').indexOf('startxref\n70\n%%EOF', 161), 204, 'the trap really does hold a complete startxref and EOF pair inside object 2 stream');
const trapped = await analyzePdf(eofTrap);
equal(trapped.revisions.map(revision => revision.sliceEnd), [160, 344], 'a startxref inside a stream cannot move a revision boundary');
equal(trapped.revisions.map(revision => revision.startxrefToken), [141, 324], 'each boundary token sits where its own section syntax ends');
equal(trapped.revisions.map(revision => revision.startxrefValue), [70, 240], 'each boundary prints its own section offset');
equal(trapped.revisions.map(revision => revision.eofEnd), [159, 343], 'trap specimen EOF ends');
equal(trapped.standalone.passed, 2, 'both trap slices re-parse alone');
check(trapped.revisions[0].text.some(item => item.text === 'old'), 'the earlier trap slice still holds its own text');

// An xref entry is a claim, not a definition. This 147-byte file says object 1 is at byte
// 999,999. Nothing is there. It must still be accepted structurally and must not be
// displayed as a definition that won.
const impossibleOffset = Buffer.from('JVBERi0xLjcKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZyA+PgplbmRvYmoKeHJlZgowIDIKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwOTk5OTk5IDAwMDAwIG4gCnRyYWlsZXIgPDwgL1NpemUgMiAvUm9vdCAxIDAgUiA+PgpzdGFydHhyZWYKNDUKJSVFT0YK', 'base64');
equal(impossibleOffset.length, 147, 'impossible-offset specimen length');
const impossible = await analyzePdf(impossibleOffset);
equal(impossible.revisions[0].winners.find(entry => entry.object === 1).offset, 999999, 'the impossible entry is still reported literally');
equal(impossible.revisions[0].winners.find(entry => entry.object === 1).resolved, false, 'an entry pointing outside the file is not a resolved definition');
equal(impossible.revisions[0].unresolvedCount, 1, 'the unresolved winner is counted');
equal(impossible.revisions[0].definitionCount, 1, 'free entries are not counted as definitions');
equal(impossible.revisions[0].winners.find(entry => entry.object === 0).resolved, null, 'a free entry is neither resolved nor unresolved');
equal(result.revisions.map(revision => revision.unresolvedCount), [0, 0, 0], 'every anchor winner resolves to its own object header');
equal(result.revisions.map(revision => revision.definitionCount), [107, 106, 94], 'anchor definition counts');

// The same check has to be able to say yes. A one-byte edit to the header of the object an
// entry points at must flip exactly one winner from resolved to unresolved.
const bentHeader = Buffer.from(impossibleOffset);
bentHeader.write('0000000009', impossibleOffset.toString('latin1').indexOf('0000999999'), 'latin1');
equal((await analyzePdf(bentHeader)).revisions[0].unresolvedCount, 0, 'pointing the same entry at the real object header resolves it');
const bentObject = Buffer.from(bentHeader);
bentObject.write('7', bentObject.toString('latin1').indexOf('1 0 obj'), 'latin1');
equal((await analyzePdf(bentObject)).revisions[0].unresolvedCount, 1, 'changing the object header number alone makes the entry unresolved again');

// A truncated end-of-file marker is not a malformed offset. Naming it BAD_STARTXREF_NUMBER
// pointed the reader at an integer that was perfectly well formed.
const truncatedEof = Buffer.from('JVBERi0xLjcKMSAwIG9iago8PCAvTGVuZ3RoIDE3ID4+CnN0cmVhbQpCVCAoY3V0LW1lKSBUaiBFVAplbmRzdHJlYW0KZW5kb2JqCnhyZWYKMCAyCjAwMDAwMDAwMDAgNjU1MzUgZiAKMDAwMDAwMDAwOSAwMDAwMCBuIAp0cmFpbGVyIDw8IC9TaXplIDIgPj4Kc3RhcnR4cmVmCjc2CiUlRQ==', 'base64');
equal(truncatedEof.length, 163, 'truncated-EOF specimen length');
await refusal(truncatedEof, 'NO_EOF_BOUNDARY', {}, { offset: 147, names: ['76'] });
await refusal(bytes('%PDF-1.4\nstartxref\nbanana\n%%EOF\n'), 'BAD_STARTXREF_NUMBER', {}, { offset: 9 });

// A stream the bench could not read is a hole in the reading, and has to be named as one.
const lyingLength = Buffer.from('JVBERi0xLjcKMSAwIG9iago8PCAvTGVuZ3RoIDk5OSA+PgpzdHJlYW0KQlQgKGhpZGRlbi1ieS1saWUpIFRqIEVUCmVuZHN0cmVhbQplbmRvYmoKeHJlZgowIDIKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDA5IDAwMDAwIG4gCnRyYWlsZXIgPDwgL1NpemUgMiA+PgpzdGFydHhyZWYKODQKJSVFT0YK', 'base64');
const lying = await analyzePdf(lyingLength);
equal(lying.revisions[0].text.length, 0, 'a stream with a lying /Length yields no text');
equal(lying.revisions[0].skipped.map(item => [item.object, item.code]), [[1, 'STREAM_LENGTH']], 'the skipped stream is reported by object and reason');
check(lying.revisions[0].skipped[0].message.includes('999'), 'the skipped-stream reason quotes the declared length');
equal(result.revisions.map(revision => revision.skipped.length), [1, 1, 1], 'the anchor also reports its own uninspectable stream rather than passing it over');

// Content tokenizing must always advance. Any of these bodies looped forever and exhausted
// memory before the tokenizer was made to make progress on every delimiter.
const markedContent = await analyzePdf(contentPdf('/Span << /MCID 0 >> BDC BT /F1 12 Tf 10 10 Td (payroll) Tj ET EMC'));
equal(markedContent.revisions[0].text.map(item => item.text), ['payroll'], 'a marked-content dictionary in a page stream is tokenized, not looped on');
equal((await analyzePdf(contentPdf('BT /F1 12 Tf 10 10 Td (payroll) Tj ET >'))).revisions[0].text.map(item => item.text), ['payroll'], 'a stray > terminates');
equal((await analyzePdf(contentPdf('BT /F1 12 Tf 10 10 Td (payroll) Tj ET )'))).revisions[0].text.map(item => item.text), ['payroll'], 'a stray ) terminates');
equal((await analyzePdf(contentPdf('BT /F1 12 Tf 10 10 Td (payroll) Tj ET << >> < > ] ['))).revisions[0].text.map(item => item.text), ['payroll'], 'mixed stray delimiters terminate');
const tokenCapped = await analyzePdf(contentPdf('BT /F1 12 Tf 10 10 Td (payroll) Tj ET ' + '0 0 1 1 re n '.repeat(200)), { limits: { contentTokens: 40 } });
check(tokenCapped.revisions[0].skipped.some(item => item.code === 'TOKEN_CEILING'), 'reaching the token ceiling is disclosed, not silent');
equal(tokenCapped.choices.contentTokenCeiling, 40, 'the token ceiling in force is disclosed');

// Inline image samples are not operators. Tokenizing them invents rectangles.
const inlineImage = await analyzePdf(contentPdf('BT /F1 12 Tf 10 10 Td (payroll) Tj ET q 0 g BI /W 4 /H 4 ID 8 8 60 16 re f EI Q'));
equal(inlineImage.revisions[0].covers.length, 0, 'bytes inside an inline image do not become a paint candidate');

// The re-derivation reports three legal 20-byte entry terminators. Two were already tested.
function classicSpaceCrPdf() {
  const prefix = '%PDF-1.4\n1 0 obj\n<< /Type /Catalog >>\nendobj\n';
  const offset = prefix.length;
  return bytes(`${prefix}xref\n0 2\n0000000000 65535 f \r${String(prefix.indexOf('1 0 obj')).padStart(10, '0')} 00000 n \rtrailer << /Size 2 >>\nstartxref\n${offset}\n%%EOF\n`);
}
equal((await analyzePdf(classicSpaceCrPdf())).revisions.length, 1, 'strict mode accepts conforming 20-byte space-CR xref rows');

// Boundary grammar, built rather than pasted.
function catalogPdf(afterTrailer, extraTail = '') {
  const header = '%PDF-1.4\n';
  const object = '1 0 obj\n<< /Type /Catalog >>\nendobj\n';
  const xrefAt = header.length + object.length;
  const section = `xref\n0 2\n0000000000 65535 f \n${String(header.length).padStart(10, '0')} 00000 n \ntrailer << /Size 2 >>\n${afterTrailer(xrefAt)}`;
  return { bytes: bytes(header + object + section + extraTail(xrefAt)), xrefAt };
}
const junkBoundary = catalogPdf(() => 'JUNK\n', at => `startxref\n${at}\n%%EOF\n`);
await refusal(junkBoundary.bytes, 'BOUNDARY_MISSING', {}, { names: [String(junkBoundary.xrefAt)] });
const wrongTarget = catalogPdf(() => 'startxref\n0\n%%EOF\n', at => `startxref\n${at}\n%%EOF\n`);
await refusal(wrongTarget.bytes, 'BOUNDARY_TARGET', {}, { names: ['prints 0'] });
const commentBoundary = catalogPdf(at => `%a conforming comment\nstartxref\n${at}\n%%EOF\n`, () => '');
equal((await analyzePdf(commentBoundary.bytes)).revisions.length, 1, 'a comment between the trailer and startxref is still a boundary');

// The linearized shape: two linked sections, zero updates. The discriminator is that a real
// update sits after what it points back to.
function forwardPrevPdf() {
  const header = '%PDF-1.4\n';
  const object = '1 0 obj\n<< /Type /Catalog >>\nendobj\n';
  const firstAt = header.length + object.length;
  const firstSection = mainAt => `xref\n0 2\n0000000000 65535 f \n${String(header.length).padStart(10, '0')} 00000 n \ntrailer << /Size 2 /Prev ${String(mainAt).padStart(6, '0')} >>\nstartxref\n${firstAt}\n%%EOF\n`;
  const mainAt = (header + object + firstSection(0)).length;
  const mainSection = `xref\n0 2\n0000000000 65535 f \n${String(header.length).padStart(10, '0')} 00000 n \ntrailer << /Size 2 >>\nstartxref\n${firstAt}\n%%EOF\n`;
  return { bytes: bytes(header + object + firstSection(mainAt) + mainSection), firstAt, mainAt };
}
const forward = forwardPrevPdf();
check(forward.mainAt > forward.firstAt, 'the forward-Prev specimen really does point from an earlier section to a later one');
await refusal(forward.bytes, 'NOT_APPEND_ORDERED', {}, { offset: forward.firstAt, names: [String(forward.mainAt)] });

// Two revisions where the second covers the first revision's own words. The whole claim,
// on a specimen with more than one section, which the shipped anchor never exercises
// because it has no paint at all.
function twoRevisionCoverPdf() {
  const first = 'BT /F1 12 Tf 10 10 Td (payroll) Tj ET';
  const second = 'BT /F1 12 Tf 10 10 Td (payroll) Tj ET 0 g 8 8 60 16 re f';
  const header = '%PDF-1.4\n';
  const objectA = `1 0 obj\n<< /Length ${first.length} >>\nstream\n${first}\nendstream\nendobj\n`;
  const xrefA = header.length + objectA.length;
  const sectionA = `xref\n0 2\n0000000000 65535 f \n${String(header.length).padStart(10, '0')} 00000 n \ntrailer << /Size 2 >>\nstartxref\n${xrefA}\n%%EOF\n`;
  const revisionOne = header + objectA + sectionA;
  const objectB = `1 0 obj\n<< /Length ${second.length} >>\nstream\n${second}\nendstream\nendobj\n`;
  const xrefB = revisionOne.length + objectB.length;
  const sectionB = `xref\n0 1\n0000000000 65535 f \n1 1\n${String(revisionOne.length).padStart(10, '0')} 00000 n \ntrailer << /Size 2 /Prev ${xrefA} >>\nstartxref\n${xrefB}\n%%EOF\n`;
  return { bytes: bytes(revisionOne + objectB + sectionB), revisionOneEnd: revisionOne.length, xrefs: [xrefA, xrefB] };
}
const twoRevision = twoRevisionCoverPdf();
const covering = await analyzePdf(twoRevision.bytes);
equal(covering.sections.map(section => section.offset), twoRevision.xrefs, 'two-revision cover specimen xref offsets');
equal(covering.revisions.map(revision => revision.sliceEnd), [twoRevision.revisionOneEnd, twoRevision.bytes.length], 'two-revision cover specimen slice ends');
equal(covering.revisions.map(revision => revision.covers.length), [0, 1], 'the covering rectangle exists only in the newer revision');
equal(covering.revisions[0].text.map(item => item.text), ['payroll'], 'the earlier revision holds the same words uncovered');
equal(covering.revisions[1].covers[0].text, 'payroll', 'the newer revision names the covered string');
equal(covering.revisions[1].changes.find(change => change.object === 1).action, 'superseded', 'the newer section supersedes object 1');
equal(covering.standalone.passed, 2, 'both slices of the two-revision specimen re-parse alone');
equal(covering.revisions.map(revision => revision.unresolvedCount), [0, 0], 'every winner in the two-revision specimen resolves');

// The vacuity the re-derivation named: the ordinary check for this claim is "is the string
// in the file", which returns true whether the rectangle covers the text or sits under it.
// Operator order is the instrument that separates them, so it has to be tested both ways.
const paintedOver = contentPdf('BT /F1 12 Tf 10 10 Td (payroll) Tj ET 0 g 8 8 60 16 re f');
const paintedUnder = contentPdf('0 g 8 8 60 16 re f BT /F1 12 Tf 10 10 Td (payroll) Tj ET');
check(Buffer.from(paintedOver).includes(Buffer.from('payroll')) && Buffer.from(paintedUnder).includes(Buffer.from('payroll')), 'the naive string-in-file test cannot tell the two apart');
equal((await analyzePdf(paintedOver)).revisions[0].covers.length, 1, 'a rectangle painted after the text is a candidate');
equal((await analyzePdf(paintedUnder)).revisions[0].covers.length, 0, 'the same rectangle painted before the text is not');

// The standalone slice re-parse is the check that a comparison of a prefix with itself
// cannot make. It has to be able to fail.
equal(result.standalone.passed, 3, 'all three anchor slices re-parse alone into their own section counts');
equal(result.standalone.results.map(item => item.status), ['pass', 'pass', 'pass'], 'anchor standalone statuses');
// The truncation offset is taken from the file's own chain, never from a remembered length,
// and a truncation wrong by two bytes does not survive an independent parse. That is what
// separates this from comparing a prefix with itself.
equal((await analyzePdf(pdf.subarray(0, result.revisions[0].sliceEnd - 1))).revisions[0].sliceEnd, 16033, 'the trailing line ending after %%EOF is optional');
await refusal(pdf.subarray(0, result.revisions[0].sliceEnd - 2), 'NO_EOF_BOUNDARY', {}, { offset: 16012 });
await refusal(pdf.subarray(0, result.revisions[0].sliceEnd - 22), 'NO_STARTXREF', {}, { offset: 0 });
equal((await analyzePdf(pdf, { limits: { sliceRecheckBytes: 1000 } })).standalone.attempted, 0, 'the recheck ceiling reports not attempted rather than a silent pass');
equal((await analyzePdf(pdf, { limits: { sliceRecheckBytes: 1000 } })).standalone.results.map(item => item.status), ['not attempted', 'not attempted', 'not attempted'], 'an unattempted recheck is labelled, never counted as passed');

// Every refusal path the parser can reach, asserted by code and by the byte it reports.
// Before this block nine of the parser's codes were asserted and the rest were reachable
// but untested, which meant most of the instrument's failure behaviour was unmeasured.
function xrefStreamWith(dictionary, record, { keyword = 'stream', eol = '\n', trailingObj = true } = {}) {
  const prefix = bytes('%PDF-1.5\n');
  const offset = prefix.length;
  const before = bytes(`1 0 obj\n${dictionary}\n${keyword}${eol}`);
  const after = bytes(`\nendstream\n${trailingObj ? 'endobj\n' : ''}startxref\n${offset}\n%%EOF\n`);
  const out = new Uint8Array(prefix.length + before.length + record.length + after.length);
  out.set(prefix, 0);
  out.set(before, prefix.length);
  out.set(record, prefix.length + before.length);
  out.set(after, prefix.length + before.length + record.length);
  return out;
}
const goodRecord = new Uint8Array([0, 0, 0, 0, 0, 255, 255, 1, 0, 0, 0, 9, 0, 0]);
function classicWith(body) {
  const prefix = '%PDF-1.4\n1 0 obj\n<< /Type /Catalog >>\nendobj\n';
  const offset = prefix.length;
  return { bytes: bytes(prefix + body(offset, prefix)), offset };
}

await refusal(pdf, 'TOO_LARGE', { limits: { inputBytes: 4096 } }, { offset: 0, names: ['4096'] });
await refusal(classicPdf(), 'OBJECT_LIMIT', { limits: { objects: 1 } }, { names: ['1'] });
await refusal(twoRevision.bytes, 'SECTION_LIMIT', { limits: { sections: 1 } });
await refusal(pdf, 'WORK_LIMIT', { limits: { workMs: -1 } });
{
  const specimen = classicWith((offset, prefix) => `xref\n0 2\n0000000000 65535 f \n${String(prefix.indexOf('1 0 obj')).padStart(10, '0')} 00000 n \ntrailer << /Size 2 /Prev 999999 >>\nstartxref\n${offset}\n%%EOF\n`);
  await refusal(specimen.bytes, 'PREV_RANGE', {}, { names: ['999999'] });
}
{
  const specimen = classicWith(offset => `xref\nnot a subsection\ntrailer << /Size 2 >>\nstartxref\n${offset}\n%%EOF\n`);
  await refusal(specimen.bytes, 'XREF_SUBSECTION', {}, { names: ['not a subsection'] });
}
{
  const specimen = classicWith((offset, prefix) => `xref\n0 4\n0000000000 65535 f \n${String(prefix.indexOf('1 0 obj')).padStart(10, '0')} 00000 n \nstartxref\n${offset}\n%%EOF\n`);
  await refusal(specimen.bytes, 'XREF_ENTRY', {}, { names: ['object 2'] });
}
{
  const specimen = classicWith((offset, prefix) => `xref\n0 2\n0000000000 65535 f \n${String(prefix.indexOf('1 0 obj')).padStart(10, '0')} 00000 n \n1 2\n0000000000 65535 f \n0000000000 65535 f \ntrailer << /Size 3 >>\nstartxref\n${offset}\n%%EOF\n`);
  await refusal(specimen.bytes, 'XREF_OVERLAP');
}
{
  // The xref sits at the very end with no trailer after it, so the entries loop runs off
  // the end of the file. A fixed-width offset keeps the layout stable while it is computed.
  const prefix = '%PDF-1.4\n1 0 obj\n<< /Type /Catalog >>\nendobj\n';
  const shell = at => `${prefix}startxref\n${String(at).padStart(6, '0')}\n%%EOF\nxref\n0 1\n0000000000 65535 f \n`;
  const xrefAt = shell(0).indexOf('xref\n0 1');
  const built = bytes(shell(xrefAt));
  equal(new TextDecoder().decode(built.subarray(xrefAt, xrefAt + 4)), 'xref', 'trailer-missing specimen puts an xref table at the computed offset');
  await refusal(built, 'TRAILER_MISSING', {}, { offset: xrefAt });
}
{
  const deep = `<< /Size 2 ${'<< '.repeat(10)}${'>> '.repeat(10)}>>`;
  const specimen = classicWith((offset, prefix) => `xref\n0 2\n0000000000 65535 f \n${String(prefix.indexOf('1 0 obj')).padStart(10, '0')} 00000 n \ntrailer ${deep}\nstartxref\n${offset}\n%%EOF\n`);
  await refusal(specimen.bytes, 'NESTING_LIMIT', { limits: { nesting: 4 } });
}
{
  const specimen = classicWith((offset, prefix) => `xref\n0 2\n0000000000 65535 f \n${String(prefix.indexOf('1 0 obj')).padStart(10, '0')} 00000 n \ntrailer << /Size 2 /XRefStm ${offset} >>\nstartxref\n${offset}\n%%EOF\n`);
  await refusal(specimen.bytes, 'HYBRID_TARGET');
}
await refusal(xrefStreamWith('<< /Type /XRef /Size 2 /W [1 4] /Length 14 >>', goodRecord), 'XREF_W');
await refusal(xrefStreamWith('<< /Type /XRef /Size 2 /W [1 4 2] /Index [0] /Length 14 >>', goodRecord), 'XREF_INDEX');
await refusal(xrefStreamWith('<< /Type /XRef /Size 2 /W [1 4 2] /Index [0 2 0 2] /Length 28 >>', new Uint8Array([...goodRecord, ...goodRecord])), 'XREF_DUPLICATE');
await refusal(xrefStreamWith('<< /Type /XRef /Size 2 /W [1 4 2] /Length 14 >>', new Uint8Array([5, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 9, 0, 0])), 'XREF_TYPE', {}, { names: ['type 5'] });
await refusal(xrefStreamWith('<< /Type /XRef /Size 1 /W [1 8 2] /Length 11 >>', new Uint8Array([1, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0])), 'INTEGER_OVERFLOW');
await refusal(xrefStreamWith('<< /Type /XRef /Size 2 /W [1 4 2] /Length 7 >>', goodRecord.subarray(0, 7)), 'XREF_TRUNCATED');
await refusal(xrefStreamWith('<< /Type /XRef /Size 2 /W [1 4 2] /Filter /LZWDecode /Length 14 >>', goodRecord), 'FILTER_UNSUPPORTED', {}, { names: ['/LZWDecode'] });
await refusal(xrefStreamWith('<< /Type /XRef /Size 2 /W [1 4 2] /Filter /FlateDecode /Length 14 >>', goodRecord), 'FLATE_DECODE');
await refusal(xrefStreamWith('<< /Type /XRef /Size 2 /W [1 4 2] /Filter /ASCIIHexDecode /Length 3 >>', bytes('zz>')), 'ASCIIHEX_DECODE');
await refusal(xrefStreamWith('<< /Type /XRef /Size 2 /W [1 4 2] /Length 14 >>', goodRecord, { keyword: 'stream', eol: ' ' }), 'STREAM_EOL');
await refusal(xrefStreamWith('<< /Type /XRef /Size 2 /W [1 4 2] /Length 14 >>', goodRecord, { keyword: 'streem' }), 'STREAM_KEYWORD');
await refusal(xrefStreamWith('<< /Type /XRef /Size 2 /W [1 4 2] /Length 14', goodRecord), 'DICTIONARY_TRUNCATED');
await refusal(xrefStreamWith('/Type /XRef', goodRecord), 'DICTIONARY_EXPECTED');
await refusal(xrefStreamWith('<< /Type /ObjStm /Size 2 /W [1 4 2] /Length 14 >>', goodRecord), 'STARTXREF_TARGET', {}, { names: ['/Type /ObjStm'] });
{
  const hex = bytes('0000000000FFFF01000000090000>');
  await refusal(xrefStreamWith(`<< /Type /XRef /Size 2 /W [1 4 2] /Filter /ASCIIHexDecode /Length ${hex.length} >>`, hex), 'DECODE_LIMIT', { limits: { decodedBytes: 4 } });
  equal((await analyzePdf(xrefStreamWith(`<< /Type /XRef /Size 2 /W [1 4 2] /Filter /ASCIIHexDecode /Length ${hex.length} >>`, hex))).sections[0].filter, ['ASCIIHexDecode'], 'the same ASCIIHexDecode xref stream is accepted under the shipped ceiling');
}
// FlateDecode has to actually work, and it has to work without touching anything the
// document's own connect-src 'none' policy forbids. Draining the decompressed stream
// through Response or fetch decoded every compressed PDF correctly in Node and failed on
// every one of them in the browser, where the page's own policy applies.
{
  const { deflateSync, deflateRawSync } = await import('node:zlib');
  for (const [label, compress] of [['zlib', deflateSync], ['raw deflate', deflateRawSync]]) {
    const payload = new Uint8Array(compress(Buffer.from(goodRecord)));
    const specimen = xrefStreamWith(`<< /Type /XRef /Size 2 /W [1 4 2] /Filter /FlateDecode /Length ${payload.length} >>`, payload);
    const inflated = await analyzePdf(specimen);
    equal(inflated.sections[0].entryCount, 2, `a ${label} FlateDecode xref stream decodes to its two entries`);
    equal(inflated.revisions[0].winners.find(entry => entry.object === 1).offset, 9, `a ${label} FlateDecode xref stream yields the right offset`);
  }
  const core = await readFile(join(publicDir, 'pdf-core.mjs'), 'utf8');
  check(!/new Response\(/.test(core) && !/\bfetch\(/.test(core), 'the parser never drains a decoded stream through a mechanism connect-src blocks');
  check(core.includes('new DecompressionStream(format)') && core.includes('readable.getReader()'), 'decompression reads the stream directly');
  check(core.includes("'deflate'") && core.includes("'deflate-raw'"), 'both deflate framings are attempted');
}
// FILTER_UNAVAILABLE needs a runtime with no DecompressionStream and cannot be reached here.
check(typeof DecompressionStream === 'function', 'this runtime has a deflate decoder, so FILTER_UNAVAILABLE stays unreachable and is reported as untested');

const html = await readFile(htmlPath, 'utf8');
const markdown = await readFile(markdownPath, 'utf8');
check(html.startsWith('<!doctype html>'), 'doctype is first');
check(html.trimEnd().endsWith('</html>'), 'load-bearing html close exists');
check(/<\/script>\s*<\/body>\s*<\/html>\s*$/s.test(html), 'load-bearing script, body, and html closes are ordered');
equal((html.match(/<script type="application\/ld\+json">/g) || []).length, 1, 'one JSON-LD block');
const jsonText = html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/)[1];
const jsonLd = JSON.parse(jsonText);
equal(jsonLd['@type'], 'Article', 'JSON-LD Article type');
equal(jsonLd.name, expectedSeo, 'JSON-LD search name');
equal(jsonLd.headline, 'What Your PDF Still Remembers', 'JSON-LD headline');
equal(jsonLd.description, expectedDek, 'JSON-LD description is the vetted dek');
equal(jsonLd.datePublished, '2026-08-09T00:00:00Z', 'JSON-LD publication date');
equal(html.match(/<title>([^<]+)<\/title>/)[1], expectedSeo, 'HTML title equals seoTitle');
equal(metaContent(html, 'name="description"'), expectedDek, 'meta description equals dek');
check(metaContent(html, 'property="og:description"').includes('no chain proves no edit'), 'OG concession survives the share surface');
// The body says the counters and the policy cannot prove the browser, an extension or the
// operating system is benign. A share card promising the file never leaves the device
// claims more than the page can support, so the share card says what was actually enforced.
const twitter = metaContent(html, 'name="twitter:description"');
check(twitter.includes('makes no network request that carries it'), 'Twitter privacy claim states what the page enforces');
check(!/never leaves your device/i.test(html), 'no share surface promises more containment than the body concedes');
check(metaContent(html, 'name="aw-plain"').includes('No links does not mean no editing'), 'plain-language concession is in the HTML');
check(html.includes("connect-src 'none'"), 'CSP blocks connections');
check(html.includes("form-action 'none'"), 'CSP blocks form submission');
check(html.includes("object-src 'none'"), 'CSP blocks embedded objects');
check(html.includes('17,370') && html.includes('13,801 · 16,059 · 16,940'), 'reader-visible anchor figures are present');
check(html.includes('Potato 0 → Potato 0 new'), 'reader-visible content change is present');
check(html.includes('does not certify safe redaction'), 'central negative claim is visible');
check(html.includes('not a human edit log'), 'edit-log concession is visible');
check(html.includes('No chain proves nothing'), 'absence concession is visible');
check(html.includes('inspectable containment evidence'), 'privacy evidence is correctly scoped');
check(html.includes('Disclosed change after seeing data'), 'the rules changed after seeing data are disclosed on the page');
check(html.includes('160 and 344'), 'the disclosed change names the specimen that forced it');
check(html.includes('Linked is not appended'), 'the linearized shape is named as a chain that is not an update');
check(html.includes('BOUNDARY_TARGET') && html.includes('NOT_APPEND_ORDERED') && html.includes('NO_EOF_BOUNDARY'), 'the new refusal codes are listed for the reader');
check(html.includes('shall be a direct object'), 'the corrected /Prev definition is cited');
check(html.includes('unverified claims, not as definitions that won'), 'unresolved winners are explained in the body');
check(html.includes('compared with itself would agree no matter what'), 'the vacuous comparison is named where the frames are');
check(html.includes('a check that cannot fail is decoration'), 'the scored and unscored split is explained in the check panel');
check(/id="compare-note"/.test(html) && /id="skipped-status"/.test(html), 'the comparison note and skipped-stream surfaces exist');
check((html.match(/<th>/g) || []).length >= 9, 'the object table carries its resolution column');

equal(markdown.match(/dek: "([^"]+)"/)[1], expectedDek, 'frontmatter dek');
equal(markdown.match(/plain: "([^"]+)"/)[1], expectedPlain, 'frontmatter plain');
equal(markdown.match(/seoTitle: "([^"]+)"/)[1], expectedSeo, 'frontmatter seoTitle');
check(markdown.includes('date: 2026-08-09T00:00:00Z'), 'frontmatter binding date');
check(markdown.includes('seam: "commons"'), 'frontmatter binding seam');
check(markdown.includes('"the specimen is yours"'), 'wave tag is present');
check(markdown.includes('"show-the-check"'), 'show-the-check tag is present');
equal((markdown.match(/^  - to:/gm) || []).length, 4, 'four substantive relates edges');
check(markdown.includes('draft: false'), 'stratum is published');

// Every element the page script reaches for has to exist in the document it ships with.
const pageSource = await readFile(join(publicDir, 'page.mjs'), 'utf8');
const wantedIds = [...new Set([...pageSource.matchAll(/\$\('#([A-Za-z0-9_-]+)'\)/g)].map(match => match[1]))];
check(wantedIds.length >= 20, 'the page script addresses the document by id');
const documentIds = new Set([...html.matchAll(/\bid="([A-Za-z0-9_-]+)"/g)].map(match => match[1]));
equal(wantedIds.filter(id => !documentIds.has(id)), [], 'every id the page script reads exists in the shipped HTML');
check(/class="render-card"[^>]*>\s*<div class="frame-label" id="frame-right-label"/.test(html), 'the second frame really sits inside the card the script hides for one-section files');
equal(refusalRecord(new Error('not a parser refusal')).code, 'INTERNAL', 'a non-parser error is reported as INTERNAL rather than as a structural claim');
equal(refusalRecord(new PdfRefusal('X', 'y', 7, 'z')).offset, 7, 'a parser refusal keeps its byte offset for display');
check(documentIds.has('refusal-offset') && pageSource.includes("$('#refusal-offset')"), 'the refusal surface displays the byte offset the parser reported');

const externalLoads = [];
for (const match of html.matchAll(/<(?:script|img|iframe|link)\b[^>]*(?:src|href)="([^"]+)"/gi)) {
  const value = match[1];
  if (/^https?:\/\//i.test(value) && !value.startsWith('https://artwaste.land/')) externalLoads.push(value);
}
equal(externalLoads, [], 'no third-party src or stylesheet resource');
check(!/fetch\s*\(\s*['"]https?:\/\//.test(html), 'no remote fetch literal in HTML');
// The earlier scan looked only at resource tags in the HTML, so a remote request made from
// any shipped module would have passed it. This walks every module the page loads.
const shippedModules = ['page.mjs', 'worker.mjs', 'pdf-core.mjs', 'fallback-data.mjs'];
for (const name of shippedModules) {
  const source = await readFile(join(publicDir, name), 'utf8');
  const remote = [...source.matchAll(/https?:\/\/[^\s'"`)]+/g)].map(match => match[0]);
  equal(remote, [], `${name} contains no remote URL`);
  check(!/\bimportScripts\s*\(/.test(source), `${name} does not pull in another script at runtime`);
  check(!/new\s+Image\s*\(/.test(source), `${name} does not build an image element that could carry bytes in a URL`);
}
const pageBody = pageSource.slice(pageSource.indexOf('function armPrivacy'));
for (const mechanism of ['fetch(', 'XMLHttpRequest', 'WebSocket', 'EventSource', 'sendBeacon', 'navigator.connection']) {
  check(!pageBody.includes(mechanism), `no ${mechanism} outside the counter installation`);
}
check(/url\(/.test(html) === false || !/url\(\s*['"]?https?:/i.test(html), 'no stylesheet URL reaches off origin');
check(!/connect-src[^"]*(?:\*|https?:)/.test(html), 'connect-src names no origin at all');

const publicFiles = await readdir(publicDir);
for (const name of publicFiles.filter(name => /\.(?:html|mjs|js|txt)$/.test(name))) {
  const source = await readFile(join(publicDir, name), 'utf8');
  check(!source.includes(forbiddenDash), `${name} has no em dash`);
}
check(!markdown.includes(forbiddenDash), 'frontmatter has no em dash');
const readme = await readFile(join(here, 'README.md'), 'utf8');
check(!readme.includes(forbiddenDash), 'research README has no em dash');
check(!String(await readFile(fileURLToPath(import.meta.url), 'utf8')).includes(forbiddenDash), 'verifier has no em dash');

console.log(`PASS ${checks} assertions`);
console.log(`anchor ${result.fileLength} bytes, SHA-256 ${expectedHash}`);
console.log(`xref ${result.sections.map(section => section.offset).join(' -> ')}`);
console.log(`EOF ${result.revisions.map(revision => revision.eofStart).join(' -> ')}`);
console.log('content Potato 0 -> Potato 0 new');
