@uncarved/jade 0.3.1 → 0.4.1

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 (206) hide show
  1. package/README.md +1 -0
  2. package/dist/api.d.ts +1 -1
  3. package/dist/api.js +1 -1
  4. package/dist/host.d.ts +2 -0
  5. package/dist/host.js +39 -5
  6. package/dist/host.js.map +1 -1
  7. package/dist/remote.js +5 -0
  8. package/dist/remote.js.map +1 -1
  9. package/dist/session.d.ts +7 -0
  10. package/dist/session.js +490 -29
  11. package/dist/session.js.map +1 -1
  12. package/package.json +4 -4
  13. package/plugins/approval/index.ts +36 -14
  14. package/plugins/approval/policy.ts +15 -10
  15. package/plugins/approval/review.ts +9 -5
  16. package/plugins/checks/checks.ts +10 -7
  17. package/plugins/checks/index.ts +13 -13
  18. package/plugins/checks/plugin.json +1 -1
  19. package/plugins/checks/project.ts +37 -38
  20. package/plugins/commands/index.ts +27 -3
  21. package/plugins/compact/compact.ts +13 -5
  22. package/plugins/compact/index.ts +20 -3
  23. package/plugins/compact/style.ts +13 -14
  24. package/plugins/completions/index.ts +35 -0
  25. package/plugins/completions/plugin.json +7 -0
  26. package/plugins/copy/index.ts +46 -0
  27. package/plugins/copy/plugin.json +7 -0
  28. package/plugins/editor/index.ts +10 -4
  29. package/plugins/fs/diff.ts +7 -6
  30. package/plugins/fs/fs.ts +8 -4
  31. package/plugins/fs/grep.ts +42 -9
  32. package/plugins/fs/index.ts +2 -7
  33. package/plugins/fs/plugin.json +1 -1
  34. package/plugins/fs/renderers.ts +16 -15
  35. package/plugins/fs/style.ts +16 -15
  36. package/plugins/hooks/index.ts +3 -2
  37. package/plugins/keys/index.ts +5 -1
  38. package/plugins/mcp/index.ts +197 -78
  39. package/plugins/mcp/install.ts +5 -3
  40. package/plugins/mcp/mcp.ts +163 -11
  41. package/plugins/mcp/plugin.json +2 -1
  42. package/plugins/mcp/project.ts +47 -50
  43. package/plugins/memory/index.ts +4 -4
  44. package/plugins/memory/style.ts +13 -14
  45. package/plugins/mentions/candidates.ts +67 -0
  46. package/plugins/mentions/index.ts +12 -5
  47. package/plugins/mentions/plugin.json +1 -1
  48. package/plugins/mentions/style.ts +13 -14
  49. package/plugins/models/configure.ts +47 -12
  50. package/plugins/models/index.ts +27 -1
  51. package/plugins/models/provider.ts +24 -0
  52. package/plugins/models/saved.ts +1 -1
  53. package/plugins/modes/index.ts +13 -2
  54. package/plugins/print/index.ts +7 -4
  55. package/plugins/prompts/index.ts +0 -0
  56. package/plugins/renderers/index.ts +10 -5
  57. package/plugins/repeats/index.ts +8 -8
  58. package/plugins/schedule/index.ts +5 -1
  59. package/plugins/screenshot/browser.ts +10 -0
  60. package/plugins/sessions/index.ts +48 -2
  61. package/plugins/shell/index.ts +27 -28
  62. package/plugins/shell/plugin.json +1 -1
  63. package/plugins/shell/renderers.ts +9 -7
  64. package/plugins/shell/shell.ts +3 -1
  65. package/plugins/skills/index.ts +28 -19
  66. package/plugins/skills/project.ts +12 -7
  67. package/plugins/steer/index.ts +5 -4
  68. package/plugins/task/index.ts +80 -50
  69. package/plugins/task/plugin.json +6 -2
  70. package/plugins/task/style.ts +13 -14
  71. package/plugins/task/subagent.ts +67 -184
  72. package/plugins/todo/index.ts +39 -9
  73. package/plugins/tools/index.ts +9 -2
  74. package/plugins/tui/frontend.ts +139 -89
  75. package/plugins/tui/index.ts +2 -3
  76. package/plugins/tui/mentions.ts +11 -80
  77. package/plugins/tui/plugin.json +1 -1
  78. package/plugins/tui/screen.ts +55 -5
  79. package/plugins/tui/transcript.ts +17 -7
  80. package/plugins/tui/tui.ts +337 -101
  81. package/plugins/tui/vendor.ts +1 -1
  82. package/plugins/undo/checkpoint.ts +8 -4
  83. package/plugins/undo/index.ts +170 -31
  84. package/plugins/undo/plugin.json +1 -0
  85. package/plugins/undo/snapshot.ts +87 -14
  86. package/plugins/undo/style.ts +13 -14
  87. package/plugins/web/index.ts +7 -18
  88. package/plugins/web/plugin.json +1 -1
  89. package/plugins-dist/approval/index.js +363 -418
  90. package/plugins-dist/approval/policy.js +391 -508
  91. package/plugins-dist/approval/review.js +132 -158
  92. package/plugins-dist/approval/schema.js +50 -55
  93. package/plugins-dist/ask/index.js +115 -129
  94. package/plugins-dist/budget/index.js +27 -31
  95. package/plugins-dist/checks/checks.js +293 -329
  96. package/plugins-dist/checks/index.js +119 -139
  97. package/plugins-dist/checks/plugin.json +2 -1
  98. package/plugins-dist/checks/project.js +57 -65
  99. package/plugins-dist/commands/index.js +47 -29
  100. package/plugins-dist/compact/compact.js +233 -249
  101. package/plugins-dist/compact/index.js +98 -95
  102. package/plugins-dist/compact/style.js +9 -14
  103. package/plugins-dist/completions/index.js +30 -0
  104. package/plugins-dist/completions/plugin.json +9 -0
  105. package/plugins-dist/continue/index.js +40 -52
  106. package/plugins-dist/copy/index.js +40 -0
  107. package/plugins-dist/copy/plugin.json +9 -0
  108. package/plugins-dist/cost/index.js +98 -115
  109. package/plugins-dist/custom-commands/index.js +55 -72
  110. package/plugins-dist/editor/index.js +64 -72
  111. package/plugins-dist/fs/diff.js +111 -124
  112. package/plugins-dist/fs/fs.js +426 -469
  113. package/plugins-dist/fs/grep.js +262 -253
  114. package/plugins-dist/fs/index.js +20 -34
  115. package/plugins-dist/fs/plugin.json +1 -2
  116. package/plugins-dist/fs/renderers.js +100 -112
  117. package/plugins-dist/fs/style.js +11 -15
  118. package/plugins-dist/fs/sys.js +31 -43
  119. package/plugins-dist/hooks/index.js +107 -127
  120. package/plugins-dist/keys/index.js +27 -31
  121. package/plugins-dist/mcp/index.js +271 -199
  122. package/plugins-dist/mcp/install.js +123 -137
  123. package/plugins-dist/mcp/mcp.js +638 -577
  124. package/plugins-dist/mcp/plugin.json +3 -1
  125. package/plugins-dist/mcp/project.js +98 -115
  126. package/plugins-dist/memory/index.js +83 -88
  127. package/plugins-dist/memory/memory.js +111 -128
  128. package/plugins-dist/memory/style.js +9 -14
  129. package/plugins-dist/mentions/attach.js +91 -99
  130. package/plugins-dist/mentions/candidates.js +49 -0
  131. package/plugins-dist/mentions/index.js +71 -81
  132. package/plugins-dist/mentions/plugin.json +2 -1
  133. package/plugins-dist/mentions/style.js +9 -14
  134. package/plugins-dist/models/config.js +29 -43
  135. package/plugins-dist/models/configure.js +421 -474
  136. package/plugins-dist/models/context.js +14 -22
  137. package/plugins-dist/models/index.js +182 -189
  138. package/plugins-dist/models/provider.js +263 -307
  139. package/plugins-dist/models/saved.js +60 -72
  140. package/plugins-dist/modes/index.js +138 -165
  141. package/plugins-dist/plugins/index.js +34 -34
  142. package/plugins-dist/print/index.js +192 -175
  143. package/plugins-dist/prompts/index.js +86 -89
  144. package/plugins-dist/prompts/notes.js +31 -37
  145. package/plugins-dist/prompts/prompts.js +155 -193
  146. package/plugins-dist/prompts/results.js +40 -53
  147. package/plugins-dist/prompts/sys.js +39 -50
  148. package/plugins-dist/renderers/index.js +32 -32
  149. package/plugins-dist/repeats/index.js +131 -174
  150. package/plugins-dist/schedule/cron.js +49 -56
  151. package/plugins-dist/schedule/index.js +230 -247
  152. package/plugins-dist/schedule/store.js +93 -109
  153. package/plugins-dist/scratch/index.js +12 -18
  154. package/plugins-dist/screenshot/browser.js +136 -154
  155. package/plugins-dist/screenshot/index.js +37 -46
  156. package/plugins-dist/screenshot/sys.js +53 -65
  157. package/plugins-dist/screenshot/tool.js +98 -126
  158. package/plugins-dist/sessions/index.js +149 -117
  159. package/plugins-dist/shell/index.js +117 -135
  160. package/plugins-dist/shell/plugin.json +1 -1
  161. package/plugins-dist/shell/renderers.js +28 -33
  162. package/plugins-dist/shell/service.js +17 -23
  163. package/plugins-dist/shell/shell.js +307 -362
  164. package/plugins-dist/shell/sys.js +64 -79
  165. package/plugins-dist/skills/index.js +193 -211
  166. package/plugins-dist/skills/install.js +122 -149
  167. package/plugins-dist/skills/project.js +65 -73
  168. package/plugins-dist/skills/skills.js +135 -171
  169. package/plugins-dist/steer/index.js +108 -125
  170. package/plugins-dist/suggest/index.js +235 -259
  171. package/plugins-dist/task/index.js +130 -117
  172. package/plugins-dist/task/plugin.json +5 -2
  173. package/plugins-dist/task/style.js +9 -14
  174. package/plugins-dist/task/subagent.js +156 -279
  175. package/plugins-dist/todo/index.js +79 -63
  176. package/plugins-dist/tools/index.js +36 -42
  177. package/plugins-dist/tui/editor.js +145 -160
  178. package/plugins-dist/tui/frontend.js +639 -678
  179. package/plugins-dist/tui/history.js +34 -37
  180. package/plugins-dist/tui/index.js +16 -18
  181. package/plugins-dist/tui/markdown.js +203 -247
  182. package/plugins-dist/tui/mascot.js +266 -355
  183. package/plugins-dist/tui/mentions.js +67 -144
  184. package/plugins-dist/tui/plugin.json +1 -2
  185. package/plugins-dist/tui/render.js +35 -45
  186. package/plugins-dist/tui/screen.js +197 -180
  187. package/plugins-dist/tui/transcript.js +436 -468
  188. package/plugins-dist/tui/tui.js +1554 -1656
  189. package/plugins-dist/tui/vendor.js +1088 -1388
  190. package/plugins-dist/undo/checkpoint.js +97 -118
  191. package/plugins-dist/undo/index.js +281 -192
  192. package/plugins-dist/undo/plugin.json +3 -0
  193. package/plugins-dist/undo/snapshot.js +134 -99
  194. package/plugins-dist/undo/style.js +9 -14
  195. package/plugins-dist/update/index.js +26 -28
  196. package/plugins-dist/web/env.js +55 -68
  197. package/plugins-dist/web/index.js +80 -110
  198. package/plugins-dist/web/plugin.json +1 -2
  199. package/plugins-dist/web/renderers.js +4 -5
  200. package/plugins-dist/web/web.js +514 -593
  201. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  202. package/sdk/python/jade_plugin.py +9 -2
  203. package/src/api.ts +1 -1
  204. package/src/host.ts +39 -4
  205. package/src/remote.ts +6 -1
  206. package/src/session.ts +496 -36
@@ -1,46 +1,43 @@
1
- // 输入历史:输入框里提交过的内容,跨会话保留,↑/↓ 和 Ctrl+R 用。
2
- // 所有目录共用 $JADE_HOME/history.jsonl,每条记下目录;读的时候只取当前目录的。
3
1
  import { appendFile, mkdir, readFile, writeFile } from "node:fs/promises";
4
2
  import path from "node:path";
5
- /** 每个目录最多留多少条 */
6
3
  export const HISTORY_LIMIT = 500;
7
- /** 文件超过这么多行时,下次读取顺便删掉旧的 */
8
4
  const FILE_LIMIT = 5000;
5
+
9
6
  export class InputHistory {
10
- file;
11
- cwd;
12
- constructor(file, cwd) {
13
- this.file = file;
14
- this.cwd = path.resolve(cwd);
7
+ file;
8
+ cwd;
9
+ constructor(file, cwd) {
10
+ this.file = file;
11
+ this.cwd = path.resolve(cwd);
12
+ }
13
+ async load() {
14
+ let text;
15
+ try {
16
+ text = await readFile(this.file, "utf8");
17
+ } catch {
18
+ return [];
15
19
  }
16
- /** 当前目录的历史,旧的在前,重复的只留最后一次 */
17
- async load() {
18
- let text;
19
- try {
20
- text = await readFile(this.file, "utf8");
21
- }
22
- catch {
23
- return [];
24
- }
25
- const lines = text.split("\n").filter(Boolean);
26
- const entries = [];
27
- for (const line of lines) {
28
- try {
29
- const e = JSON.parse(line);
30
- if (typeof e.text === "string" && typeof e.cwd === "string")
31
- entries.push(e);
32
- }
33
- catch { }
34
- }
35
- if (lines.length > FILE_LIMIT) {
36
- await writeFile(this.file, entries.slice(-FILE_LIMIT / 2).map((e) => JSON.stringify(e) + "\n").join("")).catch(() => { });
37
- }
38
- const mine = entries.filter((e) => samePath(e.cwd, this.cwd)).map((e) => e.text);
39
- return mine.filter((t, i) => mine.lastIndexOf(t) === i).slice(-HISTORY_LIMIT);
20
+ const lines = text.split(`
21
+ `).filter(Boolean);
22
+ const entries = [];
23
+ for (const line of lines) {
24
+ try {
25
+ const e = JSON.parse(line);
26
+ if (typeof e.text === "string" && typeof e.cwd === "string")
27
+ entries.push(e);
28
+ } catch {}
40
29
  }
41
- async add(text) {
42
- await mkdir(path.dirname(this.file), { recursive: true });
43
- await appendFile(this.file, JSON.stringify({ text, cwd: this.cwd }) + "\n");
30
+ if (lines.length > FILE_LIMIT) {
31
+ await writeFile(this.file, entries.slice(-FILE_LIMIT / 2).map((e) => JSON.stringify(e) + `
32
+ `).join("")).catch(() => {});
44
33
  }
34
+ const mine = entries.filter((e) => samePath(e.cwd, this.cwd)).map((e) => e.text);
35
+ return mine.filter((t, i) => mine.lastIndexOf(t) === i).slice(-HISTORY_LIMIT);
36
+ }
37
+ async add(text) {
38
+ await mkdir(path.dirname(this.file), { recursive: true });
39
+ await appendFile(this.file, JSON.stringify({ text, cwd: this.cwd }) + `
40
+ `);
41
+ }
45
42
  }
46
- const samePath = (a, b) => (process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b);
43
+ const samePath = (a, b) => process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
@@ -1,22 +1,20 @@
1
- // jade/tui:终端界面,默认的前端。提供 frontend@1 和 ui@1;命令、快捷键、显示方式都来自注册表插件。
2
1
  import { definePlugin } from "@uncarved/jade-api";
3
2
  import { ScreenBridge, tuiFrontend } from "./frontend.js";
4
3
  export default definePlugin({
5
- process(ctx) {
6
- const bridge = new ScreenBridge();
7
- ctx.provide("ui@1", bridge.ui);
8
- ctx.provide("frontend@1", tuiFrontend({
9
- home: ctx.home,
10
- cwd: ctx.cwd,
11
- commands: ctx.require("commands@1"),
12
- keys: ctx.require("keys@1"),
13
- renderers: ctx.require("renderers@1"),
14
- ...optional("modes", ctx.service("modes@1")),
15
- ...optional("models", ctx.service("models@1")),
16
- ...optional("compact", ctx.service("compact@1")),
17
- ...optional("index", ctx.service("sessions@1")),
18
- ...optional("steer", ctx.service("steer@1")),
19
- }, bridge));
20
- },
4
+ process(ctx) {
5
+ const bridge = new ScreenBridge;
6
+ ctx.provide("ui@1", bridge.ui);
7
+ ctx.provide("frontend@1", tuiFrontend({
8
+ home: ctx.home,
9
+ cwd: ctx.cwd,
10
+ commands: ctx.require("commands@1"),
11
+ keys: ctx.require("keys@1"),
12
+ renderers: ctx.require("renderers@1"),
13
+ ...optional("models", ctx.service("models@1")),
14
+ ...optional("completions", ctx.service("completions@1")),
15
+ ...optional("index", ctx.service("sessions@1")),
16
+ ...optional("steer", ctx.service("steer@1"))
17
+ }, bridge));
18
+ }
21
19
  });
22
- const optional = (k, v) => (v === undefined ? {} : { [k]: v });
20
+ const optional = (k, v) => v === undefined ? {} : { [k]: v };
@@ -1,6 +1,3 @@
1
- // 终端里显示模型回复的 Markdown:标题、粗体、斜体、行内代码、链接、列表、引用、分隔线、代码块和表格。
2
- // 回复是流式到达的,按完整的行逐行处理:代码块要记住是否在块里,表格要攒齐所有行才能算列宽,
3
- // 所以做成有状态的 markdownStream。表格和分隔线跟终端宽度有关,交出去的是按宽度现排的函数。
4
1
  import stringWidth from "string-width";
5
2
  import wrapAnsi from "wrap-ansi";
6
3
  import { bold, cyan, dim, italic, strike, underline } from "./screen.js";
@@ -8,276 +5,235 @@ const FENCE = /^\s*(`{3,}|~{3,})\s*([^`\s]*)/;
8
5
  const RULE = /^\s{0,3}([-*_])(\s*\1){2,}\s*$/;
9
6
  const DELIMITER = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
10
7
  export function markdownStream() {
11
- /** 所在代码块的开头标记(``` 或 ~~~),不在代码块里时为 undefined */
12
- let fence;
13
- /** 带 | 的一行:下一行是分隔行时它是表头,否则是普通的一行 */
14
- let candidate;
15
- let table;
16
- const endTable = () => {
17
- const out = [];
18
- if (table)
19
- out.push(tableLine(table.rows, table.align));
20
- else if (candidate !== undefined)
21
- out.push(renderLine(candidate));
22
- table = undefined;
8
+ let fence;
9
+ let candidate;
10
+ let table;
11
+ const endTable = () => {
12
+ const out = [];
13
+ if (table)
14
+ out.push(tableLine(table.rows, table.align));
15
+ else if (candidate !== undefined)
16
+ out.push(renderLine(candidate));
17
+ table = undefined;
18
+ candidate = undefined;
19
+ return out;
20
+ };
21
+ function push(line) {
22
+ if (fence) {
23
+ const m = line.match(FENCE);
24
+ if (m && m[1][0] === fence[0] && m[1].length >= fence.length && !m[2]) {
25
+ fence = undefined;
26
+ return [];
27
+ }
28
+ return [hanging(dim("┃ "), line, dim("┃ "))];
29
+ }
30
+ if (table) {
31
+ if (line.includes("|") && line.trim()) {
32
+ table.rows.push(cells(line));
33
+ return [];
34
+ }
35
+ return [...endTable(), ...push(line)];
36
+ }
37
+ if (candidate !== undefined) {
38
+ if (DELIMITER.test(line) && line.includes("-")) {
39
+ const header = cells(candidate);
40
+ const align = cells(line).map((c) => c.startsWith(":") && c.endsWith(":") ? "center" : c.endsWith(":") ? "right" : "left");
41
+ while (align.length < header.length)
42
+ align.push("left");
43
+ table = { align, rows: [header] };
23
44
  candidate = undefined;
24
- return out;
25
- };
26
- function push(line) {
27
- if (fence) {
28
- const m = line.match(FENCE);
29
- if (m && m[1][0] === fence[0] && m[1].length >= fence.length && !m[2]) {
30
- fence = undefined;
31
- return [];
32
- }
33
- // 左边一条竖线和正文分开;长行折行后续行也带竖线
34
- return [hanging(dim("┃ "), line, dim("┃ "))];
35
- }
36
- if (table) {
37
- if (line.includes("|") && line.trim()) {
38
- table.rows.push(cells(line));
39
- return [];
40
- }
41
- return [...endTable(), ...push(line)];
42
- }
43
- if (candidate !== undefined) {
44
- if (DELIMITER.test(line) && line.includes("-")) {
45
- const header = cells(candidate);
46
- const align = cells(line).map((c) => (c.startsWith(":") && c.endsWith(":") ? "center" : c.endsWith(":") ? "right" : "left"));
47
- while (align.length < header.length)
48
- align.push("left");
49
- table = { align, rows: [header] };
50
- candidate = undefined;
51
- return [];
52
- }
53
- return [...endTable(), ...push(line)];
54
- }
55
- const m = line.match(FENCE);
56
- if (m) {
57
- fence = m[1];
58
- return m[2] ? [dim(`┃ ${m[2]}`)] : [];
59
- }
60
- if (splitCells(line).length > 1) {
61
- candidate = line;
62
- return [];
63
- }
64
- return [renderLine(line)];
45
+ return [];
46
+ }
47
+ return [...endTable(), ...push(line)];
48
+ }
49
+ const m = line.match(FENCE);
50
+ if (m) {
51
+ fence = m[1];
52
+ return m[2] ? [dim(`┃ ${m[2]}`)] : [];
65
53
  }
66
- return {
67
- push,
68
- flush() {
69
- const out = endTable();
70
- fence = undefined;
71
- return out;
72
- },
73
- pending: () => (table ? [tableLine(table.rows, table.align)] : candidate !== undefined ? [renderLine(candidate)] : []),
74
- };
54
+ if (splitCells(line).length > 1) {
55
+ candidate = line;
56
+ return [];
57
+ }
58
+ return [renderLine(line)];
59
+ }
60
+ return {
61
+ push,
62
+ flush() {
63
+ const out = endTable();
64
+ fence = undefined;
65
+ return out;
66
+ },
67
+ pending: () => table ? [tableLine(table.rows, table.align)] : candidate !== undefined ? [renderLine(candidate)] : []
68
+ };
75
69
  }
76
- /** 整段 Markdown 排好版(测试和一次性显示用) */
77
70
  export function renderMarkdown(text, width) {
78
- const md = markdownStream();
79
- const out = [...text.split("\n").flatMap((l) => md.push(l)), ...md.flush()];
80
- return out.flatMap((l) => (typeof l === "string" ? [l] : l.render(width))).map(visibleRow);
71
+ const md = markdownStream();
72
+ const out = [...text.split(`
73
+ `).flatMap((l) => md.push(l)), ...md.flush()];
74
+ return out.flatMap((l) => typeof l === "string" ? [l] : l.render(width)).map(visibleRow);
81
75
  }
82
- // ---------- 自动折行的记号 ----------
83
- //
84
- // 一行太长折成屏幕上的几行时,后面的几行(续行)开头带一个看不见的记号:用鼠标选中复制时,续行接回上一行,
85
- // 而不是变成换行。记号只用几个控制字符(显示之前去掉;外面来的文字里的控制字符早被 safeScreen 去掉了,不会撞上):
86
- // \x1f \x1e × gap \x1d × indent \x1c
87
- // gap:折行时上一行行尾去掉了几个空格,接回去时补上;indent:续行开头排版加的几列(列表的缩进、代码块的竖线),接回去时跳过
88
76
  const SOFT_HEAD = /^\x1f(\x1e*)(\x1d*)\x1c/;
89
- /** 把一行标成续行 */
90
- export const softRow = (row, gap = 0, indent = 0) => `\x1f${"\x1e".repeat(gap)}${"\x1d".repeat(indent)}\x1c${row}`;
91
- /** 去掉记号,得到要显示的那一行 */
92
- export const visibleRow = (row) => (row.charCodeAt(0) === 0x1f ? row.replace(SOFT_HEAD, "") : row);
93
- /** 一行是不是续行,以及接回上一行时要补的空格数、要跳过的列数;text 是去掉记号的那一行 */
77
+ export const softRow = (row, gap = 0, indent = 0) => `\x1F${"\x1E".repeat(gap)}${"\x1D".repeat(indent)}\x1C${row}`;
78
+ export const visibleRow = (row) => row.charCodeAt(0) === 31 ? row.replace(SOFT_HEAD, "") : row;
94
79
  export function softInfo(row) {
95
- const m = row.charCodeAt(0) === 0x1f ? SOFT_HEAD.exec(row) : null;
96
- if (!m)
97
- return { text: row, soft: false, gap: 0, indent: 0 };
98
- return { text: row.slice(m[0].length), soft: true, gap: m[1].length, indent: m[2].length };
80
+ const m = row.charCodeAt(0) === 31 ? SOFT_HEAD.exec(row) : null;
81
+ if (!m)
82
+ return { text: row, soft: false, gap: 0, indent: 0 };
83
+ return { text: row.slice(m[0].length), soft: true, gap: m[1].length, indent: m[2].length };
99
84
  }
100
85
  const WRAP = { hard: true, trim: false };
101
- /**
102
- * 按显示宽度折行,保留颜色;每一项是屏幕上的一行,续行带记号。制表符先换成空格:按 0 列算宽度会对不齐、超宽。
103
- * 不去掉空格(trim: false),所以续行直接接在上一行后面就是原文
104
- */
105
86
  export function wrapRows(text, width) {
106
- const expanded = expandTabs(text);
107
- // 整段一起折:颜色可能跨行,分开折会丢掉后面几行的颜色
108
- const rows = wrapAnsi(expanded, width, WRAP).split("\n");
109
- const logical = expanded.split("\n");
110
- if (rows.length === logical.length)
111
- return rows;
112
- // 每个原来的行占了几行:放得下的占一行,放不下的单独折一次数出来(颜色不占宽度,不影响在哪里折)
113
- const counts = logical.map((l) => (stringWidth(l) <= width ? 1 : wrapAnsi(l, width, WRAP).split("\n").length));
114
- if (counts.reduce((a, b) => a + b, 0) !== rows.length)
115
- return rows;
116
- let at = 0;
117
- for (const n of counts) {
118
- for (let i = 1; i < n; i++)
119
- rows[at + i] = softRow(rows[at + i]);
120
- at += n;
121
- }
87
+ const expanded = expandTabs(text);
88
+ const rows = wrapAnsi(expanded, width, WRAP).split(`
89
+ `);
90
+ const logical = expanded.split(`
91
+ `);
92
+ if (rows.length === logical.length)
122
93
  return rows;
94
+ const counts = logical.map((l) => stringWidth(l) <= width ? 1 : wrapAnsi(l, width, WRAP).split(`
95
+ `).length);
96
+ if (counts.reduce((a, b) => a + b, 0) !== rows.length)
97
+ return rows;
98
+ let at = 0;
99
+ for (const n of counts) {
100
+ for (let i = 1;i < n; i++)
101
+ rows[at + i] = softRow(rows[at + i]);
102
+ at += n;
103
+ }
104
+ return rows;
123
105
  }
124
- /** 代码块和表格以外的一行 */
125
106
  function renderLine(line) {
126
- if (RULE.test(line))
127
- return { render: (width) => [dim("─".repeat(Math.max(1, Math.min(width, 80))))] };
128
- const heading = line.match(/^\s{0,3}(#{1,6})\s+(.*?)(\s+#+)?\s*$/);
129
- if (heading) {
130
- const text = inline(heading[2]);
131
- return heading[1].length === 1 ? bold(underline(text)) : bold(text);
132
- }
133
- const quote = line.match(/^\s*>\s?(.*)$/);
134
- if (quote)
135
- return hanging(dim("│ "), inline(quote[1]), dim("│ "));
136
- const item = line.match(/^(\s*)([-*+])\s+(\[[ xX]\]\s+)?(.*)$/);
137
- // 列表项折行时续行和正文对齐
138
- if (item) {
139
- const box = item[3] ? (item[3][1] === " " ? "☐ " : "☑ ") : "";
140
- return hanging(`${item[1]}${box ? "" : cyan("• ")}${box}`, inline(item[4]));
141
- }
142
- const ordered = line.match(/^(\s*)(\d+[.)])\s+(.*)$/);
143
- if (ordered)
144
- return hanging(`${ordered[1]}${cyan(ordered[2])} `, inline(ordered[3]));
145
- return inline(line);
107
+ if (RULE.test(line))
108
+ return { render: (width) => [dim("─".repeat(Math.max(1, Math.min(width, 80))))] };
109
+ const heading = line.match(/^\s{0,3}(#{1,6})\s+(.*?)(\s+#+)?\s*$/);
110
+ if (heading) {
111
+ const text = inline(heading[2]);
112
+ return heading[1].length === 1 ? bold(underline(text)) : bold(text);
113
+ }
114
+ const quote = line.match(/^\s*>\s?(.*)$/);
115
+ if (quote)
116
+ return hanging(dim("│ "), inline(quote[1]), dim("│ "));
117
+ const item = line.match(/^(\s*)([-*+])\s+(\[[ xX]\]\s+)?(.*)$/);
118
+ if (item) {
119
+ const box = item[3] ? item[3][1] === " " ? "☐ " : "☑ " : "";
120
+ return hanging(`${item[1]}${box ? "" : cyan("• ")}${box}`, inline(item[4]));
121
+ }
122
+ const ordered = line.match(/^(\s*)(\d+[.)])\s+(.*)$/);
123
+ if (ordered)
124
+ return hanging(`${ordered[1]}${cyan(ordered[2])} `, inline(ordered[3]));
125
+ return inline(line);
146
126
  }
147
- /**
148
- * 行内格式:`代码`、**粗体**、*斜体*、~~删除线~~、[链接](url)、反斜杠转义。代码里的内容原样显示。
149
- * 行内代码先换成占位符,粗体、斜体处理完再换回来,"**用 `foo()` 实现**" 这样跨过代码的粗体才认得出
150
- */
151
127
  export function inline(text) {
152
- const codes = [];
153
- return text
154
- .replace(/`+[^`]*?`+/g, (code) => `\x01${codes.push(cyan(code.replace(/^`+ ?|`+$/g, "").replace(/ $/, ""))) - 1}\x01`)
155
- .replace(/\\([\\`*_{}[\]()#+\-.!|~<>])/g, (_, c) => `\0${c.charCodeAt(0)}\0`)
156
- .replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, (_, label, url) => label === url ? underline(url) : `${underline(label)}${dim(` (${url})`)}`)
157
- .replace(/<(https?:\/\/[^>\s]+)>/g, (_, url) => underline(url))
158
- .replace(/\*\*(?=\S)(.+?)(?<=\S)\*\*|(?<![\w])__(?=\S)(.+?)(?<=\S)__(?![\w])/g, (_, a, b) => bold(a ?? b))
159
- .replace(/(?<![*\w])\*(?=[^\s*])(.+?)(?<=[^\s*])\*(?![*\w])|(?<![_\w])_(?=[^\s_])(.+?)(?<=[^\s_])_(?![_\w])/g, (_, a, b) => italic(a ?? b))
160
- .replace(/~~(?=\S)(.+?)(?<=\S)~~/g, (_, s) => strike(s))
161
- .replace(/\0(\d+)\0/g, (_, c) => String.fromCharCode(Number(c)))
162
- .replace(/\x01(\d+)\x01/g, (_, i) => codes[Number(i)]);
128
+ const codes = [];
129
+ return text.replace(/`+[^`]*?`+/g, (code) => `\x01${codes.push(cyan(code.replace(/^`+ ?|`+$/g, "").replace(/ $/, ""))) - 1}\x01`).replace(/\\([\\`*_{}[\]()#+\-.!|~<>])/g, (_, c) => `\x00${c.charCodeAt(0)}\x00`).replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, (_, label, url) => label === url ? underline(url) : `${underline(label)}${dim(` (${url})`)}`).replace(/<(https?:\/\/[^>\s]+)>/g, (_, url) => underline(url)).replace(/\*\*(?=\S)(.+?)(?<=\S)\*\*|(?<![\w])__(?=\S)(.+?)(?<=\S)__(?![\w])/g, (_, a, b) => bold(a ?? b)).replace(/(?<![*\w])\*(?=[^\s*])(.+?)(?<=[^\s*])\*(?![*\w])|(?<![_\w])_(?=[^\s_])(.+?)(?<=[^\s_])_(?![_\w])/g, (_, a, b) => italic(a ?? b)).replace(/~~(?=\S)(.+?)(?<=\S)~~/g, (_, s) => strike(s)).replace(/\0(\d+)\0/g, (_, c) => String.fromCharCode(Number(c))).replace(/\x01(\d+)\x01/g, (_, i) => codes[Number(i)]);
163
130
  }
164
- /** 制表符换成空格,按 stop 列一个制表位对齐(按显示宽度算,忽略颜色)。终端按 8 列显示 tab,按 0 列算宽度会对不齐、超宽 */
165
131
  export function expandTabs(text, stop = 4) {
166
- if (!text.includes("\t"))
167
- return text;
168
- return text
169
- .split("\n")
170
- .map((line) => {
171
- if (!line.includes("\t"))
172
- return line;
173
- let out = "";
174
- let col = 0;
175
- const parts = line.split("\t");
176
- parts.forEach((p, i) => {
177
- out += p;
178
- col += stringWidth(p);
179
- if (i < parts.length - 1) {
180
- const n = stop - (col % stop);
181
- out += " ".repeat(n);
182
- col += n;
183
- }
184
- });
185
- return out;
186
- })
187
- .join("\n");
132
+ if (!text.includes("\t"))
133
+ return text;
134
+ return text.split(`
135
+ `).map((line) => {
136
+ if (!line.includes("\t"))
137
+ return line;
138
+ let out = "";
139
+ let col = 0;
140
+ const parts = line.split("\t");
141
+ parts.forEach((p, i) => {
142
+ out += p;
143
+ col += stringWidth(p);
144
+ if (i < parts.length - 1) {
145
+ const n = stop - col % stop;
146
+ out += " ".repeat(n);
147
+ col += n;
148
+ }
149
+ });
150
+ return out;
151
+ }).join(`
152
+ `);
188
153
  }
189
- /** 折行时续行缩进到 head 之后(列表项的正文、代码块的竖线);rest 是续行开头显示的内容,宽度和 head 相同 */
190
154
  function hanging(head, body, rest = " ".repeat(stringWidth(head))) {
191
- return {
192
- render: (width) => {
193
- const indent = stringWidth(head);
194
- const room = Math.max(1, width - indent);
195
- const rows = wrapAnsi(expandTabs(body), room, WRAP).split("\n");
196
- // 折行处留下的行尾空格看不见,去掉免得多占一列;去掉了几个记在续行的记号里,复制时补回去
197
- return rows.map((r, i) => (i === 0 ? head + r.trimEnd() : softRow(rest + r.trimEnd(), rows[i - 1].length - rows[i - 1].trimEnd().length, indent)));
198
- },
199
- };
155
+ return {
156
+ render: (width) => {
157
+ const indent = stringWidth(head);
158
+ const room = Math.max(1, width - indent);
159
+ const rows = wrapAnsi(expandTabs(body), room, WRAP).split(`
160
+ `);
161
+ return rows.map((r, i) => i === 0 ? head + r.trimEnd() : softRow(rest + r.trimEnd(), rows[i - 1].length - rows[i - 1].trimEnd().length, indent));
162
+ }
163
+ };
200
164
  }
201
- /** 按没转义、不在行内代码里的 | 拆开一行 */
202
165
  function splitCells(line) {
203
- const out = [];
204
- let cell = "";
205
- let code = false;
206
- for (let i = 0; i < line.length; i++) {
207
- const c = line[i];
208
- if (c === "\\" && line[i + 1] === "|") {
209
- cell += "|";
210
- i++;
211
- }
212
- else if (c === "`") {
213
- code = !code;
214
- cell += c;
215
- }
216
- else if (c === "|" && !code) {
217
- out.push(cell);
218
- cell = "";
219
- }
220
- else
221
- cell += c;
222
- }
223
- out.push(cell);
224
- return out;
166
+ const out = [];
167
+ let cell = "";
168
+ let code = false;
169
+ for (let i = 0;i < line.length; i++) {
170
+ const c = line[i];
171
+ if (c === "\\" && line[i + 1] === "|") {
172
+ cell += "|";
173
+ i++;
174
+ } else if (c === "`") {
175
+ code = !code;
176
+ cell += c;
177
+ } else if (c === "|" && !code) {
178
+ out.push(cell);
179
+ cell = "";
180
+ } else
181
+ cell += c;
182
+ }
183
+ out.push(cell);
184
+ return out;
225
185
  }
226
- /** 表格一行的各个单元格,去掉两端的 | */
227
186
  function cells(line) {
228
- const parts = splitCells(line.trim());
229
- if (parts.length > 1 && parts[0].trim() === "")
230
- parts.shift();
231
- if (parts.length > 1 && parts.at(-1).trim() === "")
232
- parts.pop();
233
- return parts.map((c) => c.trim());
187
+ const parts = splitCells(line.trim());
188
+ if (parts.length > 1 && parts[0].trim() === "")
189
+ parts.shift();
190
+ if (parts.length > 1 && parts.at(-1).trim() === "")
191
+ parts.pop();
192
+ return parts.map((c) => c.trim());
234
193
  }
235
194
  function tableLine(rows, align) {
236
- const shown = rows.map((r, i) => r.map((c) => (i === 0 ? bold(inline(c)) : inline(c))));
237
- return { render: (width) => renderTable(shown, align, width) };
195
+ const shown = rows.map((r, i) => r.map((c) => i === 0 ? bold(inline(c)) : inline(c)));
196
+ return { render: (width) => renderTable(shown, align, width) };
238
197
  }
239
- /**
240
- * 画带边框的表格。放不下时按比例收窄较宽的列、单元格内折行;
241
- * 窄到每列连 3 列都分不到时,改成每行一段「表头: 值」
242
- */
243
198
  function renderTable(rows, align, width) {
244
- const n = Math.max(...rows.map((r) => r.length));
245
- const grid = rows.map((r) => Array.from({ length: n }, (_, i) => r[i] ?? ""));
246
- const natural = Array.from({ length: n }, (_, i) => Math.max(1, ...grid.map((r) => stringWidth(r[i]))));
247
- const room = width - (3 * n + 1);
248
- if (room < 3 * n) {
249
- const [head, ...body] = grid;
250
- return body.flatMap((r, k) => [
251
- ...(k ? [""] : []),
252
- ...r.flatMap((c, i) => wrapAnsi(`${head[i]}${dim(":")} ${c}`, Math.max(1, width), { hard: true }).split("\n")),
253
- ]);
254
- }
255
- // 从最窄的列开始,能放下的列按原宽,放不下的平分剩下的宽度
256
- const widths = [...natural];
257
- if (natural.reduce((a, b) => a + b, 0) > room) {
258
- let left = room;
259
- let open = n;
260
- for (const i of [...natural.keys()].sort((a, b) => natural[a] - natural[b])) {
261
- const share = Math.floor(left / open);
262
- widths[i] = Math.min(natural[i], share);
263
- left -= widths[i];
264
- open--;
265
- }
266
- }
267
- const pad = (s, w, a) => {
268
- const gap = w - stringWidth(s);
269
- if (a === "right")
270
- return " ".repeat(gap) + s;
271
- if (a === "center")
272
- return " ".repeat(Math.floor(gap / 2)) + s + " ".repeat(Math.ceil(gap / 2));
273
- return s + " ".repeat(gap);
274
- };
275
- const border = (l, m, r) => dim(l + widths.map((w) => "─".repeat(w + 2)).join(m) + r);
276
- const row = (r) => {
277
- const parts = r.map((c, i) => wrapAnsi(c, widths[i], { hard: true, trim: true }).split("\n"));
278
- const height = Math.max(...parts.map((p) => p.length));
279
- return Array.from({ length: height }, (_, k) => dim("│ ") + parts.map((p, i) => pad(p[k] ?? "", widths[i], align[i] ?? "left")).join(dim(" │ ")) + dim(" │"));
280
- };
199
+ const n = Math.max(...rows.map((r) => r.length));
200
+ const grid = rows.map((r) => Array.from({ length: n }, (_, i) => r[i] ?? ""));
201
+ const natural = Array.from({ length: n }, (_, i) => Math.max(1, ...grid.map((r) => stringWidth(r[i]))));
202
+ const room = width - (3 * n + 1);
203
+ if (room < 3 * n) {
281
204
  const [head, ...body] = grid;
282
- return [border("┌", "┬", "┐"), ...row(head), border("├", "┼", "┤"), ...body.flatMap(row), border("└", "┴", "┘")];
205
+ return body.flatMap((r, k) => [
206
+ ...k ? [""] : [],
207
+ ...r.flatMap((c, i) => wrapAnsi(`${head[i]}${dim(":")} ${c}`, Math.max(1, width), { hard: true }).split(`
208
+ `))
209
+ ]);
210
+ }
211
+ const widths = [...natural];
212
+ if (natural.reduce((a, b) => a + b, 0) > room) {
213
+ let left = room;
214
+ let open = n;
215
+ for (const i of [...natural.keys()].sort((a, b) => natural[a] - natural[b])) {
216
+ const share = Math.floor(left / open);
217
+ widths[i] = Math.min(natural[i], share);
218
+ left -= widths[i];
219
+ open--;
220
+ }
221
+ }
222
+ const pad = (s, w, a) => {
223
+ const gap = w - stringWidth(s);
224
+ if (a === "right")
225
+ return " ".repeat(gap) + s;
226
+ if (a === "center")
227
+ return " ".repeat(Math.floor(gap / 2)) + s + " ".repeat(Math.ceil(gap / 2));
228
+ return s + " ".repeat(gap);
229
+ };
230
+ const border = (l, m, r) => dim(l + widths.map((w) => "─".repeat(w + 2)).join(m) + r);
231
+ const row = (r) => {
232
+ const parts = r.map((c, i) => wrapAnsi(c, widths[i], { hard: true, trim: true }).split(`
233
+ `));
234
+ const height = Math.max(...parts.map((p) => p.length));
235
+ return Array.from({ length: height }, (_, k) => dim("│ ") + parts.map((p, i) => pad(p[k] ?? "", widths[i], align[i] ?? "left")).join(dim(" │ ")) + dim(" │"));
236
+ };
237
+ const [head, ...body] = grid;
238
+ return [border("┌", "┬", "┐"), ...row(head), border("├", "┼", "┤"), ...body.flatMap(row), border("└", "┴", "┘")];
283
239
  }