import { readFile } from 'node:fs/promises' import { describe, expect, it } from 'vitest' import { SCORE_TREE, analyzeDocument, countWords, extractLinks, scoreEntity, scoreTreeDocument, stripMarkup, } from './scoring.mjs' const here = (name) => new URL(name, import.meta.url) function round(value, places = 6) { return typeof value === 'number' ? Number(value.toFixed(places)) : value } function roundDeep(value) { if (Array.isArray(value)) return value.map(roundDeep) if (value && typeof value === 'object') { return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, roundDeep(child)])) } return round(value) } describe('the scoring core', () => { it('has no imports, so a port can take the file on its own', async () => { const source = await readFile(here('./scoring.mjs'), 'utf8') expect(source).not.toMatch(/^\s*import\s/m) }) it('keeps the metrics facade pointing at the same functions', async () => { const metrics = await import('./metrics.mjs') const scoring = await import('./scoring.mjs') for (const name of [ 'analyzeDocument', 'factorValues', 'SCORE_TREE', 'treeScore', 'percentileRanks', ]) { expect(metrics[name]).toBe(scoring[name]) } }) it('exports the tree and every node has a single-entity bound', () => { const tree = scoreTreeDocument() expect(tree.categories).toHaveLength(SCORE_TREE.categories.length) for (const category of tree.categories) { expect(category.id).toBeTruthy() expect(Number.isFinite(category.weight)).toBe(true) for (const factor of category.factors) { expect(factor.id).toBeTruthy() expect(Number.isFinite(factor.weight)).toBe(true) expect(['clamp', 'divide', 'none']).toContain(factor.bound) } } }) it('refuses a factor with no declared bound', () => { const tree = { categories: [ { id: 'test', name: 'test', icon: 'test', weight: 1, factors: [{ id: 'unmapped', name: 'unmapped', weight: 1, scale: 'x' }], }, ], } expect(() => scoreTreeDocument(tree)).toThrow(/missing bounds/) }) }) describe('prose word counts', () => { const words = (text) => countWords(stripMarkup(text)) it('drops image and link URLs but keeps the words around them', () => { expect(words('Before ![a cat](https://example.com/cat.png) after')).toBe(4) expect(words('Before [the post](https://example.com/post) after')).toBe(4) expect(words('Before cat after')).toBe(2) expect(words('Before https://example.com/post after')).toBe(2) expect(words('Before at://did:plc:x/app.bsky.feed.post/1 after')).toBe(2) }) it('drops reference definitions, footnotes, and HTML comments', () => { expect(words('Before [the post][ref] after\n\n[ref]: https://example.com')).toBe(4) expect(words('Before[^1] after\n\n[^1]: note')).toBe(3) expect(words('Before after')).toBe(2) expect(words('Before after')).toBe(2) expect(words('Before after')).toBe(2) }) it('counts an image alt but not an empty image', () => { expect(words('![cat](https://example.com/cat.png)')).toBe(1) expect(words('![](https://example.com/cat.png)')).toBe(0) }) it('keeps link extraction separate from the prose count', () => { const entry = analyzeDocument({ textContent: '![cat](https://images.example.com/cat.png) [post](https://example.com/post)', }) expect(entry.words).toBe(2) expect(entry.linkUrls).not.toContain('https://images.example.com/cat.png') expect(entry.linkUrls).toContain('https://example.com/post') }) }) describe('representative Markdown', () => { const words = (text) => countWords(stripMarkup(text)) const markdown = [ '# Heading', '', 'A [source](https://example.com/source) and a bare link https://example.org/bare.', '', '![A cat](https://images.example.com/cat.png)', '', '[![Linked image](https://images.example.com/dog.png)](https://example.com/linked)', '', 'html', 'anchor', '', '', '`[not a link](https://example.com/inline)`', '', '```md', '[also not a link](https://example.com/fenced)', '```', '', '[ref link][ref] and ![ref image][img]', '', '[ref]: https://example.com/ref', '[img]: https://images.example.com/ref.png', '', 'Footnote[^note].', '', '[^note]: prose note', ].join('\n') it('counts clickable links and skips image embeds, code, and image references', () => { expect(new Set(extractLinks({ textContent: markdown }, markdown))).toEqual( new Set([ 'https://example.com/source', 'https://example.org/bare', 'https://example.com/linked', 'https://example.com/html-link', 'https://example.com/ref', ]), ) }) it('skips image blocks in structured content but keeps link facets', () => { const record = { content: { items: [ { $type: 'blog.pckt.block.image', attrs: { src: 'https://images.example.com/cat.png' }, }, { $type: 'blog.pckt.block.image', href: 'https://example.com/clicked-image', attrs: { src: 'https://images.example.com/dog.png' }, }, { $type: 'blog.pckt.block.link', uri: 'https://example.com/source' }, ], }, } expect(extractLinks(record, '').sort()).toEqual([ 'https://example.com/clicked-image', 'https://example.com/source', ]) }) it('keeps footnote prose but drops fenced code', () => { const prose = stripMarkup(markdown) expect(prose).toContain('prose note') expect(prose).not.toContain('also not a link') expect(prose).not.toContain('images.example.com') expect(words('```\n[code](https://example.com/code)\n```')).toBe(0) expect(countWords('`inline` prose')).toBe(2) }) }) describe('score-tree.json', () => { it('matches SCORE_TREE exactly', async () => { const checked = JSON.parse(await readFile(here('./score-tree.json'), 'utf8')) expect(checked).toEqual(scoreTreeDocument()) }) }) describe('single-entity scoring', () => { const now = Date.parse('2026-10-26T00:00:00.000Z') it('keeps raw and bounded values apart from the cohort score', () => { const result = scoreEntity( { publishedAt: '2026-10-25T00:00:00.000Z', textContent: 'A short note that links to https://example.org/source.', }, { now, publicationHost: 'example.com', stansiteHosts: ['example.org'] }, ) expect(result.cohort).toMatchObject({ percentiles: null, score: null }) expect(result.raw.reach).toBe(0) expect(result.raw.recommends).toBe(0) expect(result.bounded.reach).toBeNull() expect(result.bounded.recommends).toBeNull() expect(result.raw.freshness).toBeCloseTo(Math.exp(-1 / 90), 6) expect(result.bounded.freshness).toBeCloseTo(result.raw.freshness, 6) expect(result.weights).toHaveLength(SCORE_TREE.categories.length) expect(result.notes.recency).toContain('Absolute') expect(result.notes.unbounded).toEqual( expect.arrayContaining(['reach', 'recommends', 'volume']), ) for (const value of Object.values(result.bounded)) { if (value !== null) expect(value).toBeGreaterThanOrEqual(0) if (value !== null) expect(value).toBeLessThanOrEqual(1) } }) it('treats a thread as one entity', () => { const result = scoreEntity( [ { publishedAt: '2026-10-20T00:00:00.000Z', textContent: 'First post in a thread.' }, { publishedAt: '2026-10-21T00:00:00.000Z', textContent: 'Second post in a thread.' }, ], { now }, ) expect(result.metrics.docCount).toBe(2) expect(result.metrics.wordCount).toBeGreaterThan(0) }) }) describe('document parity fixture', () => { it('matches the checked-in document metrics and factor values', async () => { const fixture = JSON.parse(await readFile(here('./fixtures/document-parity.json'), 'utf8')) const wordFrequency = Object.assign( {}, ...(await Promise.all( [1, 2].map(async (part) => JSON.parse(await readFile(here(`./word-zipf-en-${part}.json`), 'utf8')), ), )), ) const digest = () => fixture.digest const options = { now: Date.parse(fixture.now), digest, wordFrequency, publicationHost: fixture.scoreOptions.publicationHost, stansiteHosts: new Set(fixture.scoreOptions.stansiteHosts), } for (const item of fixture.documents) { const entry = analyzeDocument(item.record, { digest, wordFrequency }) expect( roundDeep({ words: entry.words, tokens: entry.tokens, publishedAt: entry.publishedAt, tags: entry.tags, linkUrls: entry.linkUrls, atprotoRefs: entry.atprotoRefs, embeds: entry.embeds, readability: entry.readability, lexical: entry.lexical, style: entry.style, structure: entry.structure, }), ).toEqual(item.expected.document) const scored = scoreEntity(item.record, options) expect(roundDeep(scored.raw)).toEqual(item.expected.raw) expect(roundDeep(scored.bounded)).toEqual(item.expected.bounded) } }) })