ShtukbaseStandard
archivo del paquete→ .shtukbase/packages/tui/lib/tui.ts

lib/tui.ts

314 líneas, 14.6 KB.

El archivo tal como está en el paquete: el código y sus comentarios no se traducen.

  1. // The shared part of the tui package: find the Shtukbase binary with the terminal front, reach a node that serves this
  2. // project, run one text command of the front and turn its terminal output into plain lines.
  3. // Bun only, no dependencies. The working directory is the project root.
  4. //
  5. // The terminal front reads every screen through the local node (`sb_space::reads` behind `sb-client`). The node serves
  6. // the projects listed in its home (`<home>/spaces.md` → space `index.md` → `projects:`). When the person's own node
  7. // (`$SHTUKBASE_HOME` or `~/.shtukbase`) does not serve this project, the package starts a node of its own in a
  8. // temporary home that lists only this project, and stops it after the command.
  9. import { spawn, spawnSync } from 'node:child_process';
  10. import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
  11. import { tmpdir } from 'node:os';
  12. import { basename, delimiter, dirname, join, resolve } from 'node:path';
  13. /** A binary that has the terminal front. `prefix` is put before the text command (`tui` for `shtukbase`). */
  14. export type Bin = { path: string; prefix: string[]; version: string; from: string; canServe: boolean };
  15. export const INSTALL_HINT =
  16. 'install Shtukbase: `curl -fsSL https://releases.shtukbase.com/install.sh | sh` or build from source ' +
  17. '(`cd engine && cargo build --release -p shtukbase`), or point SHTUK_TUI_BIN to the file';
  18. function isFile(p: string): boolean {
  19. return statSync(p, { throwIfNoEntry: false })?.isFile() ?? false;
  20. }
  21. /** `shtukbase --version` → the version line; null when the file does not run. */
  22. function versionOf(path: string): string | null {
  23. const r = spawnSync(path, ['--version'], { encoding: 'utf8', timeout: 10_000 });
  24. if (r.error || r.status !== 0) return null;
  25. return (r.stdout || '').trim().split('\n')[0] ?? '';
  26. }
  27. /** The binary at `path`, if it is a Shtukbase binary with the terminal front (or the front's own example binary). */
  28. function probe(path: string, from: string): Bin | null {
  29. if (!isFile(path)) return null;
  30. if (basename(path) === 'tui') {
  31. // engine/target/<profile>/examples/tui: the front alone, commands without the `tui` word, no node of its own.
  32. return { path, prefix: [], version: 'sb-tui (example)', from, canServe: false };
  33. }
  34. const v = versionOf(path);
  35. if (v === null || !v.startsWith('shtukbase')) return null;
  36. if (v.includes('tui: off')) return null; // built without the terminal front
  37. return { path, prefix: ['tui'], version: v, from, canServe: true };
  38. }
  39. /** Shtukbase checkouts this project knows of: $SHTUKBASE_REPO, the folders of locally installed packages, the
  40. * folders around the project. A checkout is a folder with `engine/Cargo.toml`. */
  41. export function checkouts(root: string): string[] {
  42. const out: string[] = [];
  43. const add = (p: string | undefined) => {
  44. if (p && existsSync(join(p, 'engine', 'Cargo.toml')) && !out.includes(resolve(p))) out.push(resolve(p));
  45. };
  46. add(process.env.SHTUKBASE_REPO);
  47. const lock = join(root, '.shtukbase', 'packages.lock');
  48. if (existsSync(lock)) {
  49. for (const m of readFileSync(lock, 'utf8').matchAll(/^\s+source:\s*"?([^"\n]+?)"?\s*$/gm)) {
  50. const at = m[1].indexOf('/apps/standard/packages/');
  51. if (at > 0) add(m[1].slice(0, at));
  52. }
  53. }
  54. for (let d = resolve(root); ; d = dirname(d)) {
  55. add(d);
  56. if (dirname(d) === d) break;
  57. }
  58. return out;
  59. }
  60. /** Finds the binary: $SHTUK_TUI_BIN (an explicit choice wins), then `shtukbase` on PATH, then
  61. * `engine/target/<profile>/shtukbase` and `engine/target/<profile>/examples/tui` in a known checkout. */
  62. export function findBin(root: string): { bin: Bin | null; tried: string[] } {
  63. const tried: string[] = [];
  64. const env = process.env.SHTUK_TUI_BIN;
  65. if (env) {
  66. tried.push(`SHTUK_TUI_BIN=${env}`);
  67. const b = probe(resolve(root, env), 'SHTUK_TUI_BIN');
  68. if (b) return { bin: b, tried };
  69. }
  70. for (const dir of (process.env.PATH || '').split(delimiter)) {
  71. if (!dir) continue;
  72. const p = join(dir, 'shtukbase');
  73. if (!isFile(p)) continue;
  74. tried.push(p);
  75. const b = probe(p, 'PATH');
  76. if (b) return { bin: b, tried };
  77. }
  78. for (const repo of checkouts(root)) {
  79. const target = join(repo, 'engine', 'target');
  80. const profiles = existsSync(target)
  81. ? readdirSync(target).filter((n) => statSync(join(target, n), { throwIfNoEntry: false })?.isDirectory())
  82. : [];
  83. const order = (n: string) => (n === 'release' ? 0 : n === 'hot' ? 1 : n === 'debug' ? 3 : 2);
  84. profiles.sort((a, b) => order(a) - order(b));
  85. for (const name of ['shtukbase', join('examples', 'tui')]) {
  86. for (const prof of profiles) {
  87. const p = join(target, prof, name);
  88. if (!isFile(p)) continue;
  89. tried.push(p);
  90. const b = probe(p, `build ${repo}`);
  91. if (b) return { bin: b, tried };
  92. }
  93. }
  94. tried.push(`${target}/*/shtukbase (none)`);
  95. }
  96. return { bin: null, tried };
  97. }
  98. /** A node that serves the project. `env` goes to every front command; `stop` ends a node the package started. */
  99. export type Node = { env: Record<string, string>; own: boolean; stop: () => void; note: string };
  100. function homeOf(): string {
  101. return process.env.SHTUKBASE_HOME || join(process.env.HOME || '', '.shtukbase');
  102. }
  103. /** Pages of `/automations` that a node could run. A temporary node is not started over them unless asked. */
  104. export function automationPages(root: string): number {
  105. const dir = join(root, 'automations');
  106. if (!existsSync(dir)) return 0;
  107. return readdirSync(dir).filter((n) => n.endsWith('.md')).length;
  108. }
  109. /** Runs a front command and returns its code, raw output (escape codes kept) and error text. */
  110. export function front(bin: Bin, node: Node, args: string[], root: string, extra: Record<string, string> = {}): { status: number; out: string; err: string } {
  111. const r = spawnSync(bin.path, [...bin.prefix, ...args], {
  112. cwd: root,
  113. encoding: 'utf8',
  114. timeout: 60_000,
  115. env: { ...process.env, ...node.env, ...extra, SHTUKBASE_COLOR: '1' },
  116. maxBuffer: 64 * 1024 * 1024,
  117. });
  118. return { status: r.status ?? 1, out: r.stdout || '', err: (r.stderr || '') + (r.error ? String(r.error) : '') };
  119. }
  120. /** Errors that mean "this node does not serve the project", so another node may. */
  121. export function notServed(err: string): boolean {
  122. return /UnknownSpace|LocalNodeUnavailable|not registered|node is not running|space\.ambiguous/.test(err);
  123. }
  124. /** Reaches a node for the project: the person's own node first; then a temporary one (only with a binary that can
  125. * serve; over `/automations` pages only with `ownNode`). Returns the node or the one line that says why not. */
  126. export async function reachNode(bin: Bin, root: string, opts: { ownNode?: boolean } = {}): Promise<Node | string> {
  127. const mine: Node = { env: {}, own: false, stop: () => {}, note: `the owner's node (${homeOf()})` };
  128. const probeRun = front(bin, mine, ['sidebar', '--space', root, '--width', '40'], root);
  129. if (probeRun.status === 0 && probeRun.out.trim()) return mine;
  130. if (!notServed(probeRun.err)) return `TUI cannot read the project: ${firstLine(probeRun.err) || 'empty output'}`;
  131. if (!bin.canServe) return 'no own node is running or it does not know the project, and this binary has no `serve`: ' + INSTALL_HINT;
  132. const autos = automationPages(root);
  133. if (autos > 0 && !opts.ownNode) {
  134. return `the owner's node does not serve the project; not starting a temporary node: /automations has ${autos} pages, it could run them. ` +
  135. 'Add the project to the app (or to ~/.shtukbase/spaces.md) and start it, or pass --own-node';
  136. }
  137. return await startNode(bin, root);
  138. }
  139. function firstLine(s: string): string {
  140. return s.trim().split('\n')[0] ?? '';
  141. }
  142. /** Starts `shtukbase serve` in a temporary home that lists only this project; waits until it answers. */
  143. async function startNode(bin: Bin, root: string): Promise<Node | string> {
  144. const tmp = mkdtempSync(join(tmpdir(), 'shtuk-tui-'));
  145. const home = join(tmp, 'home');
  146. const space = join(tmp, 'space');
  147. for (const d of [home, space]) mkdirSync(d, { recursive: true });
  148. const abs = resolve(root);
  149. writeFileSync(join(home, 'spaces.md'), `---\ntype: Spaces\nspaces:\n - path: ${space}\n---\n`);
  150. writeFileSync(join(space, 'index.md'), `---\ntitle: tui\nprojects:\n - name: ${JSON.stringify(basename(abs))}\n path: ${JSON.stringify(abs)}\n---\n`);
  151. const child = spawn(bin.path, ['serve', '--home', home], {
  152. cwd: tmp,
  153. env: { ...process.env, SHTUKBASE_HOME: home },
  154. stdio: ['ignore', 'ignore', 'ignore'],
  155. detached: false,
  156. });
  157. let stopped = false;
  158. const stop = () => {
  159. if (stopped) return;
  160. stopped = true;
  161. try { child.kill('SIGTERM'); } catch { /* already gone */ }
  162. rmSync(tmp, { recursive: true, force: true });
  163. };
  164. for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP'] as const) process.once(sig, () => { stop(); process.exit(130); });
  165. process.once('exit', stop);
  166. const node: Node = { env: { SHTUKBASE_HOME: home }, own: true, stop, note: 'the package\'s temporary node' };
  167. for (let i = 0; i < 100; i++) {
  168. if (child.exitCode !== null) break;
  169. if (existsSync(join(home, 'node.json'))) {
  170. const r = front(bin, node, ['sidebar', '--space', root, '--width', '40'], root);
  171. if (r.status === 0 && r.out.trim()) return node;
  172. if (!/LocalNodeUnavailable|connect/i.test(r.err)) { stop(); return `TUI cannot read the project: ${firstLine(r.err) || 'empty output'}`; }
  173. }
  174. await Bun.sleep(100);
  175. }
  176. stop();
  177. return 'the temporary node did not come up in 10 seconds (`shtukbase serve`)';
  178. }
  179. // ---- terminal output → plain lines ------------------------------------------------------------------------------
  180. const WIDE: [number, number][] = [
  181. [0x1100, 0x115f], [0x231a, 0x231b], [0x2329, 0x232a], [0x23e9, 0x23ec], [0x23f0, 0x23f0], [0x23f3, 0x23f3],
  182. [0x25fd, 0x25fe], [0x2614, 0x2615], [0x2648, 0x2653], [0x267f, 0x267f], [0x2693, 0x2693], [0x26a1, 0x26a1],
  183. [0x26aa, 0x26ab], [0x26bd, 0x26be], [0x26c4, 0x26c5], [0x26ce, 0x26ce], [0x26d4, 0x26d4], [0x26ea, 0x26ea],
  184. [0x26f2, 0x26f3], [0x26f5, 0x26f5], [0x26fa, 0x26fa], [0x26fd, 0x26fd], [0x2705, 0x2705], [0x270a, 0x270b],
  185. [0x2728, 0x2728], [0x274c, 0x274c], [0x274e, 0x274e], [0x2753, 0x2755], [0x2757, 0x2757], [0x2795, 0x2797],
  186. [0x27b0, 0x27b0], [0x27bf, 0x27bf], [0x2b1b, 0x2b1c], [0x2b50, 0x2b50], [0x2b55, 0x2b55], [0x2e80, 0x303e],
  187. [0x3041, 0x33ff], [0x3400, 0x4dbf], [0x4e00, 0x9fff], [0xa000, 0xa4cf], [0xac00, 0xd7a3], [0xf900, 0xfaff],
  188. [0xfe30, 0xfe4f], [0xff00, 0xff60], [0xffe0, 0xffe6], [0x1f004, 0x1f004], [0x1f0cf, 0x1f0cf], [0x1f18e, 0x1f18e],
  189. [0x1f191, 0x1f19a], [0x1f200, 0x1f251], [0x1f300, 0x1f64f], [0x1f680, 0x1f6ff], [0x1f7e0, 0x1f7eb],
  190. [0x1f90c, 0x1f9ff], [0x1fa70, 0x1faff], [0x20000, 0x3fffd],
  191. ];
  192. function width(cp: number): number {
  193. if (cp === 0x200d || (cp >= 0xfe00 && cp <= 0xfe0f) || (cp >= 0x0300 && cp <= 0x036f) || (cp >= 0x1f3fb && cp <= 0x1f3ff)) return 0;
  194. for (const [a, b] of WIDE) if (cp >= a && cp <= b) return 2;
  195. return 1;
  196. }
  197. /** Plays terminal output on a grid (cursor moves, line clears) and returns its lines without colours, trimmed. */
  198. export function render(raw: string): string[] {
  199. const grid: string[][] = [];
  200. let row = 0;
  201. let col = 0;
  202. const line = (r: number) => (grid[r] ??= []);
  203. const put = (ch: string, w: number) => {
  204. const l = line(row);
  205. if (w === 0) {
  206. const at = col > 0 ? col - 1 : 0;
  207. let k = at;
  208. while (k > 0 && l[k] === '') k--;
  209. l[k] = (l[k] ?? ' ') + ch;
  210. if (ch === '️' && l[k + 1] === undefined && col === k + 1) { l[k + 1] = ''; col++; }
  211. return;
  212. }
  213. while (l.length < col) l.push(' ');
  214. l[col] = ch;
  215. if (w === 2) l[col + 1] = '';
  216. col += w;
  217. };
  218. const chars = Array.from(raw);
  219. for (let i = 0; i < chars.length; i++) {
  220. const c = chars[i];
  221. if (c === '\x1b') {
  222. const n = chars[i + 1];
  223. if (n === '[') {
  224. let j = i + 2;
  225. let params = '';
  226. while (j < chars.length && !/[@-~]/.test(chars[j])) params += chars[j++];
  227. const fin = chars[j];
  228. i = j;
  229. const nums = params.replace(/^[?>=]/, '').split(';').map((x) => parseInt(x, 10));
  230. if (params.startsWith('?')) continue;
  231. if (fin === 'H' || fin === 'f') { row = (nums[0] || 1) - 1; col = (nums[1] || 1) - 1; }
  232. else if (fin === 'G') col = (nums[0] || 1) - 1;
  233. else if (fin === 'C') col += nums[0] || 1;
  234. else if (fin === 'D') col = Math.max(0, col - (nums[0] || 1));
  235. else if (fin === 'A') row = Math.max(0, row - (nums[0] || 1));
  236. else if (fin === 'B') row += nums[0] || 1;
  237. else if (fin === 'K') {
  238. const l = line(row);
  239. const mode = nums[0] || 0;
  240. if (mode === 2) l.length = 0;
  241. else if (mode === 0) l.length = Math.min(l.length, col);
  242. else for (let k = 0; k <= col && k < l.length; k++) l[k] = ' ';
  243. } else if (fin === 'J') {
  244. if ((nums[0] || 0) >= 2) grid.length = 0;
  245. else { line(row).length = Math.min(line(row).length, col); grid.length = Math.min(grid.length, row + 1); }
  246. }
  247. continue;
  248. }
  249. if (n === ']' || n === '_' || n === 'P' || n === '^') {
  250. // OSC, APC (kitty pictures), DCS (sixel), PM: up to BEL or ESC \.
  251. let j = i + 2;
  252. while (j < chars.length && chars[j] !== '\x07' && !(chars[j] === '\x1b' && chars[j + 1] === '\\')) j++;
  253. i = chars[j] === '\x07' ? j : j + 1;
  254. continue;
  255. }
  256. i += 1; // a two-character escape
  257. continue;
  258. }
  259. if (c === '\n') { row++; col = 0; continue; }
  260. if (c === '\r') { col = 0; continue; }
  261. const cp = c.codePointAt(0) ?? 32;
  262. if (cp < 0x20 || cp === 0x7f) continue;
  263. put(c, width(cp));
  264. }
  265. const lines = Array.from(grid, (l) => (l ?? []).join('').replace(/\s+$/, ''));
  266. while (lines.length && !lines[lines.length - 1]) lines.pop();
  267. return lines;
  268. }
  269. /** Parses `[address] [--flag value]... [--switch]` after the action's own words. */
  270. export function splitArgs(argv: string[]): { free: string[]; flags: string[]; ownNode: boolean } {
  271. const free: string[] = [];
  272. const flags: string[] = [];
  273. let ownNode = false;
  274. for (let i = 0; i < argv.length; i++) {
  275. const a = argv[i];
  276. if (a === '--own-node') { ownNode = true; continue; }
  277. if (a.startsWith('--')) {
  278. flags.push(a);
  279. const v = argv[i + 1];
  280. if (v !== undefined && !v.startsWith('--') && !['--desc', '--preview', '--time', '--index'].includes(a)) { flags.push(v); i++; }
  281. continue;
  282. }
  283. free.push(a);
  284. }
  285. return { free, flags, ownNode };
  286. }
  287. /** The binary or the one line that says what to do, with exit code 2. */
  288. export function needBin(root: string): Bin {
  289. const { bin } = findBin(root);
  290. if (bin) return bin;
  291. console.log(`tui: the Shtukbase binary with the text interface was not found; ${INSTALL_HINT}`);
  292. process.exit(2);
  293. }