diff --git a/.gitignore b/.gitignore index 49c0e2a16..f02f9da67 100644 --- a/.gitignore +++ b/.gitignore @@ -29,3 +29,4 @@ site/src/content/docs/_staged/ # comparison fails, and never removes it. Committed, they outlive the failure # they document and read as a difference that is still there. site/test/baselines/*.diff.png +site/public/badges/ diff --git a/package.json b/package.json index 28d8c5e9e..f3321168e 100644 --- a/package.json +++ b/package.json @@ -32,5 +32,8 @@ "oxlint": "catalog:", "smol-toml": "1.9.1", "typescript": "catalog:" + }, + "dependencies": { + "badge-maker": "6.0.0" } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 764501d53..ae949e3db 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -201,6 +201,10 @@ patchedDependencies: importers: .: + dependencies: + badge-maker: + specifier: 6.0.0 + version: 6.0.0 devDependencies: '@biomejs/biome': specifier: 'catalog:' @@ -1632,6 +1636,9 @@ packages: resolution: {integrity: sha512-KLcsDhqf1XRrJmJr+9I/C0EX2K+sGrAGZFgkmd84c8TJO9zJBu+/kFInjazu1KfJWFhWDKdRWkpBzEs7s35DVA==} hasBin: true + anafanafo@2.0.0: + resolution: {integrity: sha512-Nlfq7NC4AOkTJerWRIZcOAiMNtIDVIGWGvQ98O7Jl6Kr2Dk0dX5u4MqN778kSRTy5KRqchpLdF2RtLFEz9FVkQ==} + ansi-regex@6.4.0: resolution: {integrity: sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==} engines: {node: '>=12'} @@ -1681,12 +1688,20 @@ packages: resolution: {integrity: sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==} engines: {node: '>= 0.4'} + badge-maker@6.0.0: + resolution: {integrity: sha512-+P5EsfmFWAR2cA9M0q20pa4OVOgnOXZkfRYUkQYHanECXCIg10ZnSBzelfBtEjt03b4Vac/yC1h55/wJPLmaOg==} + engines: {node: '>=20'} + hasBin: true + bail@2.0.2: resolution: {integrity: sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==} bcp-47-match@2.0.3: resolution: {integrity: sha512-JtTezzbAibu8G0R9op9zb3vcWZd9JF6M0xOYGPn0fNCd7wOpRB1mU2mH9T8gaBGbAAyIIVgB2G7xG0GP98zMAQ==} + binary-search@1.3.6: + resolution: {integrity: sha512-nbE1WxOTTrUWIfsfZ4aHGYu5DOuNkbxGokjV6Z2kxfJK3uaAb8zNK1muzOeipoLHZjInT4Br88BHpzevc681xA==} + boolbase@1.0.0: resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==} @@ -1701,6 +1716,9 @@ packages: resolution: {integrity: sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==} engines: {node: '>=18'} + char-width-table-consumer@1.0.0: + resolution: {integrity: sha512-Fz4UD0LBpxPgL9i29CJ5O4KANwaMnX/OhhbxzvNa332h+9+nRKyeuLw4wA51lt/ex67+/AdsoBQJF3kgX2feYQ==} + character-entities-html4@2.1.0: resolution: {integrity: sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==} @@ -1738,6 +1756,12 @@ packages: collapse-white-space@2.1.0: resolution: {integrity: sha512-loKTxY1zCOuG4j9f6EPnuyyYkf58RnhhWTvRoZEokgB+WbdXehfjFviyOVYkqzEWz1Q5kRiZdBYS5SwxbQYwzw==} + color-convert@0.5.3: + resolution: {integrity: sha512-RwBeO/B/vZR3dfKL1ye/vx8MHZ40ugzpyfeVG5GsiuGnrlMWe2o8wxBbLCpw9CsxV+wHuzYlCiWnybrIA0ling==} + + color-name@1.1.4: + resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} + comma-separated-tokens@2.0.3: resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==} @@ -1759,6 +1783,9 @@ packages: crossws@0.3.5: resolution: {integrity: sha512-ojKiDvcmByhwa8YYqbQI/hg7MEU0NC03+pSdEq4ZUnZR9xXpwk7E43SMNGkn+JxJGPFtNvQ48+vV2p+P1ml5PA==} + css-color-converter@2.0.0: + resolution: {integrity: sha512-oLIG2soZz3wcC3aAl/7Us5RS8Hvvc6I8G8LniF/qfMmrm7fIKQ8RIDDRZeKyGL2SrWfNqYspuLShbnjBMVWm8g==} + css-select@6.0.0: resolution: {integrity: sha512-rZZVSLle8v0+EY8QAkDWrKhpgt6SA5OtHsgBnsj6ZaLb5dmDVOWUDtQitd9ydxxvEjhewNudS6eTVU7uOyzvXw==} @@ -1773,6 +1800,9 @@ packages: resolution: {integrity: sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==} engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0} + css-unit-converter@1.1.2: + resolution: {integrity: sha512-IiJwMC8rdZE0+xiEZHeru6YoONC4rfPMqGm2W85jMIbkFvv5nFTwJVFHam2eFrN6txmoUYFAFXiv8ICVeTO0MA==} + css-what@7.0.0: resolution: {integrity: sha512-wD5oz5xibMOPHzy13CyGmogB3phdvcDaB5t0W/Nr5Z2O/agcB8YwOz6e2Lsp10pNDzBoDO9nVa3RGs/2BttpHQ==} engines: {node: '>= 6'} @@ -4373,6 +4403,10 @@ snapshots: dependencies: process-ancestry: 0.1.0 + anafanafo@2.0.0: + dependencies: + char-width-table-consumer: 1.0.0 + ansi-regex@6.4.0: {} ansi-styles@6.2.3: {} @@ -4490,10 +4524,17 @@ snapshots: axobject-query@4.1.0: {} + badge-maker@6.0.0: + dependencies: + anafanafo: 2.0.0 + css-color-converter: 2.0.0 + bail@2.0.2: {} bcp-47-match@2.0.3: {} + binary-search@1.3.6: {} + boolbase@1.0.0: {} buffer-image-size@0.6.4: @@ -4504,6 +4545,10 @@ snapshots: chai@6.3.0: {} + char-width-table-consumer@1.0.0: + dependencies: + binary-search: 1.3.6 + character-entities-html4@2.1.0: {} character-entities-legacy@3.0.0: {} @@ -4534,6 +4579,10 @@ snapshots: collapse-white-space@2.1.0: {} + color-convert@0.5.3: {} + + color-name@1.1.4: {} + comma-separated-tokens@2.0.3: {} commander@11.1.0: {} @@ -4548,6 +4597,12 @@ snapshots: dependencies: uncrypto: 0.1.3 + css-color-converter@2.0.0: + dependencies: + color-convert: 0.5.3 + color-name: 1.1.4 + css-unit-converter: 1.1.2 + css-select@6.0.0: dependencies: boolbase: 1.0.0 @@ -4568,6 +4623,8 @@ snapshots: mdn-data: 2.27.1 source-map-js: 1.2.2 + css-unit-converter@1.1.2: {} + css-what@7.0.0: {} cssesc@3.0.0: {} diff --git a/scripts/lib/api-destinations.mjs b/scripts/lib/api-destinations.mjs index 6957c0dad..0a0b01013 100644 --- a/scripts/lib/api-destinations.mjs +++ b/scripts/lib/api-destinations.mjs @@ -369,7 +369,8 @@ export function proseSources({ root = ROOT, meta = false } = {}) { } for (const port of SOURCE_GUIDE_PORTS) { const artifact = readJson(join(root, 'site', 'src', 'data', 'port-guides', `${port}.json`)) - for (const [file, source] of stagedPortGuides(port, artifact)) pages.push(entry(`_staged/${file}`, source)) + // Badge SVGs ride in the same map for the stager to publish; they are not pages. + for (const [file, source] of stagedPortGuides(port, artifact)) if (!file.startsWith('badges/')) pages.push(entry(`_staged/${file}`, source)) } // A page a port writes for itself keeps its id; the shared source fills the ids no page claims. const claimed = new Set(pages.map((page) => page.id)) diff --git a/scripts/lib/badges.mjs b/scripts/lib/badges.mjs new file mode 100644 index 000000000..969abafa6 --- /dev/null +++ b/scripts/lib/badges.mjs @@ -0,0 +1,145 @@ +/** + * Render README badges from data the build already holds. + * + * Source guides hotlink img.shields.io and GitHub Actions badges, so every + * reader's browser (and every CI browser check) waits on a third party. This + * maps each shields URL to a label, message and colour, renders the SVG with + * shields' own `badge-maker`, and points the Markdown image at a + * content-hashed file served from the site's origin. + */ +import { createHash } from 'node:crypto' +import { existsSync, readFileSync } from 'node:fs' +import { basename, dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { makeBadge } from 'badge-maker' +import { fromMarkdown } from 'mdast-util-from-markdown' +import { toMarkdown } from 'mdast-util-to-markdown' + +const root = join(dirname(fileURLToPath(import.meta.url)), '../..') +export const BADGE_DIRECTORY = 'badges' + +/** Registries whose `//v/` badge reports a published version. */ +const VERSION_SERVICES = { + gem: 'gem', + crates: 'crates.io', + npm: 'npm', + nuget: 'nuget', + powershellgallery: 'powershell gallery', + pypi: 'pypi', +} + +const OFF_ORIGIN = /^https?:\/\/(?:img\.shields\.io|badgen\.net|badge\.fury\.io|(?:www\.)?github\.com\/[^/]+\/[^/]+\/(?:actions\/workflows\/[^/]+|workflows\/[^/]+)\/badge\.svg|github\.com\/[^/]+\/[^/]+\/workflows\/.*\/badge\.svg)/i + +export function isOffOriginBadge(url) { + return OFF_ORIGIN.test(url) +} + +/** Every off-origin badge URL in staged Markdown or HTML, whatever syntax holds it. */ +export function findOffOriginBadges(content) { + return [...content.matchAll(/https?:\/\/[^\s)"'<>]+/g)].map((match) => match[0]).filter(isOffOriginBadge) +} + +/** shields static-badge escaping: `--` is a dash, `__` an underscore, `_` a space. */ +function unescapeStatic(part) { + return decodeURIComponent(part).split('--').map((piece) => piece.split('__').map((word) => word.replaceAll('_', ' ')).join('_')).join('-') +} + +function registryVersion(registry = readRegistry(), port, name) { + const entry = registry.ports[port] + const version = entry?.packages?.[name]?.version ?? (entry?.packages ? undefined : entry?.version) + if (!version) throw new Error(`${port}: badge names package ${name}, which the registry data does not carry`) + return version +} + +/** + * Version colour as shields picks it (`version` in services/color-formatters.js + * at server-2026-08-21, commit 080e177a0a44): orange when the first digit is 0 + * or the string names a pre-release, blue otherwise. PyPI badges use shields' + * PEP 440 variant, which differs only for strings no registry entry here holds. + */ +function versionColor(version) { + const first = version.startsWith('v') ? version[1] : version[0] + return first === '0' || /alpha|beta|snapshot|dev|pre|rc|scm|cvs/i.test(version) ? '#ea7233' : '#007ec6' +} + +/** shields' `addv`: a version that already starts with `v` keeps it. */ +function addV(version) { + return version.startsWith('v') ? version : `v${version}` +} + +/** Resolve one shields URL to badge-maker input, or `null` for a status badge to drop. */ +export function badgeSpec(url, { port, registry }) { + const parsed = new URL(url) + if (parsed.hostname !== 'img.shields.io') { + if (parsed.pathname.endsWith('/badge.svg')) return null + throw new Error(`${port}: unsupported badge host ${parsed.hostname}`) + } + const query = Object.fromEntries(parsed.searchParams) + const unsupported = Object.keys(query).filter((key) => !['label', 'color'].includes(key)) + if (unsupported.length) throw new Error(`${port}: unsupported badge parameter ${unsupported.join(',')} in ${url}`) + const segments = parsed.pathname.split('/').filter(Boolean) + if (segments[0] === 'badge') { + const match = /^(.+?)(?.svg`. Status badges are dropped + * with their link: their value is a live CI result the build cannot know. + */ +export function localizeBadges(content, port, registry) { + const files = new Map() + const edits = [] + const visit = (node, parent) => { + if (node.type === 'image' && isOffOriginBadge(node.url)) { + const spec = badgeSpec(node.url, { port, registry }) + const droppable = parent?.type === 'link' && parent.children.length === 1 ? parent : node + if (!spec) { + edits.push({ start: droppable.position.start.offset, end: droppable.position.end.offset, text: '' }) + return + } + const svg = makeBadge({ label: spec.label, message: spec.message, color: spec.color }) + const name = `${BADGE_DIRECTORY}/${createHash('sha256').update(svg).digest('hex').slice(0, 12)}.svg` + files.set(name, svg) + node.url = `/${name}` + node.alt = node.alt || `${spec.label}: ${spec.message}` + edits.push({ start: node.position.start.offset, end: node.position.end.offset, text: toMarkdown(node).trimEnd() }) + return + } + for (const child of node.children ?? []) visit(child, node) + } + visit(fromMarkdown(content), undefined) + for (const { start, end, text } of edits.sort((a, b) => b.start - a.start)) { + content = content.slice(0, start) + text + content.slice(end) + } + return { content, files } +} + +/** + * Whether any badge among the staged `files` is missing from `directory` or + * holds other bytes. Badge files are content-hashed and shared by every port, + * so a port-scoped staging leaves other ports' files in place: extras in the + * directory are not stale. + */ +export function badgesStale(files, directory) { + return [...files].some(([name, svg]) => { + if (!name.startsWith(`${BADGE_DIRECTORY}/`)) return false + const path = join(directory, basename(name)) + return !existsSync(path) || readFileSync(path, 'utf8') !== svg + }) +} diff --git a/scripts/stage-port-docs.mjs b/scripts/stage-port-docs.mjs index 6b1dd24e1..b0d2aface 100644 --- a/scripts/stage-port-docs.mjs +++ b/scripts/stage-port-docs.mjs @@ -11,9 +11,12 @@ import { PORTS } from '../site/src/lib/ports.ts' import { defaultVersionFor, linkedVersionFor } from '../site/src/lib/versions.ts' import { sourceGuidesFor, sourceGuideRedirectsFor, stagedSectionsFor, SOURCE_GUIDE_PORTS } from '../site/src/lib/port-documentation.ts' import { SymbolIndex, parameterId } from '../packages/api-model/src/link.ts' +import { BADGE_DIRECTORY, badgesStale, localizeBadges } from './lib/badges.mjs' const root = resolve(dirname(fileURLToPath(import.meta.url)), '..') const output = join(root, 'site/src/content/docs/_staged') +// Badge SVGs are content-hashed, so every build publishes the same bytes at the same path. +const badgeOutput = join(root, 'site/public', BADGE_DIRECTORY) const selectedPort = process.argv.includes('--port') ? process.argv[process.argv.indexOf('--port') + 1] : undefined const check = process.argv.includes('--check') const fromSource = process.argv.includes('--from-source') @@ -172,7 +175,9 @@ export function stagedPortGuides(port, artifact) { const linked = port === 'fsharp' && sourcePath === 'docs/fsharp/supported-query-fields.md' ? linkSnapshotDepths(body) : body const nativeLinked = port === 'julia' ? linkDocumenter(linked, artifact.source) : linked - const rewritten = rewriteLinks(nativeLinked, sourcePath, route, linkRoutes, artifact.source.repository, artifact.source.revision, nativeReferenceFiles) + const { content: badged, files: badgeFiles } = localizeBadges(nativeLinked, port) + for (const [name, svg] of badgeFiles) files.set(name, svg) + const rewritten = rewriteLinks(badged, sourcePath, route, linkRoutes, artifact.source.repository, artifact.source.revision, nativeReferenceFiles) const data = { title, description: guide.description ?? `${title}: ${identity.packageName} documentation.`, @@ -352,20 +357,26 @@ export function run() { } } walk(output) - const stale = generated.size !== actual.size || [...generated].some(([file, content]) => actual.get(file) !== content) + const isBadge = (file) => file.startsWith(`${BADGE_DIRECTORY}/`) + const guides = [...generated].filter(([file]) => !isBadge(file)) + const badgeStale = badgesStale(generated, badgeOutput) + const stale = badgeStale || guides.length !== actual.size || guides.some(([file, content]) => actual.get(file) !== content) if (stale) throw new Error('staged port guides are missing or stale; rerun without --check') } else { if (selectedPort || wrappersOnly) { for (const port of selected) rmSync(join(output, port.slug), { recursive: true, force: true }) - } else rmSync(output, { recursive: true, force: true }) + } else { + rmSync(output, { recursive: true, force: true }) + rmSync(badgeOutput, { recursive: true, force: true }) + } for (const [file, content] of generated) { - const destination = join(output, file) + const destination = file.startsWith(`${BADGE_DIRECTORY}/`) ? join(badgeOutput, posix.basename(file)) : join(output, file) mkdirSync(dirname(destination), { recursive: true }) writeFileSync(destination, content) } } - console.log(`stage-port-docs: ${generated.size} guides from ${selected.map((port) => port.slug).join(',')}`) + console.log(`stage-port-docs: ${[...generated.keys()].filter((file) => !file.startsWith(`${BADGE_DIRECTORY}/`)).length} guides from ${selected.map((port) => port.slug).join(',')}`) } if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) run() diff --git a/site/src/plugins/rehype-site-root.mjs b/site/src/plugins/rehype-site-root.mjs index 7136e9e54..873b6d5b4 100644 --- a/site/src/plugins/rehype-site-root.mjs +++ b/site/src/plugins/rehype-site-root.mjs @@ -31,7 +31,12 @@ export function rehypeSiteRoot() { if (typeof value !== 'string' || !value.startsWith('/') || value.startsWith('//')) return const owner = typeof node.properties.dataDocPort === 'string' ? node.properties.dataDocPort : port const version = owner === buildPort ? buildTarget(process.env).version : (defaults[owner] || 'latest') - node.properties[attr] = attr === 'href' ? proseHref(value, root, owner, version, portRoot) : `${root}${value}` + // Badge SVGs ship in every shell's own `public/`, so a port build serves + // its guides' badges from its own mount and never depends on the root + // build having published the same content hash. + const ownMount = attr === 'src' && value.startsWith('/badges/') && owner === buildPort + node.properties[attr] = attr === 'href' ? proseHref(value, root, owner, version, portRoot) + : ownMount ? `${portRoot}/${owner}/${version}${value}` : `${root}${value}` }) } } diff --git a/site/test/port-guide-badges.test.ts b/site/test/port-guide-badges.test.ts new file mode 100644 index 000000000..c8e9e5ea9 --- /dev/null +++ b/site/test/port-guide-badges.test.ts @@ -0,0 +1,137 @@ +import { createMarkdownProcessor } from '@astrojs/markdown-remark' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { badgesStale, findOffOriginBadges, localizeBadges } from '../../scripts/lib/badges.mjs' +import { stagedPortGuides } from '../../scripts/stage-port-docs.mjs' + +const registry = { ports: { ruby: { version: '0.1.0', packages: { libtmux: { version: '0.1.0' }, 'libtmux-async': { version: '1.2.0' } } } } } +const guideCache = join(import.meta.dirname, '../src/data/port-guides') +const cached = readdirSync(guideCache).map((file) => file.replace(/\.json$/, '')) + +describe('staged guides serve badges from the site origin', () => { + it.each(cached)('%s guides hold no off-origin badge', (port) => { + const artifact = JSON.parse(readFileSync(join(guideCache, `${port}.json`), 'utf8')) + const staged = stagedPortGuides(port, artifact) + expect([...staged].filter(([file]) => !file.startsWith('badges/')).flatMap(([, text]) => findOffOriginBadges(text))).toEqual([]) + }) + + it('flags a guide that brings its own badge (negative control)', () => { + expect(findOffOriginBadges('[![x](https://img.shields.io/badge/a-b-blue)](https://example.com)')).toHaveLength(1) + expect(findOffOriginBadges('')).toHaveLength(1) + expect(findOffOriginBadges('[![x](/badges/abc.svg)](https://rubygems.org/gems/libtmux)')).toEqual([]) + }) +}) + +describe('pages outside the guide cache', () => { + it('embed no off-origin badge', () => { + const walk = (directory: string): string[] => readdirSync(directory, { withFileTypes: true }) + .flatMap((entry) => entry.isDirectory() ? walk(join(directory, entry.name)) : [join(directory, entry.name)]) + const content = join(import.meta.dirname, '../src/content') + expect(walk(content).filter((file) => /\.mdx?$/.test(file)).flatMap((file) => findOffOriginBadges(readFileSync(file, 'utf8')).map((url) => `${file}: ${url}`))).toEqual([]) + }) +}) + +describe('localizeBadges', () => { + it('renders a static badge with its label, message, colour and link', () => { + const { content, files } = localizeBadges('[![docs](https://img.shields.io/badge/docs-libtmux.org-0b7285)](https://libtmux.org/)', 'ruby', registry) + expect(content).toMatch(/^\[!\[docs\]\(\/badges\/[0-9a-f]{12}\.svg\)\]\(https:\/\/libtmux\.org\/\)$/) + const [svg] = [...files.values()] + expect(svg).toContain('aria-label="docs: libtmux.org"') + expect(svg).toContain('fill="#0b7285"') + }) + + it('takes a registry version from staged data and colours a pre-1.0 release orange', () => { + const { files } = localizeBadges('![libtmux](https://img.shields.io/gem/v/libtmux?label=libtmux)', 'ruby', registry) + expect([...files.values()][0]).toContain('aria-label="libtmux: v0.1.0"') + expect([...files.values()][0]).toContain('#ea7233') + const stable = localizeBadges('![a](https://img.shields.io/gem/v/libtmux-async)', 'ruby', registry).files + expect([...stable.values()][0]).toContain('aria-label="gem: v1.2.0"') + expect([...stable.values()][0]).toContain('#007ec6') + }) + + it.each([ + ['0.62.0', '#ea7233'], + ['0.1.0-1', '#ea7233'], + ['1.0.0', '#007ec6'], + ['10.2.0', '#007ec6'], + ['1.0.0-rc.1', '#ea7233'], + ['2.0.0-beta.3', '#ea7233'], + ['3.1.0-SNAPSHOT', '#ea7233'], + ['v0.1.0', '#ea7233'], + ['v1.4.0', '#007ec6'], + ])('colours version %s as shields does (%s)', (version, colour) => { + const data = { ports: { ruby: { version, packages: { libtmux: { version } } } } } + const [svg] = localizeBadges('![a](https://img.shields.io/gem/v/libtmux)', 'ruby', data).files.values() + expect(svg).toContain(`fill="${colour}"`) + expect(svg).toContain(`aria-label="gem: ${version.startsWith('v') ? version : `v${version}`}"`) + }) + + it('does not double the v of a registry version that has one', () => { + const [svg] = localizeBadges('![a](https://img.shields.io/gem/v/x)', 'go', { ports: { go: { packages: { x: { version: 'v0.1.0' } } } } }).files.values() + expect(svg).toContain('aria-label="gem: v0.1.0"') + expect(svg).not.toContain('vv0.1.0') + }) + + it('is deterministic and shares one file between identical badges', () => { + const text = '![a](https://img.shields.io/badge/license-MIT-blue) ![b](https://img.shields.io/badge/license-MIT-blue)' + const first = localizeBadges(text, 'ruby', registry) + expect(first.files.size).toBe(1) + expect(localizeBadges(text, 'ruby', registry).content).toBe(first.content) + }) + + it('drops a CI status badge and its link', () => { + const { content } = localizeBadges('[![ci](https://github.com/o/r/actions/workflows/ci.yml/badge.svg)](https://github.com/o/r/actions/workflows/ci.yml) after', 'ruby', registry) + expect(content).toBe(' after') + }) + + it('refuses a badge it cannot render rather than hotlinking it', () => { + expect(() => localizeBadges('![x](https://img.shields.io/github/stars/o/r)', 'ruby', registry)).toThrow(/unsupported badge/) + expect(() => localizeBadges('![x](https://img.shields.io/gem/v/missing)', 'ruby', registry)).toThrow(/registry data does not carry/) + }) +}) + +describe('stage --check compares badge files', () => { + let directory = '' + beforeEach(() => { directory = mkdtempSync(join(tmpdir(), 'libtmux-badges-')) }) + afterEach(() => rmSync(directory, { recursive: true, force: true })) + const files = new Map([['badges/abc123abc123.svg', 'a']]) + + it('is stale when a badge file is missing or holds other bytes, and clean when it matches', () => { + expect(badgesStale(files, directory)).toBe(true) + writeFileSync(join(directory, 'abc123abc123.svg'), 'other') + expect(badgesStale(files, directory)).toBe(true) + writeFileSync(join(directory, 'abc123abc123.svg'), 'a') + expect(badgesStale(files, directory)).toBe(false) + }) + + it('ignores guide files and badge files that belong to other ports', () => { + writeFileSync(join(directory, 'abc123abc123.svg'), 'a') + writeFileSync(join(directory, 'other-port.svg'), 'b') + expect(badgesStale(new Map([...files, ['ruby/index.md', '# x']]), directory)).toBe(false) + }) +}) + +describe('badge URLs in a rendered guide', () => { + afterEach(() => vi.unstubAllEnvs()) + + const render = async (port: string) => { + vi.stubEnv('LIBTMUX_DOCS_PORT', port) + vi.stubEnv('LIBTMUX_DOCS_VERSION', 'latest') + vi.stubEnv('LIBTMUX_DOCS_ROOT', '') + vi.stubEnv('LIBTMUX_DOCS_PORT_ROOT', '') + vi.resetModules() + const { rehypeSiteRoot } = await import('../src/plugins/rehype-site-root.mjs') + const processor = await createMarkdownProcessor({ rehypePlugins: [rehypeSiteRoot], syntaxHighlight: false }) + return (await processor.render('![x](/badges/abc.svg)', { frontmatter: { port: 'ruby' } })).code + } + + it('serves a port build\'s badges from its own mount', async () => { + expect(await render('ruby')).toContain('src="/ruby/latest/badges/abc.svg"') + }) + + it('serves badges from the root when no port is being built', async () => { + expect(await render('')).toContain('src="/badges/abc.svg"') + }) +}) diff --git a/site/test/stage-port-docs.outer.test.ts b/site/test/stage-port-docs.outer.test.ts index 7c7ab8f4f..f50e85a0d 100644 --- a/site/test/stage-port-docs.outer.test.ts +++ b/site/test/stage-port-docs.outer.test.ts @@ -8,7 +8,7 @@ import { PORTS } from '../src/lib/ports.ts' const root = new URL('../../', import.meta.url).pathname const cachedRevision = 'a'.repeat(40) -const files = ['scripts/stage-port-docs.mjs', 'site/src/lib/ports.ts', +const files = ['scripts/stage-port-docs.mjs', 'scripts/lib/badges.mjs', 'site/src/lib/ports.ts', 'site/src/lib/site-root.ts', 'site/src/lib/cooldown.ts', 'site/src/lib/port-documentation.ts', 'site/src/lib/versions.ts'] const stagedPorts = ['ruby', 'lua', 'powershell', 'julia', 'elixir', 'kotlin', 'scala', 'fsharp']