ai-release-notes 0.3.0 → 0.4.0

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.
Files changed (54) hide show
  1. package/README.md +261 -12
  2. package/dist/bin/cli.js +428 -331
  3. package/dist/bin/cli.js.map +1 -1
  4. package/dist/generator.d.ts.map +1 -1
  5. package/dist/generator.js +25 -44
  6. package/dist/generator.js.map +1 -1
  7. package/dist/index.d.ts +17 -3
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +47 -1
  10. package/dist/index.js.map +1 -1
  11. package/dist/output-index.d.ts +71 -1
  12. package/dist/output-index.d.ts.map +1 -1
  13. package/dist/output-index.js +333 -1
  14. package/dist/output-index.js.map +1 -1
  15. package/dist/output-path.d.ts +61 -0
  16. package/dist/output-path.d.ts.map +1 -0
  17. package/dist/output-path.js +182 -0
  18. package/dist/output-path.js.map +1 -0
  19. package/dist/promote.d.ts +133 -0
  20. package/dist/promote.d.ts.map +1 -0
  21. package/dist/promote.js +0 -0
  22. package/dist/promote.js.map +1 -0
  23. package/dist/prompt-session.d.ts +172 -0
  24. package/dist/prompt-session.d.ts.map +1 -0
  25. package/dist/prompt-session.js +484 -0
  26. package/dist/prompt-session.js.map +1 -0
  27. package/dist/prompts/builder.d.ts +77 -0
  28. package/dist/prompts/builder.d.ts.map +1 -1
  29. package/dist/prompts/builder.js +134 -0
  30. package/dist/prompts/builder.js.map +1 -1
  31. package/dist/release-date.d.ts +14 -0
  32. package/dist/release-date.d.ts.map +1 -0
  33. package/dist/release-date.js +54 -0
  34. package/dist/release-date.js.map +1 -0
  35. package/dist/release-document.d.ts +150 -0
  36. package/dist/release-document.d.ts.map +1 -0
  37. package/dist/release-document.js +651 -0
  38. package/dist/release-document.js.map +1 -0
  39. package/dist/release.d.ts +27 -3
  40. package/dist/release.d.ts.map +1 -1
  41. package/dist/release.js +88 -2
  42. package/dist/release.js.map +1 -1
  43. package/dist/text-diff.d.ts +19 -0
  44. package/dist/text-diff.d.ts.map +1 -0
  45. package/dist/text-diff.js +81 -0
  46. package/dist/text-diff.js.map +1 -0
  47. package/dist/types.d.ts +10 -7
  48. package/dist/types.d.ts.map +1 -1
  49. package/dist/types.js.map +1 -1
  50. package/package.json +1 -1
  51. package/prompts/release-notes-edit-system.md +48 -0
  52. package/prompts/release-notes-promote-opening.md +59 -0
  53. package/prompts/release-notes-session-router.md +68 -0
  54. package/dist/prompts/translation-system.md +0 -8
@@ -0,0 +1,651 @@
1
+ "use strict";
2
+ /**
3
+ * A generated release note, read back.
4
+ *
5
+ * Promoting a release from one environment to the next reuses the words that
6
+ * were already written and reviewed, so nothing here rewrites a release note:
7
+ * it is taken apart into the sections and lists the model wrote, several of
8
+ * them are put together in the order they were released, and the result is
9
+ * written out in the same shape it came in.
10
+ *
11
+ * Merging is what a reader would do by hand: sections that carry the same
12
+ * heading become one section, their lists become one list, and a line that
13
+ * appears in two releases is listed once. What no reader would do by hand is
14
+ * keep three titles, three dates and three summaries, so the newest release's
15
+ * opening stands for the range and the rest go.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.parseReleaseDocument = parseReleaseDocument;
19
+ exports.serializeReleaseDocument = serializeReleaseDocument;
20
+ exports.mergeReleaseDocuments = mergeReleaseDocuments;
21
+ exports.joinReleaseDocuments = joinReleaseDocuments;
22
+ exports.isReleaseDocumentReadable = isReleaseDocumentReadable;
23
+ exports.splitReleaseOpening = splitReleaseOpening;
24
+ exports.dedupeReleaseDocument = dedupeReleaseDocument;
25
+ exports.mergeSections = mergeSections;
26
+ exports.releaseContentRange = releaseContentRange;
27
+ exports.extractReleaseContent = extractReleaseContent;
28
+ exports.replaceReleaseContent = replaceReleaseContent;
29
+ // ─────────────────────────────────────────
30
+ // Reading a release note
31
+ // ─────────────────────────────────────────
32
+ /** Take a release note apart into its sections. */
33
+ function parseReleaseDocument(content, format) {
34
+ return format === "html" ? parseHtmlDocument(content) : parseMarkdownDocument(content);
35
+ }
36
+ /** Write a release note back out, in the shape it was read in. */
37
+ function serializeReleaseDocument(section, format) {
38
+ return format === "html" ? serializeHtml(section) : serializeMarkdown(section);
39
+ }
40
+ /**
41
+ * Put several release notes together, oldest first.
42
+ *
43
+ * A single note is returned untouched: promoting one release copies its words
44
+ * rather than reformatting them.
45
+ */
46
+ function mergeReleaseDocuments(documents, format, options = {}) {
47
+ const contents = documents.map((document) => document.trim()).filter(Boolean);
48
+ if (contents.length === 0)
49
+ return "";
50
+ if (contents.length === 1)
51
+ return contents[0];
52
+ const merged = contents
53
+ .map((content) => parseReleaseDocument(content, format))
54
+ .reduce((accumulated, next) => mergeSections(accumulated, next, options));
55
+ return serializeReleaseDocument(merged, format);
56
+ }
57
+ /**
58
+ * Put several release notes one after another, oldest first, each kept whole.
59
+ *
60
+ * Nothing is read or rewritten, so a note whose shape this cannot follow still
61
+ * reaches the next environment word for word.
62
+ */
63
+ function joinReleaseDocuments(documents, format) {
64
+ return documents
65
+ .map((document) => document.trim())
66
+ .filter(Boolean)
67
+ .join(format === "html" ? "\n<hr>\n" : "\n\n---\n\n");
68
+ }
69
+ /**
70
+ * Whether a note can be taken apart and written back out word for word.
71
+ *
72
+ * Merging is only worth doing on notes this can read: what it cannot read it
73
+ * would rewrite, and promoting exists to carry reviewed wording across
74
+ * untouched. A note that survives the round trip unchanged is one whose
75
+ * sections can be folded safely; anything else is kept whole instead.
76
+ */
77
+ function isReleaseDocumentReadable(content, format) {
78
+ const trimmed = content.trim();
79
+ if (!trimmed)
80
+ return true;
81
+ const written = serializeReleaseDocument(parseReleaseDocument(trimmed, format), format);
82
+ return sameLines(trimmed, written);
83
+ }
84
+ /**
85
+ * Whether two notes carry the same lines, in the same order.
86
+ *
87
+ * Blank lines, indentation and line endings are what the serializer lays out on
88
+ * its own, so a note that comes back with its wording intact reads as unchanged
89
+ * here even when it came in spaced differently or written on Windows.
90
+ *
91
+ * Indentation counts for nothing in particular: a note read back off a page is
92
+ * indented to sit where the template put it, and the serializer writes flush
93
+ * left. Comparing that would call every templated note unreadable and keep
94
+ * whole every range that was worth merging.
95
+ */
96
+ function sameLines(left, right) {
97
+ const lines = (content) => content
98
+ .split(/\r?\n/)
99
+ .map((line) => line.trim())
100
+ .filter(Boolean);
101
+ const [a, b] = [lines(left), lines(right)];
102
+ return a.length === b.length && a.every((line, index) => line === b[index]);
103
+ }
104
+ /**
105
+ * Cut a release note where its first section begins.
106
+ *
107
+ * A note opens by saying which release it is and what that release brought,
108
+ * and then lists the changes under headings. Promoting several releases as one
109
+ * merges those lists, but their openings do not merge: each names a version, a
110
+ * date and an environment of its own. Cutting them apart is what lets the
111
+ * sections be reused word for word while the opening is written once.
112
+ *
113
+ * The note itself says where the cut is: its own top heading level is the
114
+ * title, and the first heading below that level opens the sections. A note
115
+ * that never changes level has no title, so it opens at its first heading, and
116
+ * one that carries a single heading is all opening.
117
+ */
118
+ function splitReleaseOpening(content, format) {
119
+ const headings = [...content.matchAll(format === "html" ? /^[ \t]*<h([1-6])\b/gim : /^ {0,3}(#{1,6})\s/gm)].map((match) => ({
120
+ index: match.index,
121
+ level: format === "html" ? Number(match[1]) : match[1].length,
122
+ }));
123
+ if (headings.length === 0)
124
+ return { opening: content, sections: "" };
125
+ const top = Math.min(...headings.map((heading) => heading.level));
126
+ const first = headings.find((heading) => heading.level > top)
127
+ ?? (headings.length > 1 ? headings[0] : undefined);
128
+ if (!first)
129
+ return { opening: content, sections: "" };
130
+ return {
131
+ opening: content.slice(0, first.index),
132
+ sections: content.slice(first.index),
133
+ };
134
+ }
135
+ /**
136
+ * Drop the lines a release note lists more than once.
137
+ *
138
+ * A note covering several releases, or one merged by hand, repeats the same
139
+ * bullet under two sections. The first one stays where the reader meets it and
140
+ * the later ones go, whatever markup or wording carries them — the same
141
+ * comparison merging uses, so the two agree on what a repeated line is.
142
+ *
143
+ * Only listed lines are compared: a paragraph, a rule or a metadata line can be
144
+ * repeated by design, and a title block is built from exactly those. A section
145
+ * left with nothing to say goes with its lines.
146
+ */
147
+ function dedupeReleaseDocument(content, format) {
148
+ const removed = [];
149
+ const deduped = dedupeSection(parseReleaseDocument(content, format), new Set(), removed);
150
+ return {
151
+ content: removed.length === 0 ? content : serializeReleaseDocument(deduped, format),
152
+ removed,
153
+ };
154
+ }
155
+ function dedupeSection(section, seen, removed) {
156
+ const blocks = [];
157
+ for (const block of section.blocks) {
158
+ if (block.kind !== "list") {
159
+ blocks.push({ ...block });
160
+ continue;
161
+ }
162
+ const items = (block.items || []).filter((item) => {
163
+ const key = comparisonKey(item);
164
+ // A line with no letters or digits of its own carries no wording to
165
+ // repeat, so it is never taken for a duplicate of another one.
166
+ if (!key)
167
+ return true;
168
+ if (seen.has(key)) {
169
+ removed.push(item);
170
+ return false;
171
+ }
172
+ seen.add(key);
173
+ return true;
174
+ });
175
+ if (items.length > 0)
176
+ blocks.push({ ...block, items, content: items.join("\n") });
177
+ }
178
+ return {
179
+ level: section.level,
180
+ heading: section.heading,
181
+ blocks,
182
+ children: section.children
183
+ .map((child) => dedupeSection(child, seen, removed))
184
+ .filter((child) => child.blocks.length > 0 || child.children.length > 0),
185
+ };
186
+ }
187
+ /**
188
+ * Join two release notes, the later one folded into the earlier.
189
+ *
190
+ * Both are left as they were; the result is a new section tree.
191
+ */
192
+ function mergeSections(target, source, options = {}) {
193
+ const merged = {
194
+ level: target.level,
195
+ heading: target.heading,
196
+ blocks: target.blocks.map((block) => ({ ...block, items: block.items?.slice() })),
197
+ children: target.children.map(cloneSection),
198
+ };
199
+ for (const block of source.blocks) {
200
+ addBlock(merged.blocks, block, options);
201
+ }
202
+ for (const child of source.children) {
203
+ const existing = merged.children.findIndex((candidate) => candidate.level === child.level && sameHeading(candidate.heading, child.heading));
204
+ if (existing >= 0) {
205
+ merged.children[existing] = mergeSections(merged.children[existing], child, options);
206
+ continue;
207
+ }
208
+ // A release note names itself after the release it describes, so the title
209
+ // of one is never the title of the next. Merged, they are one release note
210
+ // covering the whole range, and it takes the name of the newest release in
211
+ // it rather than opening with two titles.
212
+ if (isTitle(merged, child) && isTitle(source, child)) {
213
+ merged.children[0] = {
214
+ ...mergeSections(merged.children[0], child, options),
215
+ heading: child.heading,
216
+ // What sits under a title before the first section is that release's
217
+ // own opening: which environment it went to, when, and a sentence on
218
+ // what it brought. Three of those in a row is not an opening for the
219
+ // range they cover, so the newest release's stands for all of them.
220
+ blocks: child.blocks.map((block) => ({ ...block, items: block.items?.slice() })),
221
+ };
222
+ continue;
223
+ }
224
+ merged.children.push(cloneSection(child));
225
+ }
226
+ return merged;
227
+ }
228
+ /**
229
+ * Whether a document is one heading with everything under it, and `child` is
230
+ * that heading.
231
+ *
232
+ * A note built that way has a title; a note that opens straight into its
233
+ * sections has none, and nothing is renamed.
234
+ */
235
+ function isTitle(section, child) {
236
+ return section.children.length === 1 && section.children[0].level === child.level;
237
+ }
238
+ function cloneSection(section) {
239
+ return {
240
+ level: section.level,
241
+ heading: section.heading,
242
+ blocks: section.blocks.map((block) => ({ ...block, items: block.items?.slice() })),
243
+ children: section.children.map(cloneSection),
244
+ };
245
+ }
246
+ /** Add a block to a section, merging it into a list it belongs to. */
247
+ function addBlock(blocks, block, options = {}) {
248
+ if (block.kind === "list") {
249
+ const list = blocks.find((candidate) => candidate.kind === "list" && candidate.ordered === block.ordered);
250
+ if (list) {
251
+ const known = new Set((list.items || []).map(comparisonKey));
252
+ const added = [];
253
+ for (const item of block.items || []) {
254
+ if (known.has(comparisonKey(item)))
255
+ continue;
256
+ known.add(comparisonKey(item));
257
+ added.push(item);
258
+ }
259
+ // Each release keeps the order its own lines were written in; only where
260
+ // that release sits among the others is what `leadWith` decides.
261
+ list.items = options.leadWith === "newest"
262
+ ? [...added, ...(list.items || [])]
263
+ : [...(list.items || []), ...added];
264
+ list.content = list.items.join("\n");
265
+ return;
266
+ }
267
+ }
268
+ const key = comparisonKey(block.content);
269
+ if (blocks.some((candidate) => comparisonKey(candidate.content) === key))
270
+ return;
271
+ blocks.push({ ...block, items: block.items?.slice() });
272
+ }
273
+ function sameHeading(left, right) {
274
+ return headingKey(left) === headingKey(right);
275
+ }
276
+ /**
277
+ * What makes two headings the same one.
278
+ *
279
+ * A heading is written by a model, so the same section can arrive decorated
280
+ * differently from one release to the next: emphasis, an emoji, trailing
281
+ * punctuation. Only its letters and digits decide.
282
+ */
283
+ function headingKey(heading) {
284
+ return stripMarkup(heading)
285
+ .toLowerCase()
286
+ .replace(/[^\p{L}\p{N}]+/gu, " ")
287
+ .trim();
288
+ }
289
+ /** What makes two lines the same line, whatever markup carries them. */
290
+ function comparisonKey(value) {
291
+ return stripMarkup(value).toLowerCase().replace(/\s+/g, " ").trim();
292
+ }
293
+ function stripMarkup(value) {
294
+ return value
295
+ .replace(/<[^>]*>/g, " ")
296
+ .replace(/^\s*(?:[-*+]|\d+[.)])\s+/gm, " ")
297
+ .replace(/[*_`#]/g, "")
298
+ .replace(/\s+/g, " ")
299
+ .trim();
300
+ }
301
+ // ─────────────────────────────────────────
302
+ // Markdown
303
+ // ─────────────────────────────────────────
304
+ const MARKDOWN_HEADING = /^\s{0,3}(#{1,6})\s+(.*?)\s*#*\s*$/;
305
+ const MARKDOWN_LIST_ITEM = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/;
306
+ const MARKDOWN_FENCE = /^\s*(```+|~~~+)/;
307
+ function parseMarkdownDocument(markdown) {
308
+ const root = { level: 0, heading: "", blocks: [], children: [] };
309
+ const open = [root];
310
+ let body = [];
311
+ const closeBody = () => {
312
+ open[open.length - 1].blocks.push(...splitMarkdownBlocks(body));
313
+ body = [];
314
+ };
315
+ const lines = markdown.replace(/\r\n/g, "\n").split("\n");
316
+ let inFence = false;
317
+ for (const line of lines) {
318
+ if (MARKDOWN_FENCE.test(line))
319
+ inFence = !inFence;
320
+ const heading = inFence ? null : MARKDOWN_HEADING.exec(line);
321
+ if (!heading) {
322
+ body.push(line);
323
+ continue;
324
+ }
325
+ closeBody();
326
+ const level = heading[1].length;
327
+ while (open.length > 1 && open[open.length - 1].level >= level)
328
+ open.pop();
329
+ const section = { level, heading: heading[2].trim(), blocks: [], children: [] };
330
+ open[open.length - 1].children.push(section);
331
+ open.push(section);
332
+ }
333
+ closeBody();
334
+ return root;
335
+ }
336
+ function splitMarkdownBlocks(lines) {
337
+ const blocks = [];
338
+ let index = 0;
339
+ while (index < lines.length) {
340
+ const line = lines[index];
341
+ if (!line.trim()) {
342
+ index += 1;
343
+ continue;
344
+ }
345
+ const fence = MARKDOWN_FENCE.exec(line);
346
+ if (fence) {
347
+ const start = index;
348
+ index += 1;
349
+ while (index < lines.length && !new RegExp(`^\\s*${fence[1][0]}{3,}\\s*$`).test(lines[index])) {
350
+ index += 1;
351
+ }
352
+ index = Math.min(index + 1, lines.length);
353
+ blocks.push({ kind: "text", content: lines.slice(start, index).join("\n").trimEnd() });
354
+ continue;
355
+ }
356
+ if (MARKDOWN_LIST_ITEM.test(line)) {
357
+ const items = [];
358
+ let current = [];
359
+ // The first item sets what counts as an item of this list: anything
360
+ // further in belongs to the item above it.
361
+ const baseIndent = (MARKDOWN_LIST_ITEM.exec(line)?.[1] || "").length;
362
+ while (index < lines.length) {
363
+ const candidate = lines[index];
364
+ const item = MARKDOWN_LIST_ITEM.exec(candidate);
365
+ // A blank line ends the list unless the list goes on after it.
366
+ if (!candidate.trim()) {
367
+ const next = lines.slice(index + 1).find((following) => following.trim());
368
+ if (!next || !(MARKDOWN_LIST_ITEM.test(next) || /^\s+\S/.test(next)))
369
+ break;
370
+ current.push(candidate);
371
+ index += 1;
372
+ continue;
373
+ }
374
+ if (item && item[1].length <= baseIndent) {
375
+ if (current.length > 0)
376
+ items.push(current.join("\n").trimEnd());
377
+ current = [candidate];
378
+ }
379
+ else if (item || /^\s+\S/.test(candidate)) {
380
+ // An indented line belongs to the item above it, list marker or not.
381
+ current.push(candidate);
382
+ }
383
+ else {
384
+ break;
385
+ }
386
+ index += 1;
387
+ }
388
+ if (current.length > 0)
389
+ items.push(current.join("\n").trimEnd());
390
+ const ordered = /^\s*\d+[.)]\s/.test(items[0] || "");
391
+ blocks.push({ kind: "list", ordered, items, content: items.join("\n") });
392
+ continue;
393
+ }
394
+ const start = index;
395
+ while (index < lines.length && lines[index].trim() && !MARKDOWN_LIST_ITEM.test(lines[index]) && !MARKDOWN_FENCE.test(lines[index])) {
396
+ index += 1;
397
+ }
398
+ blocks.push({ kind: "text", content: lines.slice(start, index).join("\n").trimEnd() });
399
+ }
400
+ return blocks;
401
+ }
402
+ function serializeMarkdown(section) {
403
+ const parts = [];
404
+ if (section.level > 0)
405
+ parts.push(`${"#".repeat(section.level)} ${section.heading}`);
406
+ for (const block of section.blocks) {
407
+ parts.push(block.kind === "list" ? (block.items || []).join("\n") : block.content);
408
+ }
409
+ for (const child of section.children) {
410
+ parts.push(serializeMarkdown(child));
411
+ }
412
+ return parts.filter((part) => part.trim()).join("\n\n");
413
+ }
414
+ // ─────────────────────────────────────────
415
+ // HTML
416
+ // ─────────────────────────────────────────
417
+ const HTML_VOID_ELEMENTS = new Set([
418
+ "area", "base", "br", "col", "embed", "hr", "img", "input",
419
+ "link", "meta", "param", "source", "track", "wbr",
420
+ ]);
421
+ /**
422
+ * A note that arrives wrapped in one element of the page, unwrapped.
423
+ *
424
+ * A page whose note could only be reached through its own `main` hands back
425
+ * whatever the template put around it. Left whole, that wrapper is a single
426
+ * opaque block: none of the headings inside it can be seen, so two releases
427
+ * merged within it would only be stacked one after the other. Opened, the
428
+ * headings the model wrote are there to merge on.
429
+ */
430
+ function unwrapHtmlContainer(html) {
431
+ const elements = splitHtmlElements(html);
432
+ if (elements.length !== 1)
433
+ return html;
434
+ const container = /^<(div|section|main|article)\b[^>]*>([\s\S]*)<\/\1>$/i.exec(elements[0].trim());
435
+ // Only a wrapper is opened. An element holding no heading of the note's own
436
+ // is the note's own markup rather than something the page put around it.
437
+ if (!container || !/<h[1-6]\b/i.test(container[2]))
438
+ return html;
439
+ return unwrapHtmlContainer(container[2]);
440
+ }
441
+ function parseHtmlDocument(html) {
442
+ const root = { level: 0, heading: "", blocks: [], children: [] };
443
+ const open = [root];
444
+ for (const element of splitHtmlElements(unwrapHtmlContainer(html))) {
445
+ const heading = /^<h([1-6])\b[^>]*>([\s\S]*)<\/h\1>$/i.exec(element.trim());
446
+ if (!heading) {
447
+ open[open.length - 1].blocks.push(toHtmlBlock(element));
448
+ continue;
449
+ }
450
+ const level = Number(heading[1]);
451
+ while (open.length > 1 && open[open.length - 1].level >= level)
452
+ open.pop();
453
+ const section = { level, heading: heading[2].trim(), blocks: [], children: [] };
454
+ open[open.length - 1].children.push(section);
455
+ open.push(section);
456
+ }
457
+ return root;
458
+ }
459
+ function toHtmlBlock(element) {
460
+ const list = /^<(ul|ol)\b[^>]*>([\s\S]*)<\/\1>$/i.exec(element.trim());
461
+ if (!list)
462
+ return { kind: "text", content: element.trim() };
463
+ return {
464
+ kind: "list",
465
+ ordered: list[1].toLowerCase() === "ol",
466
+ items: splitHtmlListItems(list[2]),
467
+ content: element.trim(),
468
+ };
469
+ }
470
+ /**
471
+ * The top-level elements of an HTML fragment, in order.
472
+ *
473
+ * Depth is counted so that a list, a blockquote or a code block arrives whole,
474
+ * with whatever it contains.
475
+ */
476
+ function splitHtmlElements(html) {
477
+ const elements = [];
478
+ let depth = 0;
479
+ let current = [];
480
+ for (const line of html.replace(/\r\n/g, "\n").split("\n")) {
481
+ if (!line.trim() && depth === 0)
482
+ continue;
483
+ current.push(line);
484
+ depth += htmlDepthChange(line);
485
+ if (depth <= 0) {
486
+ const element = current.join("\n").trim();
487
+ if (element)
488
+ elements.push(element);
489
+ current = [];
490
+ depth = 0;
491
+ }
492
+ }
493
+ const trailing = current.join("\n").trim();
494
+ if (trailing)
495
+ elements.push(trailing);
496
+ return elements;
497
+ }
498
+ function htmlDepthChange(line) {
499
+ let change = 0;
500
+ for (const match of line.matchAll(/<(\/?)([a-zA-Z][\w-]*)\b[^>]*?(\/?)>/g)) {
501
+ const [, closing, name, selfClosing] = match;
502
+ if (HTML_VOID_ELEMENTS.has(name.toLowerCase()) || selfClosing)
503
+ continue;
504
+ change += closing ? -1 : 1;
505
+ }
506
+ return change;
507
+ }
508
+ function splitHtmlListItems(list) {
509
+ const items = [];
510
+ let depth = 0;
511
+ let current = [];
512
+ for (const line of list.split("\n")) {
513
+ const opensItem = depth === 0 && /^\s*<li\b/i.test(line);
514
+ if (opensItem && current.length > 0) {
515
+ items.push(current.join("\n").trim());
516
+ current = [];
517
+ }
518
+ if (!line.trim() && current.length === 0)
519
+ continue;
520
+ current.push(line);
521
+ depth = Math.max(0, depth + htmlDepthChange(line));
522
+ }
523
+ const trailing = current.join("\n").trim();
524
+ if (trailing)
525
+ items.push(trailing);
526
+ return items.filter(Boolean);
527
+ }
528
+ function serializeHtml(section) {
529
+ const parts = [];
530
+ if (section.level > 0)
531
+ parts.push(`<h${section.level}>${section.heading}</h${section.level}>`);
532
+ for (const block of section.blocks) {
533
+ if (block.kind !== "list") {
534
+ parts.push(block.content);
535
+ continue;
536
+ }
537
+ const tag = block.ordered ? "ol" : "ul";
538
+ parts.push([`<${tag}>`, ...(block.items || []), `</${tag}>`].join("\n"));
539
+ }
540
+ for (const child of section.children) {
541
+ parts.push(serializeHtml(child));
542
+ }
543
+ return parts.filter((part) => part.trim()).join("\n");
544
+ }
545
+ /**
546
+ * Find the release note inside a rendered HTML page.
547
+ *
548
+ * A page carries no mark of ours saying where the note begins: the template
549
+ * that produced it already says what surrounds it, and failing that the page's
550
+ * own `main` or `article` does. When neither answers — a template of yours this
551
+ * has never seen — nothing is returned, and the page is left whole rather than
552
+ * cut at a guessed place.
553
+ */
554
+ function releaseContentRange(page, template) {
555
+ const anchored = template ? betweenTemplateAnchors(page, template) : undefined;
556
+ if (anchored)
557
+ return anchored;
558
+ for (const element of ["main", "article"]) {
559
+ const match = new RegExp(`<${element}\\b[^>]*>([\\s\\S]*)</${element}>`, "i").exec(page);
560
+ if (!match)
561
+ continue;
562
+ // The opening tag is whatever the match holds beyond the content and the
563
+ // closing tag, so an element carrying attributes is measured, not assumed.
564
+ const start = match.index + match[0].length - match[1].length - element.length - "</>".length;
565
+ return { start, end: start + match[1].length, via: "element" };
566
+ }
567
+ return undefined;
568
+ }
569
+ /** Read the release note out of a rendered HTML page. */
570
+ function extractReleaseContent(page, template) {
571
+ const range = releaseContentRange(page, template);
572
+ if (!range)
573
+ return undefined;
574
+ const content = page.slice(range.start, range.end);
575
+ // An element found on the page may hold the page's own footer as well as the
576
+ // note; a template says exactly where the note ends, so nothing is stripped.
577
+ return range.via === "element"
578
+ ? content.replace(/<footer\b[^>]*>[\s\S]*?<\/footer>/gi, "").trim()
579
+ : content.trim();
580
+ }
581
+ /**
582
+ * Put a revised release note back on the page it was read out of.
583
+ *
584
+ * Only the note is replaced, so the page keeps its own head, styles, footer and
585
+ * every value the template filled in when it was generated. A page whose note
586
+ * cannot be told apart from the page's own wording is not rewritten at all:
587
+ * nothing is returned, and the caller reports the file as one to edit by hand.
588
+ */
589
+ function replaceReleaseContent(page, revised, template) {
590
+ const range = releaseContentRange(page, template);
591
+ if (!range)
592
+ return undefined;
593
+ // Reached the note through the page's own element, and the footer sits inside
594
+ // it: the footer is the page's wording rather than the release's, and a
595
+ // revision is not asked to touch it.
596
+ if (range.via === "element" && /<footer\b/i.test(page.slice(range.start, range.end))) {
597
+ return undefined;
598
+ }
599
+ return `${page.slice(0, range.start)}\n${revised.trim()}\n${page.slice(range.end)}`;
600
+ }
601
+ /**
602
+ * The text a template puts either side of `{{content}}`, used to find the note.
603
+ *
604
+ * Only the literal text next to the slot can be looked for: everything else in
605
+ * a template is a slot whose value differs from one release to the next. Text
606
+ * that appears more than once in the page is no landmark, and the page is left
607
+ * to the next reader rather than cut at the wrong place.
608
+ */
609
+ function betweenTemplateAnchors(page, template) {
610
+ const slot = template.indexOf("{{content}}");
611
+ if (slot < 0)
612
+ return undefined;
613
+ const opening = landmark(page, anchorsBefore(template.slice(0, slot)));
614
+ const closing = landmark(page, anchorsAfter(template.slice(slot + "{{content}}".length)));
615
+ if (opening === undefined || closing === undefined)
616
+ return undefined;
617
+ const from = page.indexOf(opening);
618
+ const to = page.indexOf(closing, from + opening.length);
619
+ if (to < 0)
620
+ return undefined;
621
+ return { start: from + opening.length, end: to, via: "template" };
622
+ }
623
+ /** The first anchor the page carries exactly once. */
624
+ function landmark(page, anchors) {
625
+ return anchors.find((anchor) => page.indexOf(anchor) >= 0 && page.indexOf(anchor) === page.lastIndexOf(anchor));
626
+ }
627
+ /**
628
+ * What a template writes just before `{{content}}`, the longest run first.
629
+ *
630
+ * A closing tag on a line of its own is no landmark — a page is full of them —
631
+ * so the whole run of literal text is offered before any part of it, and only
632
+ * shortened, line by line, when the page does not carry it. That is what a page
633
+ * written by an earlier revision of the template needs: the run has changed,
634
+ * the lines nearest the note have not.
635
+ */
636
+ function anchorsBefore(before) {
637
+ const lastSlot = before.lastIndexOf("}}");
638
+ const lines = (lastSlot < 0 ? before : before.slice(lastSlot + 2)).split("\n");
639
+ return lines
640
+ .map((_, index) => lines.slice(index).join("\n"))
641
+ .filter((anchor) => anchor.trim());
642
+ }
643
+ /** What a template writes just after `{{content}}`, the longest run first. */
644
+ function anchorsAfter(after) {
645
+ const nextSlot = after.indexOf("{{");
646
+ const lines = (nextSlot < 0 ? after : after.slice(0, nextSlot)).split("\n");
647
+ return lines
648
+ .map((_, index) => lines.slice(0, lines.length - index).join("\n"))
649
+ .filter((anchor) => anchor.trim());
650
+ }
651
+ //# sourceMappingURL=release-document.js.map