@kgdiff/cli 0.4.0 → 0.5.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 (61) hide show
  1. package/README.md +21 -4
  2. package/dist/args.d.ts +5 -0
  3. package/dist/args.d.ts.map +1 -1
  4. package/dist/args.js +6 -0
  5. package/dist/args.js.map +1 -1
  6. package/dist/diff-command.d.ts.map +1 -1
  7. package/dist/diff-command.js +7 -1
  8. package/dist/diff-command.js.map +1 -1
  9. package/dist/errors.d.ts +8 -2
  10. package/dist/errors.d.ts.map +1 -1
  11. package/dist/errors.js +21 -4
  12. package/dist/errors.js.map +1 -1
  13. package/dist/help.d.ts.map +1 -1
  14. package/dist/help.js +5 -0
  15. package/dist/help.js.map +1 -1
  16. package/dist/index.d.ts +1 -1
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +1 -1
  19. package/dist/index.js.map +1 -1
  20. package/dist/io.d.ts +5 -0
  21. package/dist/io.d.ts.map +1 -1
  22. package/dist/locale.d.ts +34 -1
  23. package/dist/locale.d.ts.map +1 -1
  24. package/dist/locale.js +65 -0
  25. package/dist/locale.js.map +1 -1
  26. package/dist/main.d.ts.map +1 -1
  27. package/dist/main.js +5 -2
  28. package/dist/main.js.map +1 -1
  29. package/dist/markdown.d.ts +12 -2
  30. package/dist/markdown.d.ts.map +1 -1
  31. package/dist/markdown.js +94 -11
  32. package/dist/markdown.js.map +1 -1
  33. package/dist/model.d.ts +42 -2
  34. package/dist/model.d.ts.map +1 -1
  35. package/dist/model.js +82 -0
  36. package/dist/model.js.map +1 -1
  37. package/dist/node-io.d.ts.map +1 -1
  38. package/dist/node-io.js +1 -0
  39. package/dist/node-io.js.map +1 -1
  40. package/dist/report.d.ts +1 -1
  41. package/dist/report.d.ts.map +1 -1
  42. package/dist/report.js +3 -3
  43. package/dist/report.js.map +1 -1
  44. package/dist/summary.d.ts +19 -4
  45. package/dist/summary.d.ts.map +1 -1
  46. package/dist/summary.js +105 -19
  47. package/dist/summary.js.map +1 -1
  48. package/package.json +6 -6
  49. package/src/args.ts +14 -0
  50. package/src/diff-command.ts +7 -1
  51. package/src/errors.ts +30 -4
  52. package/src/help.ts +5 -0
  53. package/src/index.ts +2 -0
  54. package/src/io.ts +5 -0
  55. package/src/locale.ts +123 -1
  56. package/src/main.ts +5 -2
  57. package/src/markdown.ts +128 -12
  58. package/src/model.ts +115 -2
  59. package/src/node-io.ts +1 -0
  60. package/src/report.ts +3 -3
  61. package/src/summary.ts +145 -22
package/src/locale.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * searched for.
5
5
  */
6
6
  import type { Locale, ReplayPhase } from '@kgdiff/core';
7
- import type { ChangeFamily } from './model.js';
7
+ import { type ChangeFamily, isDefinitionKey, type PossibleMatchSide } from './model.js';
8
8
  import type { Env } from './style.js';
9
9
 
10
10
  export const LOCALES: readonly Locale[] = ['en', 'zh-CN'];
@@ -67,13 +67,71 @@ export interface Messages {
67
67
  readonly byType: string;
68
68
  readonly untyped: string;
69
69
  readonly moreTypes: (n: number) => string;
70
+ /** Watched attributes (`--watch-attr`): changes flagged ⚑ for review first. */
71
+ readonly watch: {
72
+ /** How the default definition keys (`def`, `IAO:0000115`, …) are named. */
73
+ readonly definition: string;
74
+ /** After ⚑ under the diffstat bar: `Review first: definition changed in 10 hunks`. */
75
+ readonly line: (labels: readonly string[], hunks: number) => string;
76
+ /** After ⚑ in a hunk's summary: `definition`. */
77
+ readonly marker: (labels: readonly string[]) => string;
78
+ };
79
+ /** Pairings kgdiff considered but did not apply, listed after the hunks. */
80
+ readonly possible: {
81
+ readonly heading: string;
82
+ /** `“Saudi Aramco” → “Aramco”`; each side's id is added when both have the same name. */
83
+ readonly title: (before: PossibleMatchSide, after: PossibleMatchSide) => string;
84
+ readonly belowThreshold: (threshold: string) => string;
85
+ readonly ambiguous: string;
86
+ readonly evidence: (label: string, neighbors: string) => string;
87
+ /** Terminal: what "not applied" means and how to pair one. */
88
+ readonly hint: string;
89
+ readonly more: (n: number) => string;
90
+ };
70
91
  readonly markdown: {
71
92
  readonly legend: string;
72
93
  readonly more: (n: number) => string;
94
+ /** Heading of the block of hunks that change a watched attribute (after ⚑). */
95
+ readonly reviewFirst: string;
96
+ readonly reviewFirstHint: (labels: readonly string[]) => string;
97
+ readonly reviewFirstMore: (n: number) => string;
98
+ /** Like `possible.hint`, as Markdown. */
99
+ readonly possibleHint: string;
100
+ readonly possibleMore: (n: number) => string;
73
101
  readonly generatedBy: (generator: string) => string;
74
102
  };
75
103
  }
76
104
 
105
+ /**
106
+ * Display names of watched attribute keys, in order: the default definition keys are all
107
+ * “definition” (once), other keys are shown as they are.
108
+ */
109
+ export function watchLabels(keys: readonly string[], m: Messages): string[] {
110
+ const labels: string[] = [];
111
+ for (const key of keys) {
112
+ const label = isDefinitionKey(key) ? m.watch.definition : key;
113
+ if (!labels.includes(label)) labels.push(label);
114
+ }
115
+ return labels;
116
+ }
117
+
118
+ /**
119
+ * Both sides of a possible match, quoted and joined by `arrow`. When they share a name (two
120
+ * “Apple”s), `withId` adds each side's id, as hunk titles do for equally named nodes.
121
+ */
122
+ function possibleTitle(
123
+ before: PossibleMatchSide,
124
+ after: PossibleMatchSide,
125
+ quote: (name: string) => string,
126
+ withId: (quoted: string, id: string) => string,
127
+ arrow: string,
128
+ ): string {
129
+ const same = before.name === after.name;
130
+ const side = (s: PossibleMatchSide): string =>
131
+ same ? withId(quote(s.name), s.id) : quote(s.name);
132
+ return `${side(before)}${arrow}${side(after)}`;
133
+ }
134
+
77
135
  /** A count before and after the change. */
78
136
  export type Count = readonly [before: number, after: number];
79
137
 
@@ -123,12 +181,47 @@ const en: Messages = {
123
181
  byType: 'By type',
124
182
  untyped: '(untyped)',
125
183
  moreTypes: (n) => `… and ${plural(n, 'more type', 'more types')}`,
184
+ watch: {
185
+ definition: 'definition',
186
+ line: (labels, hunks) =>
187
+ `Review first: ${labels.join(', ')} changed in ${plural(hunks, 'hunk', 'hunks')}`,
188
+ marker: (labels) => labels.join(', '),
189
+ },
190
+ possible: {
191
+ heading: 'Possible matches',
192
+ title: (before, after) =>
193
+ possibleTitle(
194
+ before,
195
+ after,
196
+ (name) => `“${name}”`,
197
+ (quoted, id) => `${quoted} (${id})`,
198
+ ' → ',
199
+ ),
200
+ belowThreshold: (threshold) => `below the ${threshold} threshold`,
201
+ ambiguous: 'too close to another candidate',
202
+ evidence: (label, neighbors) => `name ${label} · neighbours ${neighbors}`,
203
+ hint:
204
+ 'Not paired, so listed as removed or added. To pair one, add a synonym or a ' +
205
+ 'replacement link, or lower --threshold.',
206
+ more: (n) => `… and ${formatInt(n)} more · --json lists all`,
207
+ },
126
208
  markdown: {
127
209
  legend:
128
210
  '🟩 added · 🟥 removed · 🟨 content (renames, attributes, types, synonyms) · ' +
129
211
  '🟦 structure (moves, relations) · 🟪 identity (merges, splits)',
130
212
  more: (n) =>
131
213
  `…and ${plural(n, 'more hunk', 'more hunks')}. Open the HTML report for the full list.`,
214
+ reviewFirst: 'Review first',
215
+ reviewFirstHint: (labels) =>
216
+ `These hunks change a watched attribute (${labels.join(', ')}). Such an edit can change ` +
217
+ 'what existing data means even when the diff looks small.',
218
+ reviewFirstMore: (n) => `…and ${formatInt(n)} more.`,
219
+ possibleHint:
220
+ 'kgdiff did not pair these nodes, so they are listed above as removed or added. If a ' +
221
+ 'pair is the same thing, add a synonym or a replacement link, or lower `--threshold`.',
222
+ possibleMore: (n) =>
223
+ `…and ${plural(n, 'more possible match', 'more possible matches')}. The HTML report ` +
224
+ "shows them in each node's details.",
132
225
  generatedBy: (generator) => `Generated by ${generator}`,
133
226
  },
134
227
  };
@@ -162,10 +255,39 @@ const zh: Messages = {
162
255
  byType: '按类型',
163
256
  untyped: '(无类型)',
164
257
  moreTypes: (n) => `… 另有 ${formatInt(n)} 个类型`,
258
+ watch: {
259
+ definition: '定义',
260
+ line: (labels, hunks) => `优先审查:${formatInt(hunks)} 组变更修改了${labels.join('、')}`,
261
+ marker: (labels) => labels.join('、'),
262
+ },
263
+ possible: {
264
+ heading: '可能的匹配',
265
+ title: (before, after) =>
266
+ possibleTitle(
267
+ before,
268
+ after,
269
+ (name) => `「${name}」`,
270
+ (quoted, id) => `${quoted}(${id})`,
271
+ '→',
272
+ ),
273
+ belowThreshold: (threshold) => `低于阈值 ${threshold}`,
274
+ ambiguous: '与其他候选过于接近',
275
+ evidence: (label, neighbors) => `名称 ${label} · 邻居 ${neighbors}`,
276
+ hint: '这些节点未配对,因此按删除或新增列出。如是同一节点,可补充别名或替换链接,或调低 --threshold。',
277
+ more: (n) => `… 另有 ${formatInt(n)} 对 · --json 列出全部`,
278
+ },
165
279
  markdown: {
166
280
  legend:
167
281
  '🟩 新增 · 🟥 删除 · 🟨 内容(改名、属性、类型、别名) · 🟦 结构(移动、关系) · 🟪 身份(合并、拆分、换 ID)',
168
282
  more: (n) => `……另有 ${formatInt(n)} 组变更未列出,完整列表请查看 HTML 报告。`,
283
+ reviewFirst: '优先审查',
284
+ reviewFirstHint: (labels) =>
285
+ `这些变更修改了受关注的属性(${labels.join('、')})。这类修改在差异里看起来很小,却可能改变已有数据的含义。`,
286
+ reviewFirstMore: (n) => `……另有 ${formatInt(n)} 组。`,
287
+ possibleHint:
288
+ 'kgdiff 没有配对这些节点,因此它们在上方按删除或新增列出。如果某一对其实是同一节点,可补充别名或替换链接,或调低 `--threshold`。',
289
+ possibleMore: (n) =>
290
+ `……另有 ${formatInt(n)} 对可能的匹配未列出,HTML 报告的节点详情中可以看到全部。`,
169
291
  generatedBy: (generator) => `由 ${generator} 生成`,
170
292
  },
171
293
  };
package/src/main.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * load the diff engine.
5
5
  */
6
6
  import { parseCommandLine, peekColorMode } from './args.js';
7
- import { debugEnabled, formatError } from './errors.js';
7
+ import { bugReportUrl, debugEnabled, formatError } from './errors.js';
8
8
  import { renderHelp } from './help.js';
9
9
  import type { CliIO } from './io.js';
10
10
  import { createPainter, isLightBackground, resolveColorLevel } from './style.js';
@@ -50,7 +50,10 @@ export async function main(argv: readonly string[], io: CliIO): Promise<number>
50
50
  resolveColorLevel(peekColorMode(argv), io.env, io.stderrIsTTY),
51
51
  light,
52
52
  );
53
- io.stderr.write(formatError(error, paint, debugEnabled(io.env.DEBUG)));
53
+ // The platform comes from `io` like every other side effect, so `main` stays runnable
54
+ // in-process and its output deterministic in tests.
55
+ const report = bugReportUrl(cliVersion(), io.runtime);
56
+ io.stderr.write(formatError(error, paint, debugEnabled(io.env.DEBUG), report));
54
57
  return 2;
55
58
  }
56
59
  }
package/src/markdown.ts CHANGED
@@ -1,11 +1,22 @@
1
1
  /**
2
2
  * GitHub-flavoured Markdown summary for PR comments and `$GITHUB_STEP_SUMMARY`
3
- * (docs/cli.md §Markdown summary): title, diffstat table, family legend and the hunk list
4
- * grouped by phase in `<details>` blocks. No HTML beyond `<details>` / `<summary>`.
3
+ * (docs/cli.md §Markdown summary): title, diffstat table, family legend, the hunks that change
4
+ * a watched attribute (review first), the hunk list grouped by phase and the possible matches,
5
+ * in `<details>` blocks. No HTML beyond `<details>` / `<summary>`.
5
6
  */
6
- import { type DiffResult, formatHunk, type Locale } from '@kgdiff/core';
7
- import { formatInt, messages } from './locale.js';
8
- import { type ChangeFamily, groupByPhase, hunkFamily, hunkGlyph, overview } from './model.js';
7
+ import { type DiffResult, formatHunk, type Hunk, type Locale } from '@kgdiff/core';
8
+ import { formatInt, messages, watchLabels } from './locale.js';
9
+ import {
10
+ type ChangeFamily,
11
+ DEFAULT_WATCH_ATTRS,
12
+ groupByPhase,
13
+ hunkFamily,
14
+ hunkGlyph,
15
+ overview,
16
+ percent,
17
+ possibleMatches,
18
+ watchedChanges,
19
+ } from './model.js';
9
20
  import { totalsText } from './summary.js';
10
21
  import { revealInvisible } from './width.js';
11
22
 
@@ -13,6 +24,12 @@ import { revealInvisible } from './width.js';
13
24
  export const MARKDOWN_HUNK_LIMIT = 100;
14
25
  /** Groups start expanded when the whole list is at most this long. */
15
26
  const OPEN_THRESHOLD = 30;
27
+ /** Hunks listed under "Review first" before "…and N more". */
28
+ export const MARKDOWN_REVIEW_LIMIT = 20;
29
+ /** Possible matches listed before "…and N more". */
30
+ export const MARKDOWN_POSSIBLE_LIMIT = 20;
31
+ /** The possible matches start expanded when there are at most this many. */
32
+ const POSSIBLE_OPEN_THRESHOLD = 10;
16
33
 
17
34
  const FAMILY_SQUARE: Readonly<Record<ChangeFamily, string>> = {
18
35
  added: '🟩',
@@ -61,6 +78,11 @@ export interface MarkdownOptions {
61
78
  readonly title: string;
62
79
  /** e.g. `kgdiff 0.1.0`. */
63
80
  readonly generator: string;
81
+ /**
82
+ * Attribute keys whose changes are flagged ⚑ for review first (`--watch-attr`). Default
83
+ * `DEFAULT_WATCH_ATTRS` (definitions); `[]` flags nothing.
84
+ */
85
+ readonly watch?: readonly string[];
64
86
  }
65
87
 
66
88
  /** Render the Markdown summary. Deterministic: no timestamps. */
@@ -90,6 +112,10 @@ export function renderMarkdown(diff: DiffResult, options: MarkdownOptions): stri
90
112
  m.markdown.legend,
91
113
  '',
92
114
  );
115
+ const watch = options.watch ?? DEFAULT_WATCH_ATTRS;
116
+ const watched = watchedChanges(diff, watch);
117
+ const item = (hunk: Hunk): string => hunkItem(hunk, diff, options.locale, watched.get(hunk.id));
118
+ out.push(...reviewFirstSection(diff, watched, watch, options.locale, item));
93
119
  let budget = MARKDOWN_HUNK_LIMIT;
94
120
  const open = ov.hunks <= OPEN_THRESHOLD ? ' open' : '';
95
121
  for (const group of groupByPhase(diff.hunks)) {
@@ -101,19 +127,109 @@ export function renderMarkdown(diff: DiffResult, options: MarkdownOptions): stri
101
127
  `<summary>${m.phase[group.phase]} (${formatInt(group.hunks.length)})</summary>`,
102
128
  '',
103
129
  );
104
- for (const hunk of listed) {
105
- const { title, subtitle } = formatHunk(hunk, diff, options.locale);
106
- const family = hunkFamily(hunk);
107
- const glyph = hunkGlyph(hunk) === '~' ? '\\~' : hunkGlyph(hunk);
108
- const note = subtitle ? ` — *${escapeMarkdown(subtitle)}*` : '';
109
- out.push(`- ${FAMILY_SQUARE[family]} ${glyph} ${escapeMarkdown(title)}${note}`);
110
- }
130
+ for (const hunk of listed) out.push(item(hunk));
111
131
  out.push('', '</details>', '');
112
132
  }
113
133
  if (ov.hunks > MARKDOWN_HUNK_LIMIT) {
114
134
  out.push(`*${escapeMarkdown(m.markdown.more(ov.hunks - MARKDOWN_HUNK_LIMIT))}*`, '');
115
135
  }
136
+ out.push(...possibleSection(diff, options.locale));
116
137
  }
117
138
  out.push(`*${escapeMarkdown(m.markdown.generatedBy(options.generator))}*`);
118
139
  return `${out.join('\n')}\n`;
119
140
  }
141
+
142
+ /**
143
+ * A hunk as a list item: family square, glyph, title, then its summary in italics, after
144
+ * `⚑ definition` when it changes a watched attribute.
145
+ */
146
+ function hunkItem(
147
+ hunk: Hunk,
148
+ diff: DiffResult,
149
+ locale: Locale,
150
+ watchedKeys: readonly string[] | undefined,
151
+ ): string {
152
+ const m = messages(locale);
153
+ const { title, subtitle } = formatHunk(hunk, diff, locale);
154
+ const glyph = hunkGlyph(hunk) === '~' ? '\\~' : hunkGlyph(hunk);
155
+ const flag = watchedKeys ? `⚑ ${m.watch.marker(watchLabels(watchedKeys, m))}` : '';
156
+ const note = [flag, subtitle].filter(Boolean).join(' · ');
157
+ return `- ${FAMILY_SQUARE[hunkFamily(hunk)]} ${glyph} ${escapeMarkdown(title)}${note ? ` — *${escapeMarkdown(note)}*` : ''}`;
158
+ }
159
+
160
+ /**
161
+ * The hunks that change a watched attribute, before the phase groups (which may start
162
+ * collapsed), in list order: a reworded definition can change what existing data means while
163
+ * the diff looks small. The same items in the groups carry the ⚑ marker. Empty when none.
164
+ */
165
+ function reviewFirstSection(
166
+ diff: DiffResult,
167
+ watched: ReadonlyMap<string, readonly string[]>,
168
+ watch: readonly string[],
169
+ locale: Locale,
170
+ item: (hunk: Hunk) => string,
171
+ ): string[] {
172
+ if (watched.size === 0) return [];
173
+ const m = messages(locale);
174
+ const keys = new Set<string>();
175
+ for (const list of watched.values()) for (const key of list) keys.add(key);
176
+ const labels = watchLabels(
177
+ watch.filter((k) => keys.has(k)),
178
+ m,
179
+ );
180
+ const flagged = groupByPhase(diff.hunks).flatMap((g) => g.hunks.filter((h) => watched.has(h.id)));
181
+ const out = [
182
+ '<details open>',
183
+ `<summary>⚑ ${m.markdown.reviewFirst} (${formatInt(flagged.length)})</summary>`,
184
+ '',
185
+ `*${escapeMarkdown(m.markdown.reviewFirstHint(labels))}*`,
186
+ '',
187
+ ];
188
+ for (const hunk of flagged.slice(0, MARKDOWN_REVIEW_LIMIT)) out.push(item(hunk));
189
+ if (flagged.length > MARKDOWN_REVIEW_LIMIT) {
190
+ out.push(
191
+ '',
192
+ `*${escapeMarkdown(m.markdown.reviewFirstMore(flagged.length - MARKDOWN_REVIEW_LIMIT))}*`,
193
+ );
194
+ }
195
+ out.push('', '</details>', '');
196
+ return out;
197
+ }
198
+
199
+ /**
200
+ * The possible matches (`possibleMatches`): pairings kgdiff did not apply between a node listed
201
+ * as removed and one listed as added. In a pull request comment they are what tells a reviewer
202
+ * that "removed X" and "added Y" may be one entity. Empty when there are none.
203
+ */
204
+ function possibleSection(diff: DiffResult, locale: Locale): string[] {
205
+ const possible = possibleMatches(diff);
206
+ if (possible.length === 0) return [];
207
+ const m = messages(locale);
208
+ const threshold = percent(diff.options.match.threshold);
209
+ const open = possible.length <= POSSIBLE_OPEN_THRESHOLD ? ' open' : '';
210
+ const out = [
211
+ `<details${open}>`,
212
+ `<summary>${m.possible.heading} (${formatInt(possible.length)})</summary>`,
213
+ '',
214
+ `*${m.markdown.possibleHint}*`,
215
+ '',
216
+ ];
217
+ for (const p of possible.slice(0, MARKDOWN_POSSIBLE_LIMIT)) {
218
+ const reason =
219
+ p.reason === 'ambiguous' ? m.possible.ambiguous : m.possible.belowThreshold(threshold);
220
+ const note = [
221
+ percent(p.score),
222
+ reason,
223
+ m.possible.evidence(percent(p.label), percent(p.neighbors)),
224
+ ].join(' · ');
225
+ out.push(`- ≈ ${escapeMarkdown(m.possible.title(p.before, p.after))} — *${note}*`);
226
+ }
227
+ if (possible.length > MARKDOWN_POSSIBLE_LIMIT) {
228
+ out.push(
229
+ '',
230
+ `*${escapeMarkdown(m.markdown.possibleMore(possible.length - MARKDOWN_POSSIBLE_LIMIT))}*`,
231
+ );
232
+ }
233
+ out.push('', '</details>', '');
234
+ return out;
235
+ }
package/src/model.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * Presentation model shared by every text output: hunk families, glyphs, name-status letters,
3
- * phase grouping and the per-phase counts behind the counters and the diffstat bar.
3
+ * phase grouping, the per-phase counts behind the counters and the diffstat bar, the watched
4
+ * attributes flagged for review first, and the possible matches listed after the hunks.
4
5
  */
5
- import type { DiffResult, Hunk, HunkKind, ReplayPhase } from '@kgdiff/core';
6
+ import type { DiffResult, Hunk, HunkKind, MatchSuggestion, ReplayPhase } from '@kgdiff/core';
6
7
 
7
8
  /** The five meaning families of docs/visual-language.md (mirrors `@kgdiff/scene`). */
8
9
  export type ChangeFamily = 'added' | 'removed' | 'content' | 'structure' | 'identity';
@@ -176,6 +177,118 @@ export function apportion(weights: readonly number[], total: number): number[] {
176
177
  return cells;
177
178
  }
178
179
 
180
+ /**
181
+ * Attributes watched by default: definitions, under the keys the formats give them (OBO `def`,
182
+ * kgdiff JSON `definition`, `IAO:0000115` for OBO ontologies in RDF, `skos:definition`). A
183
+ * reworded definition can change what existing data means while the diff looks small.
184
+ */
185
+ export const DEFAULT_WATCH_ATTRS: readonly string[] = [
186
+ 'def',
187
+ 'definition',
188
+ 'IAO:0000115',
189
+ 'skos:definition',
190
+ ];
191
+
192
+ const DEFINITION_KEYS: ReadonlySet<string> = new Set(DEFAULT_WATCH_ATTRS);
193
+
194
+ /** Whether `key` is one of the default definition keys, shown as “definition”. */
195
+ export function isDefinitionKey(key: string): boolean {
196
+ return DEFINITION_KEYS.has(key);
197
+ }
198
+
199
+ /**
200
+ * The watched attributes each hunk changes, by hunk id, in `watch` order; hunks that change
201
+ * none are absent. Only attribute changes of matched nodes count: an added or removed node's
202
+ * definition is part of that addition or removal, not a change to a definition. Ignored
203
+ * attributes (`ignoreAttrs`) never show up here, since the diff does not report them. O(changes).
204
+ */
205
+ export function watchedChanges(
206
+ diff: DiffResult,
207
+ watch: readonly string[],
208
+ ): ReadonlyMap<string, readonly string[]> {
209
+ const watched = new Set(watch);
210
+ const byHunk = new Map<string, readonly string[]>();
211
+ if (watched.size === 0) return byHunk;
212
+ for (const hunk of diff.hunks) {
213
+ const keys = new Set<string>();
214
+ for (const id of hunk.nodes) {
215
+ for (const facet of diff.index.node(id)?.facets ?? []) {
216
+ if (facet.kind !== 'attrs') continue;
217
+ for (const change of facet.changes) if (watched.has(change.key)) keys.add(change.key);
218
+ }
219
+ }
220
+ if (keys.size > 0)
221
+ byHunk.set(
222
+ hunk.id,
223
+ [...watched].filter((k) => keys.has(k)),
224
+ );
225
+ }
226
+ return byHunk;
227
+ }
228
+
229
+ /** One side of a possible match: the node's id in its version and the name shown for it. */
230
+ export interface PossibleMatchSide {
231
+ readonly id: string;
232
+ readonly name: string;
233
+ }
234
+
235
+ /** A pairing kgdiff considered but did not apply (a `MatchSuggestion`), ready to list. */
236
+ export interface PossibleMatch {
237
+ readonly before: PossibleMatchSide;
238
+ readonly after: PossibleMatchSide;
239
+ readonly score: number;
240
+ readonly reason: MatchSuggestion['reason'];
241
+ /** Label and neighbourhood evidence, 0..1. */
242
+ readonly label: number;
243
+ readonly neighbors: number;
244
+ }
245
+
246
+ /** Longest name shown for either side (as hunk titles shorten names, @kgdiff/core i18n). */
247
+ const MAX_POSSIBLE_NAME = 40;
248
+
249
+ function shortName(label: string): string {
250
+ const chars = Array.from(label);
251
+ return chars.length > MAX_POSSIBLE_NAME
252
+ ? `${chars.slice(0, MAX_POSSIBLE_NAME - 1).join('')}…`
253
+ : label;
254
+ }
255
+
256
+ const byCodePoint = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);
257
+
258
+ /**
259
+ * The suggestions a reviewer of the text outputs needs to see: pairings kgdiff did not apply
260
+ * where the before node is reported removed or the after node added, so that "removed X, added
261
+ * Y" can be read as "maybe X became Y". The viewer's detail panel lists the same ones. Names
262
+ * are the label each node had in its own version. Highest score first, then by ids.
263
+ */
264
+ export function possibleMatches(diff: DiffResult): PossibleMatch[] {
265
+ const list: PossibleMatch[] = [];
266
+ for (const s of diff.suggestions) {
267
+ const before = diff.index.nodeByBefore(s.before);
268
+ const after = diff.index.nodeByAfter(s.after);
269
+ if (before?.status !== 'removed' && after?.status !== 'added') continue;
270
+ list.push({
271
+ before: { id: s.before, name: shortName(before?.before?.label ?? before?.label ?? s.before) },
272
+ after: { id: s.after, name: shortName(after?.after?.label ?? after?.label ?? s.after) },
273
+ score: s.score,
274
+ reason: s.reason,
275
+ label: s.evidence.label,
276
+ neighbors: s.evidence.neighbors,
277
+ });
278
+ }
279
+ return list.sort(
280
+ (x, y) =>
281
+ y.score - x.score ||
282
+ byCodePoint(x.before.id, y.before.id) ||
283
+ byCodePoint(x.after.id, y.after.id),
284
+ );
285
+ }
286
+
287
+ /** A score or evidence value as a whole percentage: `0.796` → `80%`. */
288
+ export function percent(value: number): string {
289
+ return `${Math.round(value * 100)}%`;
290
+ }
291
+
179
292
  export function assertNever(value: never): never {
180
293
  throw new Error(`Unexpected value: ${String(value)}`);
181
294
  }
package/src/node-io.ts CHANGED
@@ -138,6 +138,7 @@ export function nodeIO(): CliIO {
138
138
  stderrIsTTY: process.stderr.isTTY === true,
139
139
  stdinIsTTY: process.stdin.isTTY === true,
140
140
  columns: process.stdout.isTTY ? process.stdout.columns : undefined,
141
+ runtime: `${process.platform} ${process.arch}, Node.js ${process.version}`,
141
142
  now: () => new Date(),
142
143
  makeTempDir: () => mkdtemp(join(tmpdir(), 'kgdiff-')),
143
144
  openFile,
package/src/report.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * Build the `ReportPayload` embedded in HTML reports: diff (`diffToJSON`) + layout
2
+ * Build the `ReportPayload` embedded in HTML reports: packed diff (`packDiffJSON`) + layout
3
3
  * (`layoutToJSON`) + meta + initial view preferences. `@kgdiff/layout` and `node:zlib` are
4
4
  * loaded on demand, so text outputs never pay for them.
5
5
  */
6
- import { type DiffResult, diffToJSON, type Locale } from '@kgdiff/core';
6
+ import { type DiffResult, diffToJSON, type Locale, packDiffJSON } from '@kgdiff/core';
7
7
  import type { ReportPayload, ThemePreference, ViewerMode, ViewerScope } from '@kgdiff/viewer';
8
8
  import { renderReportHtml } from './html.js';
9
9
 
@@ -34,7 +34,7 @@ export async function buildReportPayload(
34
34
  return {
35
35
  format: 'kgdiff.report',
36
36
  version: 1,
37
- diff: diffToJSON(diff),
37
+ diff: packDiffJSON(diffToJSON(diff)),
38
38
  layout,
39
39
  meta: {
40
40
  title: info.title,