@khanglvm/relay 0.18.0 → 0.20.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 (138) hide show
  1. package/bin/rly.js +1 -1
  2. package/package.json +39 -4
  3. package/schema/spec.v1.json +1368 -0
  4. package/src/a2ui/compile.js +2 -0
  5. package/src/cli/args.js +46 -0
  6. package/src/cli/ask.js +12 -0
  7. package/src/cli/boards.js +326 -0
  8. package/src/cli/config.js +56 -0
  9. package/src/cli/context.js +13 -0
  10. package/src/cli/git.js +183 -0
  11. package/src/cli/help.js +90 -0
  12. package/src/cli/index.js +103 -0
  13. package/src/cli/install.js +197 -0
  14. package/src/cli/io.js +186 -0
  15. package/src/cli/mcp.js +94 -0
  16. package/src/cli/share.js +45 -0
  17. package/src/cli/skill.js +192 -0
  18. package/src/cli/upgrade.js +130 -0
  19. package/src/cli/wait.js +172 -0
  20. package/src/file-preview.js +1 -1
  21. package/src/index.js +104 -0
  22. package/src/link.js +1 -0
  23. package/src/mcp-ui/board/block-ctx.js +43 -0
  24. package/src/mcp-ui/board/bridge.js +165 -0
  25. package/src/mcp-ui/board/controls.js +310 -0
  26. package/src/mcp-ui/board/core.js +20 -0
  27. package/src/mcp-ui/board/lifecycle.js +118 -0
  28. package/src/mcp-ui/board/normalize.js +95 -0
  29. package/src/mcp-ui/board/render.js +200 -0
  30. package/src/mcp-ui/board/state.js +106 -0
  31. package/src/mcp-ui/board/vendors.js +86 -0
  32. package/src/mcp.js +15 -21
  33. package/src/{server.js → server/board.js} +17 -781
  34. package/src/server/files.js +141 -0
  35. package/src/server/http.js +114 -0
  36. package/src/server/index.js +2 -0
  37. package/src/server/page.js +183 -0
  38. package/src/server/paths.js +7 -0
  39. package/src/server/result.js +58 -0
  40. package/src/server/reviews.js +41 -0
  41. package/src/server/sanitize.js +231 -0
  42. package/src/spec/blocks/a2ui.js +25 -0
  43. package/src/spec/blocks/chart.js +49 -0
  44. package/src/spec/blocks/code.js +38 -0
  45. package/src/spec/blocks/diagram.js +39 -0
  46. package/src/spec/blocks/git-conflict.js +106 -0
  47. package/src/spec/blocks/image.js +32 -0
  48. package/src/spec/blocks/index.js +33 -0
  49. package/src/spec/blocks/markdown.js +13 -0
  50. package/src/spec/blocks/pdf.js +38 -0
  51. package/src/spec/blocks/table.js +122 -0
  52. package/src/spec/blocks/video.js +68 -0
  53. package/src/spec/blocks/widgets.js +98 -0
  54. package/src/spec/constants.js +65 -0
  55. package/src/spec/index.js +5 -0
  56. package/src/spec/normalize.js +285 -0
  57. package/src/spec/ready.js +106 -0
  58. package/src/spec/schema.js +182 -0
  59. package/src/spec/sources.js +83 -0
  60. package/src/ui/annotate/api.js +149 -0
  61. package/src/ui/annotate/badges.js +77 -0
  62. package/src/ui/annotate/chrome.js +158 -0
  63. package/src/ui/annotate/core.js +134 -0
  64. package/src/ui/annotate/highlights.js +129 -0
  65. package/src/ui/annotate/mutations.js +127 -0
  66. package/src/ui/annotate/popover.js +206 -0
  67. package/src/ui/annotate/summary.js +67 -0
  68. package/src/ui/app/annotations.js +88 -0
  69. package/src/ui/app/autosave.js +44 -0
  70. package/src/ui/app/core.js +74 -0
  71. package/src/ui/app/drafts.js +201 -0
  72. package/src/ui/app/heartbeat.js +150 -0
  73. package/src/ui/app/iframe-bridge.js +64 -0
  74. package/src/ui/app/persistence.js +117 -0
  75. package/src/ui/app/prefilled.js +21 -0
  76. package/src/ui/app/presence.js +38 -0
  77. package/src/ui/app/question-color.js +67 -0
  78. package/src/ui/app/questions.js +360 -0
  79. package/src/ui/app/render.js +135 -0
  80. package/src/ui/app/share.js +108 -0
  81. package/src/ui/app/submit.js +109 -0
  82. package/src/ui/app/theme.js +63 -0
  83. package/src/ui/blocks/api.js +1 -0
  84. package/src/ui/blocks/chart.js +222 -0
  85. package/src/ui/blocks/code.js +138 -0
  86. package/src/ui/blocks/compare.js +82 -0
  87. package/src/ui/blocks/core.js +74 -0
  88. package/src/ui/blocks/diff.js +361 -0
  89. package/src/ui/blocks/dispatch.js +111 -0
  90. package/src/ui/blocks/file-links.js +180 -0
  91. package/src/ui/blocks/git-conflict.js +151 -0
  92. package/src/ui/blocks/graphviz.js +57 -0
  93. package/src/ui/blocks/html.js +45 -0
  94. package/src/ui/blocks/image.js +371 -0
  95. package/src/ui/blocks/kpi.js +26 -0
  96. package/src/ui/blocks/markdown.js +223 -0
  97. package/src/ui/blocks/mermaid.js +242 -0
  98. package/src/ui/blocks/palette.js +59 -0
  99. package/src/ui/blocks/pdf.js +21 -0
  100. package/src/ui/blocks/plantuml.js +152 -0
  101. package/src/ui/blocks/table.js +155 -0
  102. package/src/ui/blocks/typography.js +25 -0
  103. package/src/ui/blocks/vendor.js +43 -0
  104. package/src/ui/blocks/video.js +43 -0
  105. package/src/ui/blocks/viewer-fullscreen.js +146 -0
  106. package/src/ui/blocks/viewer.js +324 -0
  107. package/src/ui/kit.js +1 -0
  108. package/src/ui/manifest.js +140 -0
  109. package/types/a2ui/compile.d.ts +40 -0
  110. package/types/index.d.ts +181 -0
  111. package/types/mcp.d.ts +31 -0
  112. package/types/spec/blocks/a2ui.d.ts +4 -0
  113. package/types/spec/blocks/chart.d.ts +4 -0
  114. package/types/spec/blocks/code.d.ts +10 -0
  115. package/types/spec/blocks/diagram.d.ts +15 -0
  116. package/types/spec/blocks/git-conflict.d.ts +7 -0
  117. package/types/spec/blocks/image.d.ts +5 -0
  118. package/types/spec/blocks/index.d.ts +30 -0
  119. package/types/spec/blocks/markdown.d.ts +5 -0
  120. package/types/spec/blocks/pdf.d.ts +4 -0
  121. package/types/spec/blocks/table.d.ts +9 -0
  122. package/types/spec/blocks/video.d.ts +4 -0
  123. package/types/spec/blocks/widgets.d.ts +21 -0
  124. package/types/spec/constants.d.ts +67 -0
  125. package/types/spec/index.d.ts +4 -0
  126. package/types/spec/normalize.d.ts +17 -0
  127. package/types/spec/ready.d.ts +1 -0
  128. package/types/spec/schema.d.ts +1171 -0
  129. package/types/spec/sources.d.ts +14 -0
  130. package/types/store.d.ts +29 -0
  131. package/types/ui/manifest.d.ts +62 -0
  132. package/types/util.d.ts +6 -0
  133. package/src/cli.js +0 -1766
  134. package/src/mcp-ui/board.js +0 -1162
  135. package/src/spec.js +0 -1222
  136. package/src/ui/annotate.js +0 -1055
  137. package/src/ui/app.js +0 -1643
  138. package/src/ui/blocks.js +0 -3260
@@ -0,0 +1,231 @@
1
+ // Cleans what a page posts (replies, annotations, edits, A2UI state) before it is stored.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { assertSafeJson } from '../a2ui/compile.js';
5
+ import { artifactDirPath } from '../store.js';
6
+ import { ARTIFACT_MAX_BYTES, ARTIFACT_MIMES } from './result.js';
7
+
8
+ // Validates + sanitizes one annotation's threaded replies. Keeps only
9
+ // well-formed {author, text, createdAt} entries; caps at 50; coerces author.
10
+ function sanitizeReplies(value) {
11
+ if (!Array.isArray(value)) return [];
12
+ const out = [];
13
+ for (const r of value) {
14
+ if (out.length >= 50) break;
15
+ if (r === null || typeof r !== 'object' || Array.isArray(r)) continue;
16
+ if (typeof r.text !== 'string' || r.text.length > 5000) continue;
17
+ const author = r.author === 'agent' ? 'agent' : 'user';
18
+ const createdAt = typeof r.createdAt === 'string' ? r.createdAt : new Date().toISOString();
19
+ out.push({ author, text: r.text, createdAt });
20
+ }
21
+ return out;
22
+ }
23
+
24
+ // Validates + sanitizes an incoming annotations array (from draft/submit).
25
+ // Drops anything that isn't a well-formed annotation object; caps at 500.
26
+ // Each annotation may carry an optional author ('user'|'agent', default
27
+ // 'user') and a threaded replies array (validated + capped at 50).
28
+ function sanitizeAnnotationCrop(value, boardId) {
29
+ if (!value || typeof value !== 'object' || Array.isArray(value) || !boardId) return null;
30
+ const rawPath = typeof value.path === 'string' ? value.path : '';
31
+ if (!rawPath) return null;
32
+ const base = path.resolve(artifactDirPath(boardId)) + path.sep;
33
+ const resolved = path.resolve(rawPath);
34
+ if (!resolved.startsWith(base)) return null;
35
+ let stat;
36
+ try { stat = fs.statSync(resolved); } catch { return null; }
37
+ if (!stat.isFile() || stat.size < 1 || stat.size > ARTIFACT_MAX_BYTES) return null;
38
+ const mime = ARTIFACT_MIMES[value.mime] ? value.mime : 'image/png';
39
+ return {
40
+ path: resolved,
41
+ name: path.basename(resolved),
42
+ mime,
43
+ bytes: stat.size,
44
+ width: Math.max(1, Math.min(10000, Number.parseInt(value.width, 10) || 1)),
45
+ height: Math.max(1, Math.min(10000, Number.parseInt(value.height, 10) || 1)),
46
+ };
47
+ }
48
+
49
+ function sanitizeAnnotationTarget(value, boardId) {
50
+ const clean = { ...value };
51
+ delete clean.cropDataUrl;
52
+ if (clean.kind !== 'image-region') {
53
+ delete clean.crop;
54
+ return clean;
55
+ }
56
+ const unit = (v) => Math.max(0, Math.min(1, Number(v) || 0));
57
+ clean.x = unit(clean.x);
58
+ clean.y = unit(clean.y);
59
+ clean.w = unit(clean.w);
60
+ clean.h = unit(clean.h);
61
+ if (clean.x + clean.w > 1) clean.w = 1 - clean.x;
62
+ if (clean.y + clean.h > 1) clean.h = 1 - clean.y;
63
+ clean.label = limitString(clean.label, 200);
64
+ if (clean.side !== 'before' && clean.side !== 'after') delete clean.side;
65
+ const crop = sanitizeAnnotationCrop(clean.crop, boardId);
66
+ if (crop) clean.crop = crop;
67
+ else delete clean.crop;
68
+ return clean;
69
+ }
70
+
71
+ export function sanitizeAnnotations(value, boardId) {
72
+ if (!Array.isArray(value)) return [];
73
+ const out = [];
74
+ for (const a of value) {
75
+ if (out.length >= 500) break;
76
+ if (a === null || typeof a !== 'object' || Array.isArray(a)) continue;
77
+ if (typeof a.text !== 'string' || a.text.length > 5000) continue;
78
+ if (a.target === null || typeof a.target !== 'object' || Array.isArray(a.target)) continue;
79
+ const clean = {
80
+ ...a,
81
+ target: sanitizeAnnotationTarget(a.target, boardId),
82
+ author: a.author === 'agent' ? 'agent' : 'user',
83
+ };
84
+ if (a.replies !== undefined) clean.replies = sanitizeReplies(a.replies);
85
+ out.push(clean);
86
+ }
87
+ return out;
88
+ }
89
+
90
+ function limitString(v, max) {
91
+ return typeof v === 'string' ? v.slice(0, max) : '';
92
+ }
93
+
94
+ function sanitizeConflictResolution(value) {
95
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
96
+ if (value.type !== 'git-conflict-resolution') return null;
97
+ const out = {
98
+ type: 'git-conflict-resolution',
99
+ filename: limitString(value.filename, 500),
100
+ file: limitString(value.file, 1200),
101
+ resolved: value.resolved === true,
102
+ resolutions: {},
103
+ content: limitString(value.content, 512 * 1024),
104
+ };
105
+ const raw = value.resolutions && typeof value.resolutions === 'object' && !Array.isArray(value.resolutions)
106
+ ? value.resolutions
107
+ : {};
108
+ let n = 0;
109
+ for (const id of Object.keys(raw)) {
110
+ if (n >= 200) break;
111
+ const r = raw[id];
112
+ if (!r || typeof r !== 'object' || Array.isArray(r)) continue;
113
+ const choice = limitString(r.choice, 30);
114
+ if (!['ours', 'theirs', 'both', 'custom'].includes(choice)) continue;
115
+ out.resolutions[limitString(id, 80)] = {
116
+ choice,
117
+ value: limitString(r.value, 128 * 1024),
118
+ };
119
+ n++;
120
+ }
121
+ return Object.keys(out.resolutions).length ? out : null;
122
+ }
123
+
124
+ function sanitizeDiffReview(value) {
125
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
126
+ if (value.type !== 'diff-review') return null;
127
+ const out = {
128
+ type: 'diff-review',
129
+ reviewKind: limitString(value.reviewKind, 80),
130
+ commit: limitString(value.commit, 120),
131
+ title: limitString(value.title, 500),
132
+ resolved: value.resolved === true,
133
+ hunks: {},
134
+ };
135
+ const raw = value.hunks && typeof value.hunks === 'object' && !Array.isArray(value.hunks)
136
+ ? value.hunks
137
+ : {};
138
+ let n = 0;
139
+ for (const id of Object.keys(raw)) {
140
+ if (n >= 500) break;
141
+ const h = raw[id];
142
+ if (!h || typeof h !== 'object' || Array.isArray(h)) continue;
143
+ const choice = limitString(h.choice, 30);
144
+ if (!['apply', 'skip', 'hold'].includes(choice)) continue;
145
+ out.hunks[limitString(id, 80)] = {
146
+ choice,
147
+ file: limitString(h.file, 1200),
148
+ header: limitString(h.header, 500),
149
+ };
150
+ n++;
151
+ }
152
+ return Object.keys(out.hunks).length ? out : null;
153
+ }
154
+
155
+ // An a2ui block's state: the widget's data model (inputs the user changed) and
156
+ // the button events they fired, in order. Bounded like every other edit.
157
+ const A2UI_STATE_MAX_BYTES = 64 * 1024;
158
+ const A2UI_EVENTS_MAX = 50;
159
+ function sanitizeA2uiState(value) {
160
+ if (!value || typeof value !== 'object' || Array.isArray(value) || value.type !== 'a2ui') return null;
161
+ try {
162
+ assertSafeJson(value.data ?? {}, 'a2ui state');
163
+ const events = (Array.isArray(value.events) ? value.events : []).slice(-A2UI_EVENTS_MAX).flatMap((e) => {
164
+ if (!e || typeof e !== 'object' || typeof e.name !== 'string' || !/^[a-z][a-z0-9_-]{0,39}$/.test(e.name)) return [];
165
+ const context = e.context && typeof e.context === 'object' && !Array.isArray(e.context) ? e.context : {};
166
+ assertSafeJson(context, 'a2ui event');
167
+ if (JSON.stringify(context).length > 4096) return [];
168
+ return [{ name: e.name, context, at: limitString(e.at, 40) }];
169
+ });
170
+ const data = value.data && typeof value.data === 'object' && !Array.isArray(value.data) ? value.data : {};
171
+ if (JSON.stringify(data).length > A2UI_STATE_MAX_BYTES) return null;
172
+ return { type: 'a2ui', data, events };
173
+ } catch {
174
+ return null;
175
+ }
176
+ }
177
+
178
+ // Validates + sanitizes an incoming blockEdits map (from draft/submit).
179
+ // String values are editable Mermaid source. Structured git-conflict-resolution
180
+ // and diff-review values carry bounded per-hunk choices. Caps prevent a draft
181
+ // from bloating board storage; invalid entries are dropped.
182
+ export function sanitizeBlockEdits(value) {
183
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return {};
184
+ const out = {};
185
+ let n = 0;
186
+ for (const key of Object.keys(value)) {
187
+ if (n >= 50) break;
188
+ if (typeof key !== 'string') continue;
189
+ const v = value[key];
190
+ if (typeof v === 'string') {
191
+ if (v.length > 20000) continue;
192
+ out[key] = v;
193
+ } else {
194
+ const edit = sanitizeConflictResolution(v) || sanitizeDiffReview(v) || sanitizeA2uiState(v);
195
+ if (!edit) continue;
196
+ out[key] = edit;
197
+ }
198
+ n++;
199
+ }
200
+ return out;
201
+ }
202
+
203
+ // Resolves a block by id + type from the board, any question, or any option.
204
+ export function findBlock(spec, blockId, type) {
205
+ const scan = (blocks) => (Array.isArray(blocks) ? blocks.find((b) => b && b.id === blockId && b.type === type) : undefined);
206
+ const board = scan(spec.blocks);
207
+ if (board) return board;
208
+ for (const q of spec.questions) {
209
+ const hit = scan(q.blocks);
210
+ if (hit) return hit;
211
+ for (const o of Array.isArray(q.options) ? q.options : []) {
212
+ const opt = o && scan(o.blocks);
213
+ if (opt) return opt;
214
+ }
215
+ }
216
+ return undefined;
217
+ }
218
+
219
+ export function findHtmlBlock(spec, blockId) {
220
+ return findBlock(spec, blockId, 'html');
221
+ }
222
+
223
+ // The board's first html block (legacy /html/board alias).
224
+ export function firstBoardHtml(spec) {
225
+ return (spec.blocks || []).find((b) => b && b.type === 'html');
226
+ }
227
+
228
+ // A question's first html block (legacy /html/q/<id> alias).
229
+ export function firstQuestionHtml(q) {
230
+ return (q.blocks || []).find((b) => b && b.type === 'html');
231
+ }
@@ -0,0 +1,25 @@
1
+ // The a2ui block. Express text compiles later, in assertSpecReady.
2
+ import { assertSafeJson, guardExpress, validateSurface } from '../../a2ui/compile.js';
3
+ import { CliError } from '../../util.js';
4
+ import { asStr, clampInt } from '../sources.js';
5
+ import { BLOCK_HEIGHT } from '../constants.js';
6
+
7
+ // Normalizes one a2ui block. `id` is the already-assigned block id.
8
+ export function normalizeA2uiBlock(rawBlock, id, cwd, where, hasHeight) {
9
+ // A live A2UI v1.0 widget: Express text (compiled in assertSpecReady) or
10
+ // ready JSON components, checked against Relay's catalog either way.
11
+ const hasExpress = rawBlock.express !== undefined && rawBlock.express !== null;
12
+ const hasComponents = rawBlock.components !== undefined && rawBlock.components !== null;
13
+ if (hasExpress === hasComponents) throw new CliError(`${where}: a2ui block needs exactly one of "express" (A2UI Express text) or "components" (JSON list).`);
14
+ const block = { id, type: 'a2ui' };
15
+ if (rawBlock.title !== undefined) block.title = asStr(rawBlock.title);
16
+ if (hasHeight) block.height = clampInt(rawBlock.height, BLOCK_HEIGHT.min, BLOCK_HEIGHT.max, undefined);
17
+ if (hasExpress) {
18
+ if (rawBlock.dataModel !== undefined) throw new CliError(`${where}: with "express", set data with \`$/path = value\` lines, not "dataModel".`);
19
+ block.express = guardExpress(rawBlock.express, where);
20
+ return block;
21
+ }
22
+ assertSafeJson(rawBlock.components, where);
23
+ const surface = validateSurface({ components: rawBlock.components, dataModel: rawBlock.dataModel }, where);
24
+ return Object.assign(block, surface);
25
+ }
@@ -0,0 +1,49 @@
1
+ // The chart block.
2
+ import { CliError } from '../../util.js';
3
+ import { asStr, clampInt } from '../sources.js';
4
+ import { BLOCK_HEIGHT, CHART_KINDS } from '../constants.js';
5
+
6
+ // Normalizes one chart block. `id` is the already-assigned block id.
7
+ export function normalizeChartBlock(rawBlock, id, cwd, where, hasHeight) {
8
+ const hasConfig = rawBlock.config && typeof rawBlock.config === 'object' && !Array.isArray(rawBlock.config);
9
+ const hasShorthand =
10
+ typeof rawBlock.kind === 'string' ||
11
+ Array.isArray(rawBlock.labels) ||
12
+ Array.isArray(rawBlock.series);
13
+ if (!hasConfig && !hasShorthand) {
14
+ throw new CliError(`${where}: chart needs "config" (full Chart.js config) or "kind"+"labels"+"series".`);
15
+ }
16
+ const block = { id, type: 'chart' };
17
+ block.height = clampInt(rawBlock.height, BLOCK_HEIGHT.min, BLOCK_HEIGHT.max, 320);
18
+ if (hasConfig) {
19
+ block.config = rawBlock.config;
20
+ return block;
21
+ }
22
+ // Shorthand form: validate kind/labels/series.
23
+ const kind = asStr(rawBlock.kind).trim().toLowerCase();
24
+ if (!kind) throw new CliError(`${where}: chart shorthand needs a "kind" (${CHART_KINDS.join('|')}).`);
25
+ if (!CHART_KINDS.includes(kind)) {
26
+ throw new CliError(`${where}: unknown chart kind "${rawBlock.kind}". Valid: ${CHART_KINDS.join(', ')}.`);
27
+ }
28
+ if (!Array.isArray(rawBlock.labels)) {
29
+ throw new CliError(`${where}: chart shorthand needs a "labels" array.`);
30
+ }
31
+ if (!Array.isArray(rawBlock.series) || rawBlock.series.length < 1) {
32
+ throw new CliError(`${where}: chart shorthand needs a non-empty "series" array of {label, data[]}.`);
33
+ }
34
+ block.kind = kind;
35
+ block.labels = rawBlock.labels.map((l) => asStr(l));
36
+ block.series = rawBlock.series.map((s, k) => {
37
+ if (s === null || typeof s !== 'object' || Array.isArray(s)) {
38
+ throw new CliError(`${where}.series[${k}]: must be an object {label, data[]}.`);
39
+ }
40
+ if (!Array.isArray(s.data)) {
41
+ throw new CliError(`${where}.series[${k}]: needs a "data" array.`);
42
+ }
43
+ const out = { label: asStr(s.label), data: s.data };
44
+ if (s.color !== undefined) out.color = asStr(s.color);
45
+ return out;
46
+ });
47
+ if (rawBlock.title !== undefined) block.title = asStr(rawBlock.title);
48
+ return block;
49
+ }
@@ -0,0 +1,38 @@
1
+ // The code and diff blocks.
2
+ import path from 'node:path';
3
+ import { CliError } from '../../util.js';
4
+ import { asStr, clampInt, readTextSource } from '../sources.js';
5
+ import { BLOCK_HEIGHT } from '../constants.js';
6
+
7
+ // Normalizes one code block. `id` is the already-assigned block id.
8
+ export function normalizeCodeBlock(rawBlock, id, cwd, where, hasHeight) {
9
+ const code = readTextSource(rawBlock, 'code', 'codeFile', cwd, where);
10
+ if (!code) throw new CliError(`${where}: code block needs a "code" string or a readable "codeFile".`);
11
+ const block = { id, type: 'code', code };
12
+ if (rawBlock.lang !== undefined) block.lang = asStr(rawBlock.lang);
13
+ // lang defaults from the codeFile extension when not given explicitly.
14
+ else if (typeof rawBlock.codeFile === 'string' && rawBlock.codeFile.trim()) {
15
+ const ext = path.extname(rawBlock.codeFile).slice(1).toLowerCase();
16
+ if (ext) block.lang = ext;
17
+ }
18
+ if (rawBlock.filename !== undefined) block.filename = asStr(rawBlock.filename);
19
+ if (hasHeight) block.height = clampInt(rawBlock.height, BLOCK_HEIGHT.min, BLOCK_HEIGHT.max, undefined);
20
+ return block;
21
+ }
22
+
23
+ // Normalizes one diff block. `id` is the already-assigned block id.
24
+ export function normalizeDiffBlock(rawBlock, id, cwd, where, hasHeight) {
25
+ const diff = readTextSource(rawBlock, 'diff', 'diffFile', cwd, where);
26
+ if (!diff.trim()) throw new CliError(`${where}: diff block needs a non-empty "diff" string (unified diff) or a readable "diffFile".`);
27
+ const block = { id, type: 'diff', diff };
28
+ if (rawBlock.lang !== undefined) block.lang = asStr(rawBlock.lang);
29
+ if (rawBlock.filename !== undefined) block.filename = asStr(rawBlock.filename);
30
+ if (rawBlock.title !== undefined) block.title = asStr(rawBlock.title);
31
+ if (rawBlock.review === true) block.review = true;
32
+ if (rawBlock.reviewKind !== undefined) block.reviewKind = asStr(rawBlock.reviewKind);
33
+ if (rawBlock.commit !== undefined) block.commit = asStr(rawBlock.commit);
34
+ const view = asStr(rawBlock.view).trim().toLowerCase();
35
+ if (view === 'split' || view === 'unified') block.view = view;
36
+ if (hasHeight) block.height = clampInt(rawBlock.height, BLOCK_HEIGHT.min, BLOCK_HEIGHT.max, undefined);
37
+ return block;
38
+ }
@@ -0,0 +1,39 @@
1
+ // The mermaid, graphviz and plantuml blocks.
2
+ import { CliError } from '../../util.js';
3
+ import { asStr, clampInt } from '../sources.js';
4
+ import { BLOCK_HEIGHT } from '../constants.js';
5
+
6
+ // Normalizes one mermaid block. `id` is the already-assigned block id.
7
+ export function normalizeMermaidBlock(rawBlock, id, cwd, where, hasHeight) {
8
+ const code = asStr(rawBlock.code);
9
+ if (!code.trim()) throw new CliError(`${where}: mermaid block needs a non-empty "code" string.`);
10
+ const block = { id, type: 'mermaid', code };
11
+ if (rawBlock.editable === true) block.editable = true;
12
+ if (hasHeight) block.height = clampInt(rawBlock.height, BLOCK_HEIGHT.min, BLOCK_HEIGHT.max, undefined);
13
+ return block;
14
+ }
15
+
16
+ // Normalizes one graphviz block. `id` is the already-assigned block id.
17
+ export function normalizeGraphvizBlock(rawBlock, id, cwd, where, hasHeight) {
18
+ const dot = asStr(rawBlock.dot);
19
+ if (!dot.trim()) throw new CliError(`${where}: graphviz block needs a non-empty "dot" string.`);
20
+ const block = { id, type: 'graphviz', dot };
21
+ if (hasHeight) block.height = clampInt(rawBlock.height, BLOCK_HEIGHT.min, BLOCK_HEIGHT.max, undefined);
22
+ return block;
23
+ }
24
+
25
+ // Normalizes one plantuml block. `id` is the already-assigned block id.
26
+ export function normalizePlantumlBlock(rawBlock, id, cwd, where, hasHeight) {
27
+ const code = asStr(rawBlock.code);
28
+ if (!code.trim()) throw new CliError(`${where}: plantuml block needs a non-empty "code" string.`);
29
+ const block = { id, type: 'plantuml', code };
30
+ if (rawBlock.server !== undefined && rawBlock.server !== null && rawBlock.server !== '') {
31
+ const server = asStr(rawBlock.server).trim();
32
+ if (!/^https?:\/\/\S+$/i.test(server)) {
33
+ throw new CliError(`${where}: plantuml "server" must be an http(s) URL string.`);
34
+ }
35
+ block.server = server;
36
+ }
37
+ if (hasHeight) block.height = clampInt(rawBlock.height, BLOCK_HEIGHT.min, BLOCK_HEIGHT.max, undefined);
38
+ return block;
39
+ }
@@ -0,0 +1,106 @@
1
+ // The git-conflict block: parses conflict markers and normalizes the block.
2
+ import path from 'node:path';
3
+ import { CliError } from '../../util.js';
4
+ import { asStr, clampInt, readAnyTextSource } from '../sources.js';
5
+ import { BLOCK_HEIGHT } from '../constants.js';
6
+
7
+ function joinConflictLines(lines) {
8
+ return lines.join('\n');
9
+ }
10
+
11
+ function parseGitConflictContent(content, where) {
12
+ const lines = String(content || '').replace(/\r\n?/g, '\n').split('\n');
13
+ const parts = [];
14
+ const conflicts = [];
15
+ let textBuf = [];
16
+ const flushText = () => {
17
+ if (!textBuf.length) return;
18
+ parts.push({ type: 'text', text: joinConflictLines(textBuf) });
19
+ textBuf = [];
20
+ };
21
+
22
+ for (let i = 0; i < lines.length; i++) {
23
+ const start = lines[i].match(/^<<<<<<<(?:\s+(.*))?$/);
24
+ if (!start) {
25
+ textBuf.push(lines[i]);
26
+ continue;
27
+ }
28
+
29
+ flushText();
30
+ const oursLabel = start[1] || 'ours';
31
+ const ours = [];
32
+ const base = [];
33
+ const theirs = [];
34
+ let baseLabel = '';
35
+ let theirsLabel = 'theirs';
36
+ let section = 'ours';
37
+ let closed = false;
38
+
39
+ for (i = i + 1; i < lines.length; i++) {
40
+ const line = lines[i];
41
+ const baseStart = line.match(/^\|\|\|\|\|\|\|(?:\s+(.*))?$/);
42
+ if (baseStart && section === 'ours') {
43
+ baseLabel = baseStart[1] || 'base';
44
+ section = 'base';
45
+ continue;
46
+ }
47
+ if (/^=======$/.test(line) && (section === 'ours' || section === 'base')) {
48
+ section = 'theirs';
49
+ continue;
50
+ }
51
+ const end = line.match(/^>>>>>>>(?:\s+(.*))?$/);
52
+ if (end && section === 'theirs') {
53
+ theirsLabel = end[1] || theirsLabel;
54
+ closed = true;
55
+ break;
56
+ }
57
+ if (section === 'ours') ours.push(line);
58
+ else if (section === 'base') base.push(line);
59
+ else theirs.push(line);
60
+ }
61
+
62
+ if (!closed) {
63
+ throw new CliError(`${where}: conflict marker starting at line ${conflicts.length + 1} is missing a matching >>>>>>> marker.`);
64
+ }
65
+ const id = `c${conflicts.length + 1}`;
66
+ conflicts.push({
67
+ id,
68
+ oursLabel,
69
+ theirsLabel,
70
+ ...(baseLabel ? { baseLabel } : {}),
71
+ ours: joinConflictLines(ours),
72
+ theirs: joinConflictLines(theirs),
73
+ ...(baseLabel ? { base: joinConflictLines(base) } : {}),
74
+ });
75
+ parts.push({ type: 'conflict', conflictId: id });
76
+ }
77
+
78
+ flushText();
79
+ return { conflicts, parts };
80
+ }
81
+
82
+ // Normalizes one git-conflict block. `id` is the already-assigned block id.
83
+ export function normalizeGitConflictBlock(rawBlock, id, cwd, where, hasHeight) {
84
+ const src = readAnyTextSource(rawBlock, ['content', 'text'], ['file', 'path', 'src'], cwd, where, 'git conflict file');
85
+ if (!src.text.trim()) {
86
+ throw new CliError(`${where}: git-conflict block needs inline "content"/"text" or a readable local "file"/"path".`);
87
+ }
88
+ const parsed = parseGitConflictContent(src.text, where);
89
+ if (!parsed.conflicts.length) {
90
+ throw new CliError(`${where}: no git conflict markers found (expected <<<<<<<, =======, >>>>>>>).`);
91
+ }
92
+ const filename = asStr(rawBlock.filename ?? rawBlock.name ?? (src.file ? path.basename(src.file) : '')).trim();
93
+ const block = {
94
+ id,
95
+ type: 'git-conflict',
96
+ filename,
97
+ conflicts: parsed.conflicts,
98
+ parts: parsed.parts,
99
+ };
100
+ const lang = asStr(rawBlock.lang).trim() || (filename ? path.extname(filename).slice(1).toLowerCase() : '');
101
+ if (lang) block.lang = lang;
102
+ if (rawBlock.title !== undefined) block.title = asStr(rawBlock.title);
103
+ if (src.file) block.file = src.file;
104
+ if (hasHeight) block.height = clampInt(rawBlock.height, BLOCK_HEIGHT.min, BLOCK_HEIGHT.max, undefined);
105
+ return block;
106
+ }
@@ -0,0 +1,32 @@
1
+ // The image block, and the image reader that compare blocks share.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { CliError } from '../../util.js';
5
+ import { asStr, clampInt } from '../sources.js';
6
+ import { BLOCK_HEIGHT, IMAGE_MAX_BYTES, IMAGE_MIMES } from '../constants.js';
7
+
8
+ // Resolve an image source (shared by the `image` and `compare` blocks): an
9
+ // http(s)/data URL passes through; a local file is read + embedded as a data
10
+ // URI (capped) so the board stays self-contained offline.
11
+ export function resolveImageSrc(srcRaw, cwd, where, field) {
12
+ const src = asStr(srcRaw).trim();
13
+ if (!src) throw new CliError(`${where}: ${field} needs a "src" (http(s)/data URL or local file path).`);
14
+ if (/^(https?:|data:)/i.test(src)) return src;
15
+ const p = path.resolve(cwd, src);
16
+ const ext = path.extname(p).slice(1).toLowerCase();
17
+ const mime = IMAGE_MIMES[ext];
18
+ if (!mime) throw new CliError(`${where}: ${field}: unsupported image extension ".${ext}" — use ${Object.keys(IMAGE_MIMES).join('/')}, or an http(s)/data URL.`);
19
+ let buf;
20
+ try { buf = fs.readFileSync(p); } catch { throw new CliError(`${where}: ${field}: cannot read image "${src}" (resolved: ${p})`); }
21
+ if (buf.length > IMAGE_MAX_BYTES) throw new CliError(`${where}: ${field}: image "${src}" is ${(buf.length / 1024 / 1024).toFixed(1)}MB — max ${IMAGE_MAX_BYTES / 1024 / 1024}MB.`);
22
+ return `data:${mime};base64,${buf.toString('base64')}`;
23
+ }
24
+
25
+ // Normalizes one image block. `id` is the already-assigned block id.
26
+ export function normalizeImageBlock(rawBlock, id, cwd, where, hasHeight) {
27
+ const block = { id, type: 'image' };
28
+ block.src = resolveImageSrc(rawBlock.src ?? rawBlock.file ?? rawBlock.url, cwd, where, 'image block');
29
+ if (rawBlock.alt !== undefined) block.alt = asStr(rawBlock.alt);
30
+ if (hasHeight) block.height = clampInt(rawBlock.height, BLOCK_HEIGHT.min, BLOCK_HEIGHT.max, undefined);
31
+ return block;
32
+ }
@@ -0,0 +1,33 @@
1
+ // Maps each block type to the function that normalizes it. The html block
2
+ // has no entry: normalizeBlock handles it last.
3
+ import { normalizeMarkdownBlock } from './markdown.js';
4
+ import { normalizeGraphvizBlock, normalizeMermaidBlock, normalizePlantumlBlock } from './diagram.js';
5
+ import { normalizeCodeBlock, normalizeDiffBlock } from './code.js';
6
+ import { normalizeGitConflictBlock } from './git-conflict.js';
7
+ import { normalizeVideoBlock } from './video.js';
8
+ import { normalizePdfBlock } from './pdf.js';
9
+ import { normalizeChartBlock } from './chart.js';
10
+ import { normalizeTableBlock } from './table.js';
11
+ import { normalizeImageBlock } from './image.js';
12
+ import { normalizeCompareBlock, normalizeKpiBlock, normalizePaletteBlock, normalizeTypographyBlock } from './widgets.js';
13
+ import { normalizeA2uiBlock } from './a2ui.js';
14
+
15
+ export const BLOCK_NORMALIZERS = {
16
+ markdown: normalizeMarkdownBlock,
17
+ mermaid: normalizeMermaidBlock,
18
+ graphviz: normalizeGraphvizBlock,
19
+ plantuml: normalizePlantumlBlock,
20
+ code: normalizeCodeBlock,
21
+ diff: normalizeDiffBlock,
22
+ 'git-conflict': normalizeGitConflictBlock,
23
+ video: normalizeVideoBlock,
24
+ pdf: normalizePdfBlock,
25
+ chart: normalizeChartBlock,
26
+ table: normalizeTableBlock,
27
+ image: normalizeImageBlock,
28
+ kpi: normalizeKpiBlock,
29
+ typography: normalizeTypographyBlock,
30
+ compare: normalizeCompareBlock,
31
+ a2ui: normalizeA2uiBlock,
32
+ palette: normalizePaletteBlock,
33
+ };
@@ -0,0 +1,13 @@
1
+ // The markdown block.
2
+ import { CliError } from '../../util.js';
3
+ import { clampInt, readTextSource } from '../sources.js';
4
+ import { BLOCK_HEIGHT } from '../constants.js';
5
+
6
+ // Normalizes one markdown block. `id` is the already-assigned block id.
7
+ export function normalizeMarkdownBlock(rawBlock, id, cwd, where, hasHeight) {
8
+ const md = readTextSource(rawBlock, 'md', 'mdFile', cwd, where);
9
+ if (!md.trim()) throw new CliError(`${where}: markdown block needs a non-empty "md" string or a readable "mdFile".`);
10
+ const block = { id, type: 'markdown', md };
11
+ if (hasHeight) block.height = clampInt(rawBlock.height, BLOCK_HEIGHT.min, BLOCK_HEIGHT.max, undefined);
12
+ return block;
13
+ }
@@ -0,0 +1,38 @@
1
+ // The pdf block.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { CliError } from '../../util.js';
5
+ import { asStr, clampInt } from '../sources.js';
6
+ import { BLOCK_HEIGHT, PDF_MAX_BYTES, PDF_MIME } from '../constants.js';
7
+
8
+ // Normalizes one pdf block. `id` is the already-assigned block id.
9
+ export function normalizePdfBlock(rawBlock, id, cwd, where, hasHeight) {
10
+ const src = asStr(rawBlock.src ?? rawBlock.file ?? rawBlock.url).trim();
11
+ if (!src) throw new CliError(`${where}: pdf block needs a "src" (http(s) PDF URL or local .pdf file path).`);
12
+ const block = { id, type: 'pdf' };
13
+ if (rawBlock.title !== undefined) block.title = asStr(rawBlock.title);
14
+ if (rawBlock.alt !== undefined && block.title === undefined) block.title = asStr(rawBlock.alt);
15
+ if (hasHeight) block.height = clampInt(rawBlock.height, BLOCK_HEIGHT.min, BLOCK_HEIGHT.max, undefined);
16
+ if (/^https?:/i.test(src)) {
17
+ block.src = src;
18
+ block.mime = PDF_MIME;
19
+ if (!block.title) block.title = path.basename(src.split(/[?#]/)[0]) || 'PDF';
20
+ return block;
21
+ }
22
+ const p = path.resolve(cwd, src);
23
+ const ext = path.extname(p).slice(1).toLowerCase();
24
+ if (ext !== 'pdf') throw new CliError(`${where}: unsupported pdf extension ".${ext}" — use a local .pdf file or an http(s) PDF URL.`);
25
+ let stat;
26
+ try {
27
+ stat = fs.statSync(p);
28
+ } catch {
29
+ throw new CliError(`${where}: cannot read pdf "${src}" (resolved: ${p})`);
30
+ }
31
+ if (stat.size > PDF_MAX_BYTES) {
32
+ throw new CliError(`${where}: pdf "${src}" is ${(stat.size / 1024 / 1024).toFixed(0)}MB — max ${PDF_MAX_BYTES / 1024 / 1024}MB.`);
33
+ }
34
+ block.file = p;
35
+ block.mime = PDF_MIME;
36
+ if (!block.title) block.title = path.basename(p);
37
+ return block;
38
+ }