@mui/internal-code-infra 0.1.1-canary.37 → 0.1.1-canary.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,421 @@
1
+ import { mapAsync } from 'es-toolkit/array';
2
+
3
+ import { getRateLimitRetryTime } from '../utils/github.mjs';
4
+
5
+ /**
6
+ * @typedef {import('@octokit/rest').Octokit} Octokit
7
+ * @typedef {import('./types.ts').GitHubRepository} GitHubRepository
8
+ * @typedef {import('./types.ts').ChangelogAuthor} ChangelogAuthor
9
+ * @typedef {import('./types.ts').ChangelogChange} ChangelogChange
10
+ * @typedef {Awaited<ReturnType<Octokit['repos']['compareCommitsWithBasehead']>>['data']['commits'][number]} Commit
11
+ */
12
+
13
+ /**
14
+ * What is needed from a pull request. Listing and getting one return different supersets of this.
15
+ *
16
+ * @typedef {Object} PullRequest
17
+ * @property {number} number
18
+ * @property {string} title
19
+ * @property {string | null} body
20
+ * @property {{ login: string, type: string } | null} user
21
+ * @property {string} author_association
22
+ * @property {{ name?: string }[]} labels
23
+ */
24
+
25
+ /** @type {Record<string, ChangelogAuthor['association']>} */
26
+ const ASSOCIATIONS = {
27
+ OWNER: 'team',
28
+ MEMBER: 'team',
29
+ COLLABORATOR: 'community',
30
+ CONTRIBUTOR: 'community',
31
+ FIRST_TIMER: 'first-timer',
32
+ FIRST_TIME_CONTRIBUTOR: 'first-timer',
33
+ MANNEQUIN: 'first-timer',
34
+ NONE: 'first-timer',
35
+ };
36
+
37
+ const BREAKING_CHANGE_LABELS = ['breaking', 'breaking change'];
38
+ const CHERRY_PICK_LABEL = 'cherry-pick';
39
+ const PULL_REFERENCE =
40
+ /(?:https:\/\/github\.com\/(?<urlOwner>[\w.-]+)\/(?<urlRepo>[\w.-]+)\/pull\/|(?:(?<owner>[\w.-]+)\/(?<repo>[\w.-]+))?#)(?<number>\d+)/;
41
+ // Unnamed, so that the pattern can be repeated.
42
+ const ANY_PULL_REFERENCE = PULL_REFERENCE.source.replaceAll(/\(\?<\w+>/g, '(?:');
43
+ // Anchored to the start of a line: changelogs quoted in dependency bumps mention cherry-picks too.
44
+ const CHERRY_PICK_LINE = new RegExp(
45
+ `^cherry[- ]pick(?:ed|s)?(?: of| from)?:? (${ANY_PULL_REFERENCE}(?:(?:,? and |, ?| )${ANY_PULL_REFERENCE})*)`,
46
+ 'gim',
47
+ );
48
+
49
+ /**
50
+ * @param {PullRequest} pull
51
+ * @param {GitHubRepository} repository - Where the pull request is
52
+ * @returns {(GitHubRepository & { number: number, text: string })[]}
53
+ */
54
+ function getCherryPickReferences(pull, repository) {
55
+ return [...(pull.body ?? '').matchAll(CHERRY_PICK_LINE)].flatMap(([, references]) =>
56
+ [...references.matchAll(new RegExp(PULL_REFERENCE, 'g'))].map(({ groups = {} }) => {
57
+ const owner = groups.urlOwner ?? groups.owner ?? repository.owner;
58
+ const repo = groups.urlRepo ?? groups.repo ?? repository.repo;
59
+ const isSameRepository = owner === repository.owner && repo === repository.repo;
60
+ return {
61
+ owner,
62
+ repo,
63
+ number: Number(groups.number),
64
+ // As written in a title, also when the body has a link.
65
+ text: isSameRepository ? `#${groups.number}` : `${owner}/${repo}#${groups.number}`,
66
+ };
67
+ }),
68
+ );
69
+ }
70
+
71
+ /**
72
+ * @param {any} error
73
+ */
74
+ function isForbidden(error) {
75
+ return error.status === 403 && getRateLimitRetryTime(error) === null;
76
+ }
77
+
78
+ /**
79
+ * @template {string} Key
80
+ * @template Value
81
+ * @param {(key: Key) => Promise<Value>} load
82
+ * @returns {(key: Key) => Promise<Value>}
83
+ */
84
+ function memoize(load) {
85
+ /** @type {Map<Key, Promise<Value>>} */
86
+ const cache = new Map();
87
+ return (key) => {
88
+ const cached = cache.get(key) ?? load(key);
89
+ cache.set(key, cached);
90
+ return cached;
91
+ };
92
+ }
93
+
94
+ /**
95
+ * @param {Object} options
96
+ * @param {Octokit} options.octokit
97
+ * @param {GitHubRepository} options.repository
98
+ * @param {AbortSignal} options.signal
99
+ */
100
+ function createAuthorResolver({ octokit, repository, signal }) {
101
+ let hasWarnedAboutMembership = false;
102
+ /**
103
+ * @param {string} login
104
+ */
105
+ function creditUnchecked(login) {
106
+ if (!hasWarnedAboutMembership) {
107
+ hasWarnedAboutMembership = true;
108
+ console.warn(
109
+ `The token can't read the private members of ${repository.owner}. ` +
110
+ `Authors that can't be checked, such as ${login}, are credited as community.`,
111
+ );
112
+ }
113
+ return /** @type {const} */ ('community');
114
+ }
115
+
116
+ const getMembership = memoize(
117
+ /**
118
+ * @param {string} login
119
+ * @returns {Promise<ChangelogAuthor['association']>}
120
+ */
121
+ async (login) => {
122
+ try {
123
+ await octokit.orgs.checkMembershipForUser({
124
+ org: repository.owner,
125
+ username: login,
126
+ request: { signal },
127
+ });
128
+ return 'team';
129
+ } catch (/** @type {any} */ error) {
130
+ if (isForbidden(error)) {
131
+ return creditUnchecked(login);
132
+ }
133
+ if (error.status === 404) {
134
+ // GitHub redirects outsiders to the public members, which don't tell about private ones.
135
+ return error.response?.url.includes('/public_members/')
136
+ ? creditUnchecked(login)
137
+ : 'community';
138
+ }
139
+ throw error;
140
+ }
141
+ },
142
+ );
143
+
144
+ const getOriginal = memoize(async (/** @type {string} */ key) => {
145
+ const [owner, repo, number] = key.split('/');
146
+ try {
147
+ const { data } = await octokit.pulls.get({
148
+ owner,
149
+ repo,
150
+ pull_number: Number(number),
151
+ request: { signal },
152
+ });
153
+ return /** @type {PullRequest} */ (data);
154
+ } catch (/** @type {any} */ error) {
155
+ if (error.status === 404 || isForbidden(error)) {
156
+ return null;
157
+ }
158
+ throw error;
159
+ }
160
+ });
161
+
162
+ /**
163
+ * @param {PullRequest} pull
164
+ * @param {GitHubRepository} pullRepository
165
+ * @returns {Promise<ChangelogAuthor | null>}
166
+ */
167
+ async function getOpener(pull, pullRepository) {
168
+ if (!pull.user) {
169
+ return null;
170
+ }
171
+ const { login, type } = pull.user;
172
+ const isSameRepository =
173
+ pullRepository.owner === repository.owner && pullRepository.repo === repository.repo;
174
+ /** @type {ChangelogAuthor['association']} */
175
+ let association = 'community';
176
+ if (type !== 'Bot') {
177
+ association = isSameRepository
178
+ ? (ASSOCIATIONS[pull.author_association] ?? 'community')
179
+ : // The association with another repository says nothing about this one.
180
+ await getMembership(login);
181
+ }
182
+ return { login, name: null, association };
183
+ }
184
+
185
+ /**
186
+ * @param {PullRequest} pull
187
+ * @param {GitHubRepository} pullRepository
188
+ * @param {string[]} chain - Cherry-picks that led to this pull request
189
+ * @returns {Promise<{ author: ChangelogAuthor | null, isBot: boolean, references: string[] } | null>}
190
+ * `null` when the pull request is a cherry-pick by a bot of which the original author is unknown
191
+ */
192
+ async function resolve(pull, pullRepository, chain = []) {
193
+ const isBot = pull.user?.type === 'Bot';
194
+ const opener = async () => ({
195
+ author: await getOpener(pull, pullRepository),
196
+ isBot,
197
+ references: [],
198
+ });
199
+ const references = getCherryPickReferences(pull, pullRepository);
200
+ if (references.length === 0) {
201
+ const isLabeled = pull.labels.some((label) => label.name === CHERRY_PICK_LABEL);
202
+ return isBot && isLabeled ? null : opener();
203
+ }
204
+
205
+ const originals = await Promise.all(
206
+ references.map(async (reference) => {
207
+ const key = `${reference.owner}/${reference.repo}/${reference.number}`;
208
+ const original = chain.includes(key) ? null : await getOriginal(key);
209
+ return original && resolve(original, reference, [...chain, key]);
210
+ }),
211
+ );
212
+ const author = originals[0]?.author;
213
+ if (author && originals.every((original) => original?.author?.login === author.login)) {
214
+ // A person who cherry-picks the work of a bot is the better credit.
215
+ const isBotAuthor = originals.some((original) => original?.isBot);
216
+ if (isBot || !isBotAuthor) {
217
+ return {
218
+ author,
219
+ isBot: isBotAuthor,
220
+ references: references.map((reference) => reference.text),
221
+ };
222
+ }
223
+ }
224
+ return isBot ? null : opener();
225
+ }
226
+
227
+ return {
228
+ /**
229
+ * @param {PullRequest} pull
230
+ * @returns {Promise<{ author: ChangelogAuthor | null, references: string[] }>}
231
+ */
232
+ async fromPullRequest(pull) {
233
+ const resolved = await resolve(pull, repository);
234
+ if (resolved) {
235
+ return resolved;
236
+ }
237
+ const author = await getOpener(pull, repository);
238
+ console.warn(
239
+ `#${pull.number} is a cherry-pick, but its original author can't be determined. ` +
240
+ `${author?.login} is credited instead.`,
241
+ );
242
+ return { author, references: [] };
243
+ },
244
+ /**
245
+ * @param {Commit} commit
246
+ * @returns {Promise<ChangelogAuthor>}
247
+ */
248
+ async fromCommit(commit) {
249
+ const login = commit.author?.login ?? null;
250
+ return {
251
+ login,
252
+ name: commit.commit.author?.name ?? null,
253
+ association:
254
+ login === null || commit.author?.type === 'Bot'
255
+ ? 'community'
256
+ : await getMembership(login),
257
+ };
258
+ },
259
+ };
260
+ }
261
+
262
+ /**
263
+ * Strips trailing `(#1)` references, and `(@login)` credits when asked to.
264
+ *
265
+ * @param {string} title
266
+ * @param {string[]} references
267
+ * @param {boolean} stripCredits
268
+ * @returns {string}
269
+ */
270
+ function stripTrailingReferences(title, references, stripCredits) {
271
+ const [, rest, reference] = /^(.*?)\s*\(([^()]+)\)$/.exec(title) ?? [];
272
+ // The credit can name a login that has since been renamed.
273
+ return references.includes(reference) || (stripCredits && /^@[\w-]+$/.test(reference))
274
+ ? stripTrailingReferences(rest, references, stripCredits)
275
+ : title;
276
+ }
277
+
278
+ /**
279
+ * @param {Object} options
280
+ * @param {Octokit} options.octokit
281
+ * @param {GitHubRepository} options.repository
282
+ * @param {string} options.previousSha
283
+ * @param {string} options.releaseSha
284
+ * @param {boolean} options.includeDirectCommits
285
+ * @param {AbortController} options.controller - Aborted when a request fails
286
+ * @returns {Promise<ChangelogChange[]>}
287
+ */
288
+ export async function fetchChangelogChanges({
289
+ octokit,
290
+ repository,
291
+ previousSha,
292
+ releaseSha,
293
+ includeDirectCommits,
294
+ controller,
295
+ }) {
296
+ const { signal } = controller;
297
+ const location = { ...repository, request: { signal } };
298
+ const authors = createAuthorResolver({ octokit, repository, signal });
299
+
300
+ async function listCommits() {
301
+ /** @type {Commit[]} */
302
+ const commits = [];
303
+ let total = 0;
304
+ const pages = octokit.paginate.iterator(
305
+ octokit.repos.compareCommitsWithBasehead.endpoint.merge({
306
+ ...location,
307
+ basehead: `${previousSha}...${releaseSha}`,
308
+ per_page: 100,
309
+ }),
310
+ );
311
+ for await (const { data } of /** @type {AsyncIterable<any>} */ (pages)) {
312
+ commits.push(...data.commits);
313
+ total = data.total_commits;
314
+ }
315
+ if (commits.length !== total) {
316
+ throw new Error(`GitHub listed ${commits.length} of the ${total} commits in the release.`);
317
+ }
318
+ return commits;
319
+ }
320
+
321
+ /**
322
+ * Asks GitHub rather than trusting the message, where a reference to an issue or to another pull
323
+ * request looks the same as the pull request the commit was merged from.
324
+ *
325
+ * @param {string} sha
326
+ * @param {string} subject
327
+ */
328
+ async function findPullRequest(sha, subject) {
329
+ const isMergedAsCommit = (
330
+ /** @type {{ merged_at: string | null, merge_commit_sha: string | null }} */ pull,
331
+ ) => pull.merged_at !== null && pull.merge_commit_sha === sha;
332
+
333
+ const pulls = await octokit.paginate(octokit.repos.listPullRequestsAssociatedWithCommit, {
334
+ ...location,
335
+ commit_sha: sha,
336
+ per_page: 100,
337
+ });
338
+ // On maintenance branches, GitHub also lists pull requests that merely contain the commit.
339
+ const listed = pulls.find(isMergedAsCommit);
340
+ if (listed) {
341
+ return listed;
342
+ }
343
+
344
+ // GitHub lists nothing for some commits, such as mui/mui-x@227a2fee.
345
+ const reference = /\(#(\d+)\)$/.exec(subject);
346
+ if (!reference) {
347
+ return null;
348
+ }
349
+ try {
350
+ const { data } = await octokit.pulls.get({ ...location, pull_number: Number(reference[1]) });
351
+ return isMergedAsCommit(data) ? data : null;
352
+ } catch (/** @type {any} */ error) {
353
+ if (error.status === 404) {
354
+ return null;
355
+ }
356
+ throw error;
357
+ }
358
+ }
359
+
360
+ /**
361
+ * @param {Commit} commit
362
+ * @returns {Promise<ChangelogChange | null>}
363
+ */
364
+ async function toChange(commit) {
365
+ const { sha } = commit;
366
+ const { message } = commit.commit;
367
+ const subject = message.split('\n', 1)[0].trim();
368
+
369
+ const pull = await findPullRequest(sha, subject);
370
+ if (pull) {
371
+ const { author, references } = await authors.fromPullRequest(pull);
372
+ const ownReference = `#${pull.number}`;
373
+ const title = subject.endsWith(`(${ownReference})`) ? subject : pull.title;
374
+ const isCreditedCherryPick = references.length > 0;
375
+ return {
376
+ title: stripTrailingReferences(title, [ownReference, ...references], isCreditedCherryPick),
377
+ message,
378
+ sha,
379
+ url: pull.html_url,
380
+ labels: pull.labels.map((label) => label.name),
381
+ isBreakingChange: pull.labels.some((label) => BREAKING_CHANGE_LABELS.includes(label.name)),
382
+ pullRequest: { number: pull.number, title: pull.title, body: pull.body ?? '' },
383
+ author,
384
+ createdAt: pull.created_at,
385
+ mergedAt: pull.merged_at,
386
+ };
387
+ }
388
+
389
+ if (!includeDirectCommits) {
390
+ return null;
391
+ }
392
+ return {
393
+ title: subject,
394
+ message,
395
+ sha,
396
+ url: commit.html_url,
397
+ labels: [],
398
+ isBreakingChange: false,
399
+ pullRequest: null,
400
+ author: await authors.fromCommit(commit),
401
+ createdAt: commit.commit.author?.date ?? null,
402
+ mergedAt: commit.commit.committer?.date ?? null,
403
+ };
404
+ }
405
+
406
+ const changes = await mapAsync(
407
+ await listCommits(),
408
+ async (commit) => {
409
+ signal.throwIfAborted();
410
+ try {
411
+ return await toChange(commit);
412
+ } catch (error) {
413
+ // Immediately, or the next queued commit still gets to make its request.
414
+ controller.abort(error);
415
+ throw error;
416
+ }
417
+ },
418
+ { concurrency: 10 },
419
+ );
420
+ return changes.filter((change) => change !== null);
421
+ }
@@ -0,0 +1,148 @@
1
+ import { matchPrefix, parseTitle } from './changelogTitle.mjs';
2
+
3
+ /**
4
+ * @typedef {import('./types.ts').ChangelogChange} ChangelogChange
5
+ * @typedef {import('./types.ts').ChangelogAuthor} ChangelogAuthor
6
+ * @typedef {import('./types.ts').ChangelogCredits} ChangelogCredits
7
+ */
8
+
9
+ const COLLATOR = new Intl.Collator('en', { numeric: true });
10
+
11
+ /**
12
+ * Ends in a comparison by code unit, so that only equal strings are equal.
13
+ *
14
+ * @param {string} a
15
+ * @param {string} b
16
+ */
17
+ function compareText(a, b) {
18
+ if (a === b) {
19
+ return 0;
20
+ }
21
+ return COLLATOR.compare(a, b) || (a < b ? -1 : 1);
22
+ }
23
+
24
+ /**
25
+ * @param {string} label
26
+ */
27
+ function getKind(label) {
28
+ return /^([^:]+):/.exec(label)?.[1];
29
+ }
30
+
31
+ /**
32
+ * The labels of a change, and the ones its title prefixes stand for. A label wins over the prefixes
33
+ * for its kind, the part before the colon: `scope: charts` leaves the scopes of the title out.
34
+ *
35
+ * @param {Pick<ChangelogChange, 'labels' | 'title'>} change
36
+ * @param {Record<string, readonly string[]>} [prefixes] - Labels that a prefix stands for, with the
37
+ * prefix spelled in any way
38
+ * @returns {string[]}
39
+ */
40
+ export function readLabels(change, prefixes = {}) {
41
+ const kinds = new Set(change.labels.map(getKind));
42
+ const titleLabels = parseTitle(change.title).prefixes.flatMap((prefix) => {
43
+ const match = matchPrefix(prefix, Object.keys(prefixes));
44
+ return match === undefined ? [] : prefixes[match];
45
+ });
46
+ return [
47
+ ...new Set([
48
+ ...change.labels,
49
+ ...titleLabels.filter((label) => {
50
+ const kind = getKind(label);
51
+ return kind === undefined || !kinds.has(kind);
52
+ }),
53
+ ]),
54
+ ];
55
+ }
56
+
57
+ /**
58
+ * The values of one kind of label: `labelValues(['scope: charts', 'docs'], 'scope')` is `['charts']`.
59
+ *
60
+ * @param {readonly string[]} labels
61
+ * @param {string} kind
62
+ * @returns {string[]}
63
+ */
64
+ export function labelValues(labels, kind) {
65
+ return labels
66
+ .filter((label) => getKind(label) === kind)
67
+ .map((label) => label.slice(kind.length + 1).trim());
68
+ }
69
+
70
+ /**
71
+ * Groups items that can be in several groups, or in none. Items keep their order.
72
+ *
73
+ * @template Item
74
+ * @template {string} Group
75
+ * @param {Iterable<Item>} items
76
+ * @param {(item: Item) => Group | readonly Group[] | null | undefined} getGroups
77
+ * @returns {Map<Group, Item[]>}
78
+ */
79
+ export function groupBy(items, getGroups) {
80
+ /** @type {Map<Group, Item[]>} */
81
+ const groups = new Map();
82
+ for (const item of items) {
83
+ for (const group of new Set([getGroups(item) ?? []].flat())) {
84
+ const members = groups.get(/** @type {Group} */ (group)) ?? [];
85
+ members.push(item);
86
+ groups.set(/** @type {Group} */ (group), members);
87
+ }
88
+ }
89
+ return groups;
90
+ }
91
+
92
+ /**
93
+ * Sorts by prefixes, then by the rest of the title. Changes of the same title are sorted by pull
94
+ * request, so that the order never depends on the order they are given in.
95
+ *
96
+ * @template {Pick<ChangelogChange, 'title' | 'pullRequest' | 'sha'>} Change
97
+ * @param {Iterable<Change>} changes
98
+ * @returns {Change[]}
99
+ */
100
+ export function sortByTitle(changes) {
101
+ return Array.from(changes, (change) => {
102
+ const { prefixes, text } = parseTitle(change.title);
103
+ return { change, prefixes: prefixes.join(','), text };
104
+ })
105
+ .sort(
106
+ (a, b) =>
107
+ compareText(a.prefixes, b.prefixes) ||
108
+ compareText(a.text, b.text) ||
109
+ (a.change.pullRequest?.number ?? 0) - (b.change.pullRequest?.number ?? 0) ||
110
+ compareText(a.change.sha, b.change.sha),
111
+ )
112
+ .map(({ change }) => change);
113
+ }
114
+
115
+ /**
116
+ * The authors of changes, once each and in alphabetical order. Someone who joined the team during
117
+ * the release is credited as team.
118
+ *
119
+ * @param {Iterable<Pick<ChangelogChange, 'author'>>} changes
120
+ * @param {Object} [options]
121
+ * @param {readonly string[]} [options.exclude] - Logins
122
+ * @returns {ChangelogCredits}
123
+ */
124
+ export function creditAuthors(changes, { exclude = [] } = {}) {
125
+ const excluded = new Set(exclude.map((login) => login.toLowerCase()));
126
+ /** @type {Map<string, ChangelogAuthor>} */
127
+ const authors = new Map();
128
+ for (const { author } of changes) {
129
+ const name = author?.login ?? author?.name;
130
+ if (!author || !name || (author.login && excluded.has(author.login.toLowerCase()))) {
131
+ continue;
132
+ }
133
+ // A name can equal the login of someone else.
134
+ const key = author.login ? `@${author.login.toLowerCase()}` : name;
135
+ if (!authors.has(key) || author.association === 'team') {
136
+ authors.set(key, author);
137
+ }
138
+ }
139
+
140
+ const all = [...authors.values()].sort((a, b) =>
141
+ compareText(a.login ?? a.name ?? '', b.login ?? b.name ?? ''),
142
+ );
143
+ return {
144
+ all,
145
+ team: all.filter((author) => author.association === 'team'),
146
+ community: all.filter((author) => author.association !== 'team'),
147
+ };
148
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * @typedef {import('./types.ts').ChangelogAuthor} ChangelogAuthor
3
+ * @typedef {import('./types.ts').ChangelogChange} ChangelogChange
4
+ * @typedef {import('./types.ts').ChangelogData} ChangelogData
5
+ * @typedef {import('./types.ts').MarkdownBlock} MarkdownBlock
6
+ * @typedef {import('./types.ts').MarkdownInline} MarkdownInline
7
+ */
8
+
9
+ const DATE_FORMAT = new Intl.DateTimeFormat('en-US', {
10
+ month: 'short',
11
+ day: 'numeric',
12
+ year: 'numeric',
13
+ timeZone: 'UTC',
14
+ });
15
+
16
+ /**
17
+ * Joins blocks with a blank line in between. Empty ones are left out. Blank lines inside a block,
18
+ * such as the ones of a code block, stay as they are.
19
+ *
20
+ * @param {...MarkdownBlock} blocks
21
+ * @returns {string}
22
+ */
23
+ export function joinBlocks(...blocks) {
24
+ return blocks
25
+ .map((block) => {
26
+ const markdown = typeof block === 'string' ? block : joinBlocks(...(block || []));
27
+ return markdown.replace(/^(?:[ \t]*\n)+/, '').trimEnd();
28
+ })
29
+ .filter(Boolean)
30
+ .join('\n\n');
31
+ }
32
+
33
+ /**
34
+ * A heading and what is below it, or nothing when there is nothing below it.
35
+ *
36
+ * @param {string} heading
37
+ * @param {...MarkdownBlock} blocks
38
+ * @returns {string}
39
+ */
40
+ export function section(heading, ...blocks) {
41
+ const content = joinBlocks(...blocks);
42
+ return content && joinBlocks(heading, content);
43
+ }
44
+
45
+ /**
46
+ * @param {Iterable<MarkdownInline>} items
47
+ * @returns {string}
48
+ */
49
+ export function bulletList(items) {
50
+ return Array.from(items)
51
+ .flatMap((item) => (item ? [`- ${item.trim().replace(/\n(?=.)/g, '\n ')}`] : []))
52
+ .join('\n');
53
+ }
54
+
55
+ /**
56
+ * Joins the parts of a line with a space. Empty ones are left out.
57
+ *
58
+ * @param {...MarkdownInline} parts
59
+ * @returns {string}
60
+ */
61
+ export function joinWords(...parts) {
62
+ return parts.filter(Boolean).join(' ');
63
+ }
64
+
65
+ /**
66
+ * `#123`, or the short SHA of a change without a pull request.
67
+ *
68
+ * @param {Pick<ChangelogChange, 'pullRequest' | 'sha'>} change
69
+ * @returns {string}
70
+ */
71
+ export function formatReference({ pullRequest, sha }) {
72
+ return pullRequest ? `#${pullRequest.number}` : sha.slice(0, 7);
73
+ }
74
+
75
+ /**
76
+ * `@login`, or the name of an author without a GitHub account. Empty when neither is known.
77
+ *
78
+ * @param {Pick<ChangelogAuthor, 'login' | 'name'> | null} author
79
+ * @returns {string}
80
+ */
81
+ export function formatAuthor(author) {
82
+ if (author?.login) {
83
+ return `@${author.login}`;
84
+ }
85
+ return (author?.name ?? '').replace(/[\\`*_[\]<>]/g, '\\$&');
86
+ }
87
+
88
+ /**
89
+ * `Jan 2, 2026`, in UTC like the date of a release.
90
+ *
91
+ * @param {string} date - ISO 8601
92
+ * @returns {string}
93
+ */
94
+ export function formatDate(date) {
95
+ return DATE_FORMAT.format(new Date(date));
96
+ }
97
+
98
+ /**
99
+ * What is below the heading of a release: a comment with the range it was generated from, and its
100
+ * date.
101
+ *
102
+ * @param {Pick<ChangelogData, 'previous' | 'release' | 'date'>} data
103
+ * @returns {string}
104
+ */
105
+ export function formatSubHeader({ previous, release, date }) {
106
+ return joinBlocks(
107
+ `<!-- generated comparing ${previous.ref}...${release.ref} -->`,
108
+ `_${formatDate(date)}_`,
109
+ );
110
+ }