Files
iptvnator/tools/release/release-notes-render.mjs
T
4grayandClaude Opus 5 270350c2e1 chore(release): author release notes in .changes instead of reconstructing them (#1256)
* chore(release): author release notes in .changes instead of reconstructing them

CHANGELOG.md has been frozen at 0.12.0 since 2023 while the app shipped
0.23.0, semantic-release sat in devDependencies with no config, and the real
user-facing notes were a 280-line MDX post written from memory at release
time. The gap was never version math — it was authored notes captured while
the context is still fresh.

Add a `.changes/*.md` note format (type, area, issues, screenshot; no version
field, since the release version is chosen deliberately) plus a generator that
composes the GitHub release body, the CHANGELOG.md section and a blog-post
scaffold from the accumulated notes.

Changesets was considered and rejected: it versions multiple published
packages, and this repo has exactly one private package. Its `version` step
would also rewrite CHANGELOG.md into a flatter format than the blog post and
fight the deliberate, updater-constrained version choice.

- hand-rolled frontmatter parser over a YAML engine: the schema is closed, so
  it can reject unknown keys, which is what catches typos
- PR numbers are resolved from the commit that added the note, never written
  by the author
- MDX-significant characters in note bodies are escaped so a stray `<` cannot
  break the website build
- blog scaffold ships `draft: true` with explicit TODO headings; the prose is
  editorial work, only the inventory is mechanical
- revive CHANGELOG.md with an honest pointer for 0.13.0-0.23.0 rather than
  fabricating the missing history
- drop the five unused semantic-release/conventional-changelog packages

Docs: `.changes/README.md`, plus a "Release Notes For User-Visible Changes"
section mirrored in CLAUDE.md and AGENTS.md, and a PR template checkbox for
contributors who never read either.

Tests: 26 unit tests in tools/release/release-notes.test.mjs covering parsing,
validation, grouping and all three renderers.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(release): default the notes version to package.json and harden alt escaping

Review follow-ups on the release-notes generator.

- `--version` now defaults to the root package.json version, so the
  `release🎶*` package scripts run bare instead of failing on a missing
  argument. Bumping package.json is the deliberate act that starts a release,
  which makes it the right single source of truth; `--version` remains as an
  override for dry runs before the bump. The notice goes to stderr so
  `--format github` keeps a pipeable stdout.
- Escape backslashes before apostrophes when building the MDX `alt` string
  literal. A note body ending in a backslash previously produced an
  unterminated string and would have broken the website build.
- Document that release posts are one per minor version, in the slug helper,
  the overwrite error, and `.changes/README.md` — a patch release edits the
  existing post rather than creating a second one.

Tests: +1 regression test for the alt escaping, verified to fail without the
fix (27 total, all passing).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(ci): put authored notes into the tag release body, fail-closed

Wires the .changes pipeline into the release workflow (Codex review P1 on
#1256). Calling the generator from the tag build cannot work — --consume
deletes .changes/ before the tag exists — so the tag build reads what the
generator already wrote: release-meta now fills BODY from the CHANGELOG.md
section matching the tag's version via tools/release/extract-changelog-section.mjs.

generate_release_notes stays on, so GitHub's commit list renders below the
authored notes; the existing draft-metadata repair step already concatenates
RELEASE_BODY with the generated notes, so the rare duplicate-draft path keeps
the same layering unchanged.

The extractor exits non-zero when the section is missing or empty, failing
the release instead of silently shipping PR-title-only notes. A hotfix tag
cut without running release:notes:changelog therefore fails at create-release
by design; the error message names the exact commands to run.

Tests: 5 new extractor tests (32 total in release-tools, all passing);
packaging suite (247) re-run green since build-and-make.yaml is one of its
inputs.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(release): escape all regex metacharacters in the changelog extractor

CodeQL flagged the version-to-RegExp interpolation in
extract-changelog-section.mjs (regex injection + incomplete escaping): only
dots were escaped, and while the CLI validates its argument as bare semver
before calling, the exported extractSection() carries no such guarantee on
its own. Escape the full metacharacter set so no caller can inject pattern
syntax, with tests covering wildcard dots, alternation, `.*` and backslashes.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(release): make changelog generation idempotent per version

Codex review P2 on #1256: rerunning `release:notes:changelog` for the same
version — the normal move after correcting a note before --consume —
prepended a second section instead of replacing the first, leaving duplicate
release entries.

Extract the marker insertion into upsertChangelogSection(): it removes any
existing section for the version, then rebuilds around the marker rather than
string-replacing into it, so the blank-line count on both sides stays exact
on both the fresh-insert and replace paths. The CLI reports when a section
was replaced.

Tests: 4 new cases (insert, replace-not-duplicate, neighbours untouched,
missing marker); 37 total passing. End-to-end rerun verified: one heading,
latest date wins, extractor output unchanged.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-07-25 18:22:43 +02:00

325 lines
10 KiB
JavaScript

/**
* Renderers turning grouped `.changes/*.md` notes into the three release
* surfaces: the GitHub release body, the CHANGELOG.md section, and the
* website blog scaffold.
*/
import { extractSection } from './extract-changelog-section.mjs';
import { groupNotes, REPO_URL } from './release-notes.mjs';
const MONTHS = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
];
/**
* @param {string} isoDate `YYYY-MM-DD`
* @returns {string} e.g. `August 1, 2026`
*/
export function formatLongDate(isoDate) {
const [year, month, day] = isoDate.split('-').map(Number);
return `${MONTHS[month - 1]} ${day}, ${year}`;
}
/**
* Deliberately minor-scoped: the website publishes one release post per minor
* version (`v0-18` … `v0-22`), and its screenshot assets live under the same
* directory. A patch release therefore reuses its minor's post rather than
* starting a new one.
*
* @param {string} version
* @returns {string} e.g. `v0-24` for both `0.24.0` and `0.24.1`
*/
export function releaseSlug(version) {
const [major, minor] = version.split('.');
return `v${major}-${minor}`;
}
/** Collapses a note body to a single line for list entries. */
function oneLine(body) {
return body.replace(/\s+/g, ' ').trim();
}
/** Trims to a word boundary; used for image alt text, never for prose. */
function truncate(text, max) {
if (text.length <= max) {
return text;
}
const cut = text.slice(0, max);
const lastSpace = cut.lastIndexOf(' ');
return `${(lastSpace > max / 2 ? cut.slice(0, lastSpace) : cut).trimEnd()}…`;
}
/**
* MDX parses `<` and `{` as markup. Note bodies are plain prose written by
* humans and agents, so escape them rather than letting a stray character
* break the website build. The closing counterparts are escaped too, so a
* body like `<live>` renders as written instead of half-escaped.
*/
function escapeMdx(text) {
return text
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/\{/g, '&#123;')
.replace(/\}/g, '&#125;');
}
/**
* @param {object} note
* @param {Map<string, { pr?: number, commit?: string }>} links
* @returns {string} trailing `([#123](url), closes [#45](url))` or ''
*/
function formatReferences(note, links) {
const parts = [];
const link = links.get(note.sourcePath);
if (link?.pr) {
parts.push(`[#${link.pr}](${REPO_URL}/pull/${link.pr})`);
} else if (link?.commit) {
parts.push(
`[${link.commit.slice(0, 7)}](${REPO_URL}/commit/${link.commit})`
);
}
for (const issue of note.issues) {
parts.push(`closes [#${issue}](${REPO_URL}/issues/${issue})`);
}
return parts.length > 0 ? ` (${parts.join(', ')})` : '';
}
function formatEntry(note, links) {
return `- **${note.area}** — ${oneLine(note.body)}${formatReferences(note, links)}`;
}
/**
* GitHub release body. `internal` notes are omitted: the release page is read
* by users, and GitHub still appends its own full commit list below.
*
* @param {object[]} notes
* @param {{ links?: Map<string, object> }} [options]
* @returns {string}
*/
export function renderGithubBody(notes, { links = new Map() } = {}) {
const sections = groupNotes(notes)
.filter((group) => group.type !== 'internal')
.map((group) => {
const entries = group.notes
.map((note) => formatEntry(note, links))
.join('\n');
return `## ${group.heading}\n\n${entries}`;
});
return sections.join('\n\n');
}
/**
* CHANGELOG.md section. Unlike the release body this keeps `internal` notes,
* collapsed, so the file stays a complete record.
*
* @param {object[]} notes
* @param {{ version: string, date: string, previousVersion?: string | null, links?: Map<string, object> }} options
* @returns {string}
*/
export function renderChangelogSection(
notes,
{ version, date, previousVersion = null, links = new Map() }
) {
const heading = previousVersion
? `# [${version}](${REPO_URL}/compare/v${previousVersion}...v${version}) (${date})`
: `# ${version} (${date})`;
const blocks = [heading];
for (const group of groupNotes(notes)) {
const entries = group.notes
.map((note) => formatEntry(note, links))
.join('\n');
if (group.type === 'internal') {
blocks.push(
`<details>\n<summary>Internal changes</summary>\n\n${entries}\n\n</details>`
);
continue;
}
blocks.push(`### ${group.heading}\n\n${entries}`);
}
return `${blocks.join('\n\n')}\n`;
}
/**
* Inserts a version section below the marker, replacing any existing section
* for the same version — rerunning `--format changelog` after correcting a
* note must not prepend a duplicate.
*
* @param {string} changelog full CHANGELOG.md content
* @param {string} section rendered section (from renderChangelogSection)
* @param {string} version bare semver the section describes
* @param {string} marker insertion marker line
* @returns {{ content: string, replaced: boolean }}
*/
export function upsertChangelogSection(changelog, section, version, marker) {
if (!changelog.includes(marker)) {
throw new Error(
`changelog is missing the \`${marker}\` marker that new sections are inserted below`
);
}
let current = changelog;
const replaced = extractSection(current, version) !== null;
if (replaced) {
const lines = current.split('\n');
const headingIndex = lines.findIndex(
(line) =>
line.startsWith(`# [${version}]`) ||
line.startsWith(`# ${version} `)
);
let end = lines.length;
for (let index = headingIndex + 1; index < lines.length; index += 1) {
if (/^#\s/.test(lines[index])) {
end = index;
break;
}
}
current = [...lines.slice(0, headingIndex), ...lines.slice(end)].join(
'\n'
);
}
// Rebuild around the marker instead of string-replacing into it, so the
// blank-line count on both sides of the section stays exact regardless of
// whether a removal just happened.
const markerIndex = current.indexOf(marker);
const before = current.slice(0, markerIndex);
const after = current
.slice(markerIndex + marker.length)
.replace(/^\n+/, '');
return {
content: `${before}${marker}\n\n${section.trim()}\n\n${after}`,
replaced,
};
}
/**
* Blog entries carrying a `screenshot:` slug become their own subsection with
* an image slider; the rest stay bullets.
*/
function renderBlogGroup(group, { slug, links }) {
const bullets = group.notes.filter((note) => !note.screenshot);
const featured = group.notes.filter((note) => note.screenshot);
const blocks = [`## ${group.heading}`];
if (bullets.length > 0) {
blocks.push(
bullets
.map(
(note) =>
`- **${note.area}** — ${escapeMdx(oneLine(note.body))}${formatReferences(note, links)}`
)
.join('\n')
);
}
for (const note of featured) {
// The heading is editorial work — a note body makes a terrible one.
// Leave a visible TODO instead of pretending otherwise; the whole
// scaffold ships as `draft: true` anyway.
// Embedded in a single-quoted JS string inside MDX. Backslashes must
// be escaped before apostrophes, or a body ending in `\` produces an
// unterminated string and breaks the website build.
const alt = truncate(oneLine(note.body), 120)
.replace(/\\/g, '\\\\')
.replace(/'/g, "\\'");
const images = ['dark', 'light']
.map(
(theme) =>
` {\n src: '/iptvnator/blog/${slug}/screenshots/${note.screenshot}-${theme}.png',\n alt: '${alt}',\n },`
)
.join('\n');
blocks.push(`### TODO headline (${note.area})`);
blocks.push(
`${escapeMdx(oneLine(note.body))}${formatReferences(note, links)}`
);
blocks.push(`<BlogImageSlider\n images={[\n${images}\n ]}\n/>`);
}
return blocks.join('\n\n');
}
/**
* Scaffold for `apps/website/src/content/blog/v0-24-release-notes.mdx`.
* Deliberately incomplete: `draft: true`, TODO markers for the narrative and
* description. The prose is editorial work, only the inventory is mechanical.
*
* @param {object[]} notes
* @param {{ version: string, date: string, links?: Map<string, object> }} options
* @returns {string}
*/
export function renderBlogScaffold(notes, { version, date, links = new Map() }) {
const slug = releaseSlug(version);
const shortVersion = slug.replace('-', '.');
const sections = groupNotes(notes)
.filter((group) => group.type !== 'internal')
.map((group) => renderBlogGroup(group, { slug, links }));
const frontmatter = [
'---',
`title: ${shortVersion} - Release Notes`,
'description: TODO — one sentence naming the two or three headline changes.',
'featured: true',
`pubDate: ${date}`,
'author: 4gray',
`heroImage: /iptvnator/blog/${slug}/hero.jpg`,
'tags:',
' - release',
' - release-notes',
` - ${shortVersion}`,
'draft: true',
'---',
].join('\n');
const imports = [
"import BlogImageSlider from '../../components/blog/BlogImageSlider.astro';",
"import ReleaseMeta from '../../components/blog/ReleaseMeta.astro';",
].join('\n');
const meta = [
'<ReleaseMeta',
` version="v${version}"`,
` releaseDate="${formatLongDate(date)}"`,
" channels={['Desktop', 'PWA']}",
'/>',
].join('\n');
return [
frontmatter,
imports,
'{/* TODO: narrative intro — what this release is about, not what it contains. */}',
meta,
...sections,
'',
].join('\n\n');
}