Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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/
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,8 @@
"oxlint": "catalog:",
"smol-toml": "1.9.1",
"typescript": "catalog:"
},
"dependencies": {
"badge-maker": "6.0.0"
}
}
57 changes: 57 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion scripts/lib/api-destinations.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
145 changes: 145 additions & 0 deletions scripts/lib/badges.mjs
Original file line number Diff line number Diff line change
@@ -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 `/<service>/v/<package>` 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 = /^(.+?)(?<!-)-(?!-)(.+?)(?<!-)-(?!-)([^-]+)$/.exec(segments.slice(1).join('/'))
if (!match) throw new Error(`${port}: unsupported static badge ${url}`)
const [, label, message, color] = match
return { label: query.label ?? unescapeStatic(label), message: unescapeStatic(message), color: query.color ?? color }
}
if (VERSION_SERVICES[segments[0]] && segments[1] === 'v' && segments.length === 3) {
const version = registryVersion(registry, port, decodeURIComponent(segments[2]))
return { label: query.label ?? VERSION_SERVICES[segments[0]], message: addV(version), color: query.color ?? versionColor(version) }
}
throw new Error(`${port}: unsupported badge ${url}; add a mapping to scripts/lib/badges.mjs`)
}

let cachedRegistry
export function readRegistry() {
cachedRegistry ??= JSON.parse(readFileSync(join(root, 'site/src/data/registry.json'), 'utf8'))
return cachedRegistry
}

/**
* Rewrite badge images in `content`. Returns the new Markdown and the SVG
* files to publish, keyed by `badges/<hash>.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
})
}
21 changes: 16 additions & 5 deletions scripts/stage-port-docs.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -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.`,
Expand Down Expand Up @@ -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()
7 changes: 6 additions & 1 deletion site/src/plugins/rehype-site-root.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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}`
})
}
}
Loading
Loading