pi-better-show 0.3.1 → 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.
@@ -0,0 +1,353 @@
1
+ import { isMap, isScalar, isSeq, LineCounter, type Node, parseDocument, type Scalar } from "yaml";
2
+ import { locate } from "./parse.ts";
3
+ import type { BlockKind } from "./types.ts";
4
+
5
+ /**
6
+ * Finds what is wrong with the blocks of a Markdown file, so the agent that wrote it can fix them: a block that does
7
+ * not parse (the page shows its source), and the slips that parse without an error and lose data (a value cut at a
8
+ * ` #`, a key no block reads). Each problem carries the line of the Markdown file.
9
+ */
10
+
11
+ export interface BlockProblem {
12
+ kind: BlockKind;
13
+ /** 1-based line of the Markdown file. */
14
+ line: number;
15
+ /** Where in the block, as the author reads it: `form question "o5" choice 1 label`. */
16
+ path: string;
17
+ message: string;
18
+ /** `error`: the block cannot be drawn. `warning`: it is drawn, but part of what was written is lost. */
19
+ severity: "error" | "warning";
20
+ }
21
+
22
+ export interface CheckOptions {
23
+ /** Checks a Mermaid source and returns what is wrong with it; core carries no Mermaid parser, a host passes one. */
24
+ mermaid?: (source: string) => string | undefined;
25
+ }
26
+
27
+ interface Shape {
28
+ /** The keys the block reads at this level. */
29
+ keys?: readonly string[];
30
+ /** Keys that hold a list of items, with the shape of an item. */
31
+ lists?: Record<string, ListShape>;
32
+ /** Keys that hold a mapping. */
33
+ maps?: Record<string, Shape>;
34
+ /** The list a document that is a bare YAML list stands for. */
35
+ bare?: string;
36
+ }
37
+ interface ListShape {
38
+ noun: string;
39
+ item?: Shape;
40
+ /** Item keys that name an item, first found wins. */
41
+ names?: readonly string[];
42
+ }
43
+
44
+ const items = (noun: string, keys: readonly string[], names?: readonly string[]): ListShape => ({
45
+ noun,
46
+ item: { keys },
47
+ ...(names ? { names } : {}),
48
+ });
49
+
50
+ /** What each YAML kind reads, level by level; it mirrors the converters in blocks.ts and blocks-new.ts. */
51
+ const SHAPES: Record<string, Shape> = {
52
+ cards: { keys: ["cards"], bare: "cards", lists: { cards: items("card", ["title", "tone", "body"]) } },
53
+ options: {
54
+ keys: ["options"],
55
+ bare: "options",
56
+ lists: { options: items("option", ["title", "recommended", "body", "pros", "cons"]) },
57
+ },
58
+ form: {
59
+ keys: ["title", "submit", "questions"],
60
+ bare: "questions",
61
+ lists: {
62
+ questions: {
63
+ noun: "question",
64
+ names: ["name", "label"],
65
+ item: {
66
+ keys: ["name", "label", "type", "hint", "required", "other", "choices"],
67
+ lists: { choices: items("choice", ["value", "label", "note", "recommended"]) },
68
+ },
69
+ },
70
+ },
71
+ },
72
+ review: {
73
+ keys: ["title", "submit", "pick", "columns", "items"],
74
+ bare: "items",
75
+ lists: { items: items("item", ["name", "label", "image", "page", "height", "body"], ["name", "label"]) },
76
+ },
77
+ suggest: { keys: ["items"], bare: "items", lists: { items: items("suggestion", ["label", "text"]) } },
78
+ checklist: {
79
+ keys: ["title", "submit", "items"],
80
+ bare: "items",
81
+ lists: { items: items("item", ["name", "label", "checked", "note"], ["name", "label"]) },
82
+ },
83
+ table: {
84
+ keys: ["columns", "rows", "sort", "filter"],
85
+ lists: { columns: items("column", ["name", "label", "type", "align"], ["name", "label"]), rows: { noun: "row" } },
86
+ maps: { sort: { keys: ["column", "by", "direction", "dir"] } },
87
+ },
88
+ steps: { keys: ["items"], bare: "items", lists: { items: items("step", ["title", "status", "when", "body"]) } },
89
+ stats: {
90
+ keys: ["items"],
91
+ bare: "items",
92
+ lists: { items: items("stat", ["label", "value", "delta", "tone", "note"]) },
93
+ },
94
+ };
95
+
96
+ /** Keys whose value is an enum, flag or number: a ` #` after one is a plain comment, not lost text. */
97
+ const NON_TEXT_KEYS = new Set([
98
+ "status",
99
+ "type",
100
+ "align",
101
+ "direction",
102
+ "dir",
103
+ "checked",
104
+ "required",
105
+ "filter",
106
+ "height",
107
+ "columns",
108
+ "tone",
109
+ ]);
110
+
111
+ const QUOTE_HINT = 'quote any value that holds " #" or ": " (and commas inside {…})';
112
+
113
+ const short = (text: string, max = 40): string => (text.length > max ? `${text.slice(0, max)}…` : text);
114
+
115
+ /** Edit distance, to offer the known key a misspelling was probably meant for. */
116
+ function distance(a: string, b: string): number {
117
+ let row = Array.from({ length: b.length + 1 }, (_, index) => index);
118
+ for (let i = 1; i <= a.length; i++) {
119
+ const next = [i];
120
+ for (let j = 1; j <= b.length; j++) {
121
+ next[j] = Math.min(
122
+ (next[j - 1] as number) + 1,
123
+ (row[j] as number) + 1,
124
+ (row[j - 1] as number) + (a[i - 1] === b[j - 1] ? 0 : 1),
125
+ );
126
+ }
127
+ row = next;
128
+ }
129
+ return row[b.length] as number;
130
+ }
131
+
132
+ const nearest = (key: string, known: readonly string[]): string | undefined => {
133
+ const lower = key.toLowerCase();
134
+ return known.find((name) => name.toLowerCase() === lower || distance(lower, name.toLowerCase()) <= 2);
135
+ };
136
+
137
+ const quoteYaml = (text: string): string => `'${text.replace(/'/g, "''")}'`;
138
+
139
+ interface Context {
140
+ kind: BlockKind;
141
+ /** The file line of the block's opening fence: a source line n is file line `fence + n`. */
142
+ fence: number;
143
+ source: string;
144
+ lines: LineCounter;
145
+ out: BlockProblem[];
146
+ }
147
+
148
+ const lineOf = (context: Context, offset: number): number => context.fence + context.lines.linePos(offset).line;
149
+
150
+ function report(context: Context, offset: number, path: string, message: string): void {
151
+ context.out.push({ kind: context.kind, line: lineOf(context, offset), path, message, severity: "warning" });
152
+ }
153
+
154
+ /** A plain value that a ` #` on its line cut short: YAML reads the rest as a comment, so that text is lost. */
155
+ function checkComment(context: Context, node: Scalar, path: string): void {
156
+ if (node.type !== "PLAIN" || node.comment === undefined || node.comment === null || !node.range) return;
157
+ const [start, end] = node.range;
158
+ const rest = context.source.slice(
159
+ end,
160
+ context.source.indexOf("\n", end) < 0 ? undefined : context.source.indexOf("\n", end),
161
+ );
162
+ if (!/^[ \t]*#/.test(rest)) return;
163
+ const kept = context.source.slice(start, end);
164
+ const whole = `${kept}${rest}`.trimEnd();
165
+ const read = kept === "" ? "no value" : `the value ${JSON.stringify(kept)}`;
166
+ report(
167
+ context,
168
+ end,
169
+ path,
170
+ `a plain value ends at " #": ${JSON.stringify(rest.trim())} is read as a YAML comment and dropped, leaving ${read}; if it is text, quote the whole value: ${quoteYaml(whole)}`,
171
+ );
172
+ }
173
+
174
+ function checkKeys(context: Context, node: Node, shape: Shape | undefined, owner: string): void {
175
+ if (!isMap(node)) return;
176
+ for (const pair of node.items) {
177
+ const key = isScalar(pair.key) ? String(pair.key.value) : undefined;
178
+ const keyAt = isScalar(pair.key) && pair.key.range ? pair.key.range[0] : (node.range?.[0] ?? 0);
179
+ if (key !== undefined && shape?.keys && !shape.keys.includes(key)) {
180
+ const near = nearest(key, shape.keys);
181
+ report(
182
+ context,
183
+ keyAt,
184
+ owner,
185
+ `unknown key ${JSON.stringify(key)} is ignored${near ? ` (did you mean ${JSON.stringify(near)}?)` : ""}; this level reads: ${shape.keys.join(", ")}`,
186
+ );
187
+ }
188
+ walk(context, pair.value as Node | null, key === undefined ? undefined : shape, owner, key);
189
+ }
190
+ }
191
+
192
+ function itemName(item: Node | unknown, names: readonly string[] | undefined): string | undefined {
193
+ if (!isMap(item) || !names) return undefined;
194
+ for (const name of names) {
195
+ const found = item.items.find((pair) => isScalar(pair.key) && pair.key.value === name);
196
+ if (found && isScalar(found.value) && found.value.value !== null && found.value.value !== "")
197
+ return short(String(found.value.value), 30);
198
+ }
199
+ return undefined;
200
+ }
201
+
202
+ /** Walks a value, checking keys against `shape` (the owner's) and plain values for a cut-off comment. */
203
+ function walk(context: Context, node: Node | null, shape: Shape | undefined, owner: string, key: string | undefined) {
204
+ const path = key === undefined ? owner : `${owner} ${key}`;
205
+ const list = key === undefined ? undefined : shape?.lists?.[key];
206
+ if (isSeq(node)) {
207
+ for (const [index, item] of node.items.entries()) {
208
+ const name = itemName(item, list?.names);
209
+ const here = list
210
+ ? `${owner} ${list.noun} ${name === undefined ? index + 1 : JSON.stringify(name)}`
211
+ : `${path} ${index + 1}`;
212
+ walk(context, item as Node | null, list?.item, here, undefined);
213
+ }
214
+ } else if (isMap(node)) {
215
+ checkKeys(context, node, key === undefined ? shape : shape?.maps?.[key], path);
216
+ } else if (isScalar(node)) {
217
+ if (key !== undefined && NON_TEXT_KEYS.has(key)) return;
218
+ checkComment(context, node, path);
219
+ }
220
+ }
221
+
222
+ /** The YAML kinds, whose body is parsed as a document. */
223
+ const isYamlKind = (kind: BlockKind): boolean => kind in SHAPES;
224
+
225
+ function checkBody(context: Context): void {
226
+ const doc = parseDocument(context.source, { lineCounter: context.lines });
227
+ if (doc.errors.length > 0) return;
228
+ const shape = SHAPES[context.kind] as Shape;
229
+ const root = doc.contents;
230
+ const name = context.kind;
231
+ if (isSeq(root)) {
232
+ if (shape.bare === undefined) return;
233
+ const list = shape.lists?.[shape.bare];
234
+ for (const [index, item] of root.items.entries()) {
235
+ const label = itemName(item, list?.names);
236
+ const here = `${name} ${list?.noun ?? "item"} ${label === undefined ? index + 1 : JSON.stringify(label)}`;
237
+ walk(context, item as Node | null, list?.item, here, undefined);
238
+ }
239
+ } else if (isMap(root)) {
240
+ checkKeys(context, root, shape, name);
241
+ }
242
+ }
243
+
244
+ /** An invalid YAML block: YAML's own error points past a broken flow collection, so look back for the line that opened it. */
245
+ function yamlError(context: Context, error: string): { line: number; message: string; hint: string } | undefined {
246
+ const doc = parseDocument(context.source, { lineCounter: new LineCounter() });
247
+ const first = doc.errors[0];
248
+ if (!first) return undefined;
249
+ const lines = context.source.split("\n");
250
+ let at = first.linePos?.[0].line ?? 1;
251
+ const message = first.message
252
+ .split("\n")[0]
253
+ ?.replace(/ at line \d+, column \d+:?$/, "")
254
+ .replace(/:$/, "");
255
+ if (first.message.startsWith("Flow ")) {
256
+ const hit = (text: string): boolean => /[{[][^}\]]*\s#/.test(text);
257
+ for (let n = at; n >= Math.max(1, at - 50); n--) {
258
+ if (hit(lines[n - 1] ?? "")) {
259
+ at = n;
260
+ return { line: at, message: message ?? error, hint: QUOTE_HINT };
261
+ }
262
+ }
263
+ at = Math.max(1, at - 1);
264
+ return { line: at, message: message ?? error, hint: QUOTE_HINT };
265
+ }
266
+ const hint =
267
+ first.code === "MISSING_CHAR" ? "close the quote" : 'check the indentation, and quote text holding ": " or " #"';
268
+ return { line: at, message: message ?? error, hint };
269
+ }
270
+
271
+ /** A tree or mindmap error that names its source line. */
272
+ function sourceLine(context: Context, error: string): number | undefined {
273
+ const numbered = /^line (\d+): /.exec(error);
274
+ if (numbered) return Number(numbered[1]);
275
+ const listed = /^not a list item: (.*)$/.exec(error);
276
+ if (listed) {
277
+ const at = context.source.split("\n").findIndex((line) => line.trim() === (listed[1] as string));
278
+ return at < 0 ? undefined : at + 1;
279
+ }
280
+ return undefined;
281
+ }
282
+
283
+ /**
284
+ * The problems of every block in `markdown`, in document order. `error` problems are blocks that cannot be drawn
285
+ * (the page shows their source); `warning` problems are blocks that draw but lose part of what was written: a plain
286
+ * value cut at ` #`, a key the block does not read, a fence that never closes, a diagram `options.mermaid` refuses.
287
+ */
288
+ export function checkBlocks(markdown: string, options: CheckOptions = {}): BlockProblem[] {
289
+ const out: BlockProblem[] = [];
290
+ for (const { segment, line, closed, source } of locate(markdown)) {
291
+ if (segment.type === "markdown") continue;
292
+ const kind = segment.kind;
293
+ const context: Context = { kind, fence: line, source, lines: new LineCounter(), out };
294
+ if (segment.type === "invalid") {
295
+ let at = line;
296
+ let message = segment.error;
297
+ let hint = "";
298
+ if (isYamlKind(kind)) {
299
+ const found = yamlError(context, segment.error);
300
+ if (found) {
301
+ at = line + found.line;
302
+ message = found.message;
303
+ hint = found.hint;
304
+ }
305
+ } else {
306
+ const inner = sourceLine(context, segment.error);
307
+ if (inner !== undefined) {
308
+ at = line + inner;
309
+ message = segment.error.replace(/^line \d+: /, "");
310
+ }
311
+ }
312
+ out.push({
313
+ kind,
314
+ line: at,
315
+ path: kind,
316
+ message: `the ${kind} block is invalid and is shown as source: ${message}${hint ? `; ${hint}` : ""}`,
317
+ severity: "error",
318
+ });
319
+ } else if (isYamlKind(kind)) {
320
+ checkBody(context);
321
+ } else if (kind === "mermaid" && options.mermaid) {
322
+ const problem = options.mermaid(source);
323
+ if (problem !== undefined) {
324
+ out.push({
325
+ kind,
326
+ line: line + 1,
327
+ path: kind,
328
+ message: `the diagram will not draw: ${problem}`,
329
+ severity: "error",
330
+ });
331
+ }
332
+ }
333
+ if (!closed) {
334
+ out.push({
335
+ kind,
336
+ line,
337
+ path: kind,
338
+ message: `the ${kind} fence is never closed, so the block runs to the end of the file; add a closing fence`,
339
+ severity: "warning",
340
+ });
341
+ }
342
+ }
343
+ return out.sort((a, b) => a.line - b.line);
344
+ }
345
+
346
+ /** The problems as the lines an agent reads: `Block problems in notes.md:` then one `- line N path: message` each. */
347
+ export function formatProblems(name: string, problems: readonly BlockProblem[]): string {
348
+ const lines = problems.map(
349
+ (problem) =>
350
+ `- line ${problem.line} ${problem.path}${problem.severity === "warning" ? " (warning)" : ""}: ${problem.message}`,
351
+ );
352
+ return [`Block problems in ${name}:`, ...lines].join("\n");
353
+ }
package/src/core/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export { encodeAnswer } from "./answer.ts";
2
- export { reviewItemName } from "./blocks.ts";
2
+ export { NOTE_FIELD, reviewItemName } from "./blocks.ts";
3
+ export { type BlockProblem, type CheckOptions, checkBlocks, formatProblems } from "./check.ts";
3
4
  export { inline, inlinePlain } from "./inline.ts";
4
5
  export { parse } from "./parse.ts";
5
6
  export { toText } from "./text.ts";
package/src/core/parse.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { parse as parseYaml } from "yaml";
2
2
  import * as legacy from "./blocks.ts";
3
3
  import * as added from "./blocks-new.ts";
4
+ import { tree } from "./tree.ts";
4
5
  import {
5
6
  type AlertData,
6
7
  type AlertTone,
@@ -49,6 +50,7 @@ const CONVERTERS: { [K in Exclude<BlockKind, "alert">]: Convert<K> } = {
49
50
  table: yaml(added.table),
50
51
  steps: yaml(added.steps),
51
52
  stats: yaml(added.stats),
53
+ tree,
52
54
  };
53
55
 
54
56
  /** The first line of the error: YAML's own messages end it with a colon and append a source excerpt. */
@@ -94,21 +96,40 @@ function trimBlankEdges(lines: string[]): string {
94
96
  return lines.slice(start, end).join("\n");
95
97
  }
96
98
 
99
+ /** A segment with the 1-based line of the document where it starts (a block's opening fence); `closed` is false for a fence that never closes. */
100
+ export interface Located {
101
+ segment: Segment;
102
+ line: number;
103
+ closed: boolean;
104
+ /** A fenced block's text between its fences, as converted; empty for prose and alerts. */
105
+ source: string;
106
+ }
107
+
97
108
  /**
98
109
  * Splits a document into its prose and its blocks, in order. A block is a fenced code block whose first
99
110
  * word names a block kind (`form`, `table`, ...), or a GitHub alert; other code, and prose, stay Markdown.
100
111
  * A block whose body does not fit its schema becomes an `invalid` segment that keeps its source and the reason.
101
112
  */
102
113
  export function parse(markdown: string): Segment[] {
114
+ return locate(markdown).map((located) => located.segment);
115
+ }
116
+
117
+ /** `parse` with where each segment starts; `checkBlocks` reports problems by these lines. */
118
+ export function locate(markdown: string): Located[] {
103
119
  const lines = markdown.replace(/\r\n?/g, "\n").split("\n");
104
- const segments: Segment[] = [];
120
+ const segments: Located[] = [];
105
121
  let prose: string[] = [];
122
+ let proseLine = 1;
106
123
  let index = 0;
107
124
  const flush = () => {
108
125
  const text = trimBlankEdges(prose);
109
- if (text !== "") segments.push({ type: "markdown", text });
126
+ if (text !== "") segments.push({ segment: { type: "markdown", text }, line: proseLine, closed: true, source: "" });
110
127
  prose = [];
111
128
  };
129
+ const addProse = (from: number, added: string[]) => {
130
+ if (prose.length === 0) proseLine = from + 1;
131
+ prose.push(...added);
132
+ };
112
133
 
113
134
  let i = 0;
114
135
  while (i < lines.length) {
@@ -122,6 +143,7 @@ export function parse(markdown: string): Segment[] {
122
143
  body.push((lines[end] as string).replace(new RegExp(`^ {0,${indent.length}}`), ""));
123
144
  end++;
124
145
  }
146
+ const closed = end < lines.length;
125
147
  const stop = Math.min(end + 1, lines.length);
126
148
  const kind = (info.trim().split(/\s+/)[0] as string).toLowerCase();
127
149
  if (fenceKinds.has(kind)) {
@@ -133,9 +155,9 @@ export function parse(markdown: string): Segment[] {
133
155
  lines.slice(i, stop).join("\n"),
134
156
  );
135
157
  if (segment.type === "block") index++;
136
- segments.push(segment);
158
+ segments.push({ segment, line: i + 1, closed, source: body.join("\n") });
137
159
  } else {
138
- prose.push(...lines.slice(i, stop));
160
+ addProse(i, lines.slice(i, stop));
139
161
  }
140
162
  i = stop;
141
163
  continue;
@@ -148,15 +170,20 @@ export function parse(markdown: string): Segment[] {
148
170
  const data = alertOf(run);
149
171
  if (data) {
150
172
  flush();
151
- segments.push({ type: "block", kind: "alert", data, raw: run.join("\n"), index: index++ });
173
+ segments.push({
174
+ segment: { type: "block", kind: "alert", data, raw: run.join("\n"), index: index++ },
175
+ line: i + 1,
176
+ closed: true,
177
+ source: "",
178
+ });
152
179
  } else {
153
- prose.push(...run);
180
+ addProse(i, run);
154
181
  }
155
182
  i = end;
156
183
  continue;
157
184
  }
158
185
 
159
- prose.push(line);
186
+ addProse(i, [line]);
160
187
  i++;
161
188
  }
162
189
  flush();
package/src/core/text.ts CHANGED
@@ -21,6 +21,8 @@ import type {
21
21
  TableData,
22
22
  TextLang,
23
23
  TextProfile,
24
+ TreeData,
25
+ TreeNode,
24
26
  } from "./types.ts";
25
27
  import { displayWidth } from "./width.ts";
26
28
 
@@ -44,26 +46,30 @@ interface Replies {
44
46
  /** Followed by the pick sentence, when the review has one. */
45
47
  review: string;
46
48
  pick: (label: string | undefined) => string;
49
+ /** Closes a review reply, which has no fixed sentence of its own. */
50
+ welcome: string;
47
51
  suggest: string;
48
52
  checklist: string;
49
53
  }
50
54
 
51
55
  const REPLIES: Record<TextLang, Replies> = {
52
56
  en: {
53
- options: "Reply with a number.",
54
- form: (example) => `Reply in text, one line per question, like ${example}.`,
57
+ options: "Reply with a number. Other comments are welcome.",
58
+ form: (example) => `Reply in text, one line per question, like ${example}. Other comments are welcome.`,
55
59
  review: "Reply with a comment for each item, naming the item.",
56
60
  pick: (label) => ` Say which one you pick${label === undefined ? "" : ` (${label})`}.`,
61
+ welcome: " Other comments are welcome.",
57
62
  suggest: "You can reply: ",
58
- checklist: "Reply with the items you tick or leave unticked, naming each.",
63
+ checklist: "Reply with the items you tick or leave unticked, naming each. Other comments are welcome.",
59
64
  },
60
65
  "zh-TW": {
61
- options: "請回覆編號。",
62
- form: (example) => `請用文字回覆,每題一行,例如 ${example}。`,
66
+ options: "請回覆編號。也歡迎補充其他意見。",
67
+ form: (example) => `請用文字回覆,每題一行,例如 ${example}。也歡迎補充其他意見。`,
63
68
  review: "請逐項回覆意見,並寫明是哪一項。",
64
69
  pick: (label) => `請說明你選哪一項${label === undefined ? "" : `(${label})`}。`,
70
+ welcome: "也歡迎補充其他意見。",
65
71
  suggest: "可以回覆:",
66
- checklist: "請回覆你勾選或不勾選的項目,逐項寫明。",
72
+ checklist: "請回覆你勾選或不勾選的項目,逐項寫明。也歡迎補充其他意見。",
67
73
  },
68
74
  };
69
75
 
@@ -150,7 +156,7 @@ function review(dialect: Dialect, data: ReviewData): string {
150
156
  ]);
151
157
  const pick = data.pick === undefined ? "" : dialect.say.pick(data.pick === true ? undefined : data.pick);
152
158
  const title = data.title ? [bold(dialect, field(dialect, data.title))] : [];
153
- return [...title, ...lines, "", `${dialect.say.review}${pick}`].join("\n");
159
+ return [...title, ...lines, "", `${dialect.say.review}${pick}${dialect.say.welcome}`].join("\n");
154
160
  }
155
161
 
156
162
  function mindmap(dialect: Dialect, data: MindmapData): string {
@@ -230,6 +236,26 @@ function stats(dialect: Dialect, data: StatsData): string {
230
236
  .join("\n");
231
237
  }
232
238
 
239
+ /** A tree in `tree` style, one line per node: tags as `[new]`, the note after ` — `. Notes lose their Markdown: the lines sit in a fence. */
240
+ function tree(dialect: Dialect, data: TreeData): string {
241
+ const lines: string[] = [];
242
+ const label = (node: TreeNode): string => {
243
+ const tags = node.tags.map((tag) => `[${tag}]`);
244
+ const note = node.note === undefined ? "" : ` — ${oneLine(inlinePlain(node.note))}`;
245
+ return `${[`${node.name}${node.dir ? "/" : ""}`, ...tags].join(" ")}${note}`;
246
+ };
247
+ const walk = (node: TreeNode, prefix: string) => {
248
+ node.children.forEach((child, index) => {
249
+ const last = index === node.children.length - 1;
250
+ lines.push(`${prefix}${last ? "└── " : "├── "}${label(child)}`);
251
+ walk(child, `${prefix}${last ? " " : "│ "}`);
252
+ });
253
+ };
254
+ lines.push(label(data.root));
255
+ walk(data.root, "");
256
+ return code(dialect, lines.join("\n"));
257
+ }
258
+
233
259
  const widest = (text: string): number => Math.max(0, ...text.split("\n").map(displayWidth));
234
260
 
235
261
  /** A diagram as a text drawing when the hook can and it fits; else its source and a pointer to the web view. */
@@ -272,6 +298,8 @@ function block(dialect: Dialect, segment: BlockSegment): string {
272
298
  return steps(dialect, segment.data);
273
299
  case "stats":
274
300
  return stats(dialect, segment.data);
301
+ case "tree":
302
+ return tree(dialect, segment.data);
275
303
  }
276
304
  }
277
305
 
@@ -0,0 +1,84 @@
1
+ import { TREE_LIMITS, TREE_TAGS, type TreeData, type TreeNode, type TreeTag } from "./types.ts";
2
+
3
+ const MORE = /^… (\d+) more$/;
4
+ const NOTE = " # ";
5
+ const TAGS = /^(?:(.*?) )?\{([^{}]*)\}$/;
6
+ const KNOWN = new Set<string>(TREE_TAGS);
7
+
8
+ /** Trims spaces and tabs only: a no-break space at an edge belongs to a name. */
9
+ const strip = (text: string): string => text.replace(/^[ \t]+|[ \t]+$/g, "");
10
+
11
+ /** The tags written between braces: names separated by commas or spaces, each once, all known. */
12
+ function tagsOf(list: string, line: number): TreeTag[] {
13
+ const tags: TreeTag[] = [];
14
+ for (const word of list.split(/[\s,]+/).filter(Boolean)) {
15
+ if (!KNOWN.has(word)) throw new Error(`line ${line}: unknown tag "${word}" (use ${TREE_TAGS.join(", ")})`);
16
+ if (!tags.includes(word as TreeTag)) tags.push(word as TreeTag);
17
+ }
18
+ return tags;
19
+ }
20
+
21
+ /** One line's content (indentation already removed): `name[/] [{tags}] [# note]`. */
22
+ function nodeOf(content: string, line: number): TreeNode {
23
+ const cut = content.indexOf(NOTE);
24
+ const head = strip(cut < 0 ? content : content.slice(0, cut));
25
+ const note = cut < 0 ? "" : strip(content.slice(cut + NOTE.length));
26
+ const tagged = TAGS.exec(head);
27
+ const text = tagged ? (tagged[1] ?? "") : head;
28
+ const dir = text.endsWith("/");
29
+ const name = strip(dir ? text.slice(0, -1) : text);
30
+ if (name === "") throw new Error(`line ${line}: a line has no name`);
31
+ // Tags are read last, so a bad name is reported before a bad tag.
32
+ const tags = tagged ? tagsOf(tagged[2] as string, line) : [];
33
+ const more = dir ? null : MORE.exec(name);
34
+ return {
35
+ name,
36
+ dir,
37
+ tags,
38
+ ...(note === "" ? {} : { note }),
39
+ children: [],
40
+ ...(more ? { more: Number(more[1]) } : {}),
41
+ };
42
+ }
43
+
44
+ /**
45
+ * An indented tree, two spaces per level: the first line is the root, a folder's name ends with `/`, then optional
46
+ * `{tags}` and a note after ` # `. A `… N more` line stands for entries a limit cut. At most 2,000 lines and 32 levels.
47
+ */
48
+ export function tree(source: string): TreeData {
49
+ const stack: TreeNode[] = [];
50
+ let root: TreeNode | undefined;
51
+ let count = 0;
52
+ for (const [at, raw] of source.split("\n").entries()) {
53
+ const line = raw.replace(/[ \t]+$/, "");
54
+ if (line === "") continue;
55
+ const number = at + 1;
56
+ const space = /^[ \t]*/.exec(line)?.[0] as string;
57
+ if (space.includes("\t")) throw new Error(`line ${number}: indent with two spaces, not tabs`);
58
+ if (space.length % 2 !== 0) throw new Error(`line ${number}: indent by two spaces per level`);
59
+ const level = space.length / 2;
60
+ if (root === undefined && level > 0) throw new Error(`line ${number}: the root line is not indented`);
61
+ if (level > stack.length) throw new Error(`line ${number}: indented more than one level below the line above`);
62
+ if (++count > TREE_LIMITS.nodes) throw new Error(`a tree holds at most ${TREE_LIMITS.nodes} nodes`);
63
+ if (level + 1 > TREE_LIMITS.depth) throw new Error(`a tree is at most ${TREE_LIMITS.depth} levels deep`);
64
+ if (level === 0 && root !== undefined) {
65
+ throw new Error("a tree has one root: indent the other top-level lines under it");
66
+ }
67
+ const node = nodeOf(line.slice(space.length), number);
68
+ stack.length = level;
69
+ const parent = stack[level - 1];
70
+ if (parent) {
71
+ if (!parent.dir) {
72
+ throw new Error(
73
+ `line ${number}: "${parent.name}" is a file and cannot hold entries (end a folder's name with /)`,
74
+ );
75
+ }
76
+ parent.children.push(node);
77
+ } else {
78
+ root = node;
79
+ }
80
+ stack.push(node);
81
+ }
82
+ if (root === undefined) throw new Error("a tree needs a root line");
83
+ return { root };
84
+ }