termkit-ui 0.0.0-stage → 0.1.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 (50) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/LICENSE +9 -0
  3. package/README.md +153 -2
  4. package/dist/components/display/layout.d.ts +91 -0
  5. package/dist/components/display/table.d.ts +53 -0
  6. package/dist/components/progress/index.d.ts +2 -0
  7. package/dist/components/progress/progressBar.d.ts +102 -0
  8. package/dist/components/progress/spinner.d.ts +107 -0
  9. package/dist/components/prompts/base.d.ts +53 -0
  10. package/dist/components/prompts/confirm.d.ts +46 -0
  11. package/dist/components/prompts/index.d.ts +6 -0
  12. package/dist/components/prompts/input.d.ts +46 -0
  13. package/dist/components/prompts/multiselect.d.ts +100 -0
  14. package/dist/components/prompts/number.d.ts +58 -0
  15. package/dist/components/prompts/password.d.ts +45 -0
  16. package/dist/components/prompts/select.d.ts +84 -0
  17. package/dist/core/ansi/escapes.d.ts +154 -0
  18. package/dist/core/caps/detect.d.ts +74 -0
  19. package/dist/core/errors/index.d.ts +73 -0
  20. package/dist/core/styles/index.d.ts +12 -0
  21. package/dist/core/width/string-width.d.ts +42 -0
  22. package/dist/engine/guard/terminal-guard.d.ts +84 -0
  23. package/dist/engine/keyboard/parser.d.ts +79 -0
  24. package/dist/engine/renderer/coordinator.d.ts +85 -0
  25. package/dist/index.d.ts +13 -0
  26. package/dist/testing/index.d.ts +127 -0
  27. package/package.json +77 -4
  28. package/src/components/display/layout.js +224 -0
  29. package/src/components/display/table.js +179 -0
  30. package/src/components/progress/index.js +6 -0
  31. package/src/components/progress/progressBar.js +153 -0
  32. package/src/components/progress/spinner.js +195 -0
  33. package/src/components/prompts/base.js +237 -0
  34. package/src/components/prompts/confirm.js +68 -0
  35. package/src/components/prompts/index.js +10 -0
  36. package/src/components/prompts/input.js +107 -0
  37. package/src/components/prompts/multiselect.js +205 -0
  38. package/src/components/prompts/number.js +140 -0
  39. package/src/components/prompts/password.js +77 -0
  40. package/src/components/prompts/select.js +171 -0
  41. package/src/core/ansi/escapes.js +52 -0
  42. package/src/core/caps/detect.js +167 -0
  43. package/src/core/errors/index.js +106 -0
  44. package/src/core/styles/index.js +174 -0
  45. package/src/core/width/string-width.js +244 -0
  46. package/src/engine/guard/terminal-guard.js +188 -0
  47. package/src/engine/keyboard/parser.js +285 -0
  48. package/src/engine/renderer/coordinator.js +263 -0
  49. package/src/index.js +17 -0
  50. package/src/testing/index.js +250 -0
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Global singleton terminal state guard.
3
+ */
4
+ export const terminalGuard: TerminalGuardManager;
5
+ export type CleanupTask = () => void;
6
+ /**
7
+ * @fileoverview Terminal State Guard.
8
+ * Manages raw mode, cursor visibility, signal traps, and guaranteed exit cleanup.
9
+ */
10
+ /**
11
+ * @typedef {() => void} CleanupTask
12
+ */
13
+ declare class TerminalGuardManager {
14
+ /** @type {Set<CleanupTask>} */
15
+ _cleanups: Set<CleanupTask>;
16
+ /** @type {boolean} */
17
+ _isRawMode: boolean;
18
+ /** @type {boolean} */
19
+ _isCursorHidden: boolean;
20
+ /** @type {NodeJS.ReadableStream | null} */
21
+ _rawStream: NodeJS.ReadableStream | null;
22
+ /** @type {NodeJS.WritableStream | null} */
23
+ _cursorStream: NodeJS.WritableStream | null;
24
+ /** @type {boolean} */
25
+ _signalsAttached: boolean;
26
+ _onSigInt: () => void;
27
+ _onSigTerm: () => void;
28
+ _onExit: () => void;
29
+ _onUncaughtException: (error: Error) => void;
30
+ /**
31
+ * Attach process signal handlers once.
32
+ * @private
33
+ */
34
+ private _ensureSignals;
35
+ /**
36
+ * Detach process signal handlers if no cleanups remain.
37
+ * @private
38
+ */
39
+ private _maybeDetachSignals;
40
+ /**
41
+ * Signal handler for SIGINT/SIGTERM.
42
+ * @private
43
+ * @param {string} signal
44
+ * @param {number} exitCode
45
+ */
46
+ private _handleSignal;
47
+ /**
48
+ * Exception monitor handler.
49
+ * @private
50
+ * @param {Error} error
51
+ */
52
+ private _handleException;
53
+ /**
54
+ * Register a custom cleanup task.
55
+ * @param {CleanupTask} cleanup
56
+ * @returns {() => void} Unsubscribe function
57
+ */
58
+ register(cleanup: CleanupTask): () => void;
59
+ /**
60
+ * Enable raw mode safely on an input stream.
61
+ * @param {NodeJS.ReadableStream} [stream]
62
+ */
63
+ enableRawMode(stream?: NodeJS.ReadableStream): void;
64
+ /**
65
+ * Disable raw mode safely.
66
+ */
67
+ disableRawMode(): void;
68
+ /**
69
+ * Hide the terminal cursor safely.
70
+ * @param {NodeJS.WritableStream} [stream]
71
+ */
72
+ hideCursor(stream?: NodeJS.WritableStream): void;
73
+ /**
74
+ * Show the terminal cursor safely.
75
+ * @param {NodeJS.WritableStream} [stream]
76
+ */
77
+ showCursor(stream?: NodeJS.WritableStream): void;
78
+ /**
79
+ * Restore terminal to pristine state:
80
+ * Disables raw mode, shows cursor, and executes all registered cleanup callbacks.
81
+ */
82
+ restore(): void;
83
+ }
84
+ export {};
@@ -0,0 +1,79 @@
1
+ /**
2
+ * @typedef {Object} KeyEvent
3
+ * @property {string} name - Normalized key name (e.g. 'up', 'down', 'return', 'escape', 'backspace', 'a')
4
+ * @property {string} sequence - Raw byte or character sequence
5
+ * @property {boolean} ctrl - Whether Ctrl key was pressed
6
+ * @property {boolean} meta - Whether Meta/Alt key was pressed
7
+ * @property {boolean} shift - Whether Shift key was pressed
8
+ * @property {boolean} [isPaste] - Whether this event represents a pasted block of text
9
+ * @property {string} [pasteText] - Text content of the paste if isPaste is true
10
+ */
11
+ export class KeyboardParser extends EventEmitter<any> {
12
+ /**
13
+ * @param {NodeJS.ReadableStream} [stream] - Defaults to process.stdin
14
+ */
15
+ constructor(stream?: NodeJS.ReadableStream);
16
+ /** @type {NodeJS.ReadableStream} */
17
+ stream: NodeJS.ReadableStream;
18
+ /** @type {string} */
19
+ _buffer: string;
20
+ /** @type {boolean} */
21
+ _isPasting: boolean;
22
+ /** @type {string} */
23
+ _pasteBuffer: string;
24
+ /** @type {(chunk: Buffer | string) => void} */
25
+ _onData: (chunk: Buffer | string) => void;
26
+ /** @type {boolean} */
27
+ _attached: boolean;
28
+ /**
29
+ * Attach parser to stream.
30
+ */
31
+ attach(): void;
32
+ /**
33
+ * Detach parser from stream.
34
+ */
35
+ detach(): void;
36
+ /**
37
+ * Process raw input chunk.
38
+ * @private
39
+ * @param {Buffer | string} chunk
40
+ */
41
+ private _handleData;
42
+ /**
43
+ * Parse normal character stream.
44
+ * @private
45
+ * @param {string} str
46
+ */
47
+ private _parseNormal;
48
+ }
49
+ export type KeyEvent = {
50
+ /**
51
+ * - Normalized key name (e.g. 'up', 'down', 'return', 'escape', 'backspace', 'a')
52
+ */
53
+ name: string;
54
+ /**
55
+ * - Raw byte or character sequence
56
+ */
57
+ sequence: string;
58
+ /**
59
+ * - Whether Ctrl key was pressed
60
+ */
61
+ ctrl: boolean;
62
+ /**
63
+ * - Whether Meta/Alt key was pressed
64
+ */
65
+ meta: boolean;
66
+ /**
67
+ * - Whether Shift key was pressed
68
+ */
69
+ shift: boolean;
70
+ /**
71
+ * - Whether this event represents a pasted block of text
72
+ */
73
+ isPaste?: boolean | undefined;
74
+ /**
75
+ * - Text content of the paste if isPaste is true
76
+ */
77
+ pasteText?: string | undefined;
78
+ };
79
+ import { EventEmitter } from 'node:events';
@@ -0,0 +1,85 @@
1
+ export class LiveRegion {
2
+ /**
3
+ * @param {OutputCoordinator} coordinator
4
+ * @param {NodeJS.WritableStream} stream
5
+ */
6
+ constructor(coordinator: OutputCoordinator, stream: NodeJS.WritableStream);
7
+ /** @type {OutputCoordinator} */
8
+ coordinator: OutputCoordinator;
9
+ /** @type {NodeJS.WritableStream} */
10
+ stream: NodeJS.WritableStream;
11
+ /** @type {string[]} */
12
+ _lines: string[];
13
+ /** @type {boolean} */
14
+ _active: boolean;
15
+ /**
16
+ * Update the live region with new line contents or via a render callback.
17
+ * @param {string[] | string | (() => string[] | string)} lines
18
+ */
19
+ render(lines: string[] | string | (() => string[] | string)): void;
20
+ /**
21
+ * Get current rendered lines.
22
+ * @returns {string[]}
23
+ */
24
+ getLines(): string[];
25
+ /**
26
+ * Erase the live region from the terminal without completing it.
27
+ */
28
+ clear(): void;
29
+ /**
30
+ * Permanently unmount the live region.
31
+ * @param {string[] | string} [finalLines]
32
+ */
33
+ unmount(finalLines?: string[] | string): void;
34
+ }
35
+ export class OutputCoordinator {
36
+ /**
37
+ * @param {NodeJS.WritableStream} [stream] - Defaults to process.stderr
38
+ */
39
+ constructor(stream?: NodeJS.WritableStream);
40
+ /** @type {NodeJS.WritableStream} */
41
+ stream: NodeJS.WritableStream;
42
+ /** @type {LiveRegion | null} */
43
+ _activeRegion: LiveRegion | null;
44
+ /** @type {string[]} */
45
+ _renderedLines: string[];
46
+ _unregisterGuard: () => void;
47
+ /** @param {any} err */
48
+ _onStreamError: ((err: any) => void) | undefined;
49
+ /**
50
+ * Mount a new live region on this stream.
51
+ * @returns {LiveRegion}
52
+ */
53
+ createLiveRegion(): LiveRegion;
54
+ /**
55
+ * Update active region lines using diffed redrawing.
56
+ * @param {LiveRegion} region
57
+ * @param {string[]} nextLines
58
+ */
59
+ updateRegion(region: LiveRegion, nextLines: string[]): void;
60
+ /**
61
+ * Clear active region lines completely.
62
+ * @param {LiveRegion} region
63
+ */
64
+ clearRegion(region: LiveRegion): void;
65
+ /**
66
+ * Safe concurrent logging: prints log content ABOVE any active live region.
67
+ * @param {string} message
68
+ */
69
+ log(message: string): void;
70
+ /**
71
+ * Remove active region.
72
+ * @param {LiveRegion} region
73
+ */
74
+ removeRegion(region: LiveRegion): void;
75
+ /**
76
+ * Emergency clear on abnormal process exit.
77
+ */
78
+ emergencyClear(): void;
79
+ /**
80
+ * Dispose coordinator.
81
+ */
82
+ dispose(): void;
83
+ }
84
+ /** Default shared coordinator for process.stderr */
85
+ export const defaultCoordinator: OutputCoordinator;
@@ -0,0 +1,13 @@
1
+ export * from "./core/errors/index.js";
2
+ export * from "./core/caps/detect.js";
3
+ export * from "./core/ansi/escapes.js";
4
+ export * from "./core/width/string-width.js";
5
+ export * from "./core/styles/index.js";
6
+ export * from "./engine/guard/terminal-guard.js";
7
+ export * from "./engine/renderer/coordinator.js";
8
+ export * from "./engine/keyboard/parser.js";
9
+ export * from "./components/prompts/index.js";
10
+ export * from "./components/progress/index.js";
11
+ export * from "./components/display/layout.js";
12
+ export * from "./components/display/table.js";
13
+ export * from "./testing/index.js";
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Factory to create an isolated VirtualTerminal.
3
+ * @param {Object} [options]
4
+ * @returns {VirtualTerminal}
5
+ */
6
+ export function createTestTerminal(options?: Object): VirtualTerminal;
7
+ export class MockReadableStream extends Readable {
8
+ constructor();
9
+ /** @type {boolean} */
10
+ isTTY: boolean;
11
+ _read(): void;
12
+ /**
13
+ * Push raw string or buffer to stream.
14
+ * @param {string | Buffer} data
15
+ */
16
+ sendData(data: string | Buffer): void;
17
+ /**
18
+ * Set raw mode mock.
19
+ * @param {boolean} mode
20
+ */
21
+ setRawMode(mode: boolean): void;
22
+ }
23
+ export class MockWritableStream extends Writable {
24
+ /**
25
+ * Mock writable stream with optional hermetic capability overrides.
26
+ * NOTE: Injecting capabilities is a testing-only mechanism to isolate tests
27
+ * from ambient environment variables and host TTY state.
28
+ * @param {Record<string, any>} [capabilities]
29
+ */
30
+ constructor(capabilities?: Record<string, any>);
31
+ /** @type {string} */
32
+ buffer: string;
33
+ /** @type {boolean} */
34
+ isTTY: boolean;
35
+ /** @type {number} */
36
+ columns: number;
37
+ /** @type {number} */
38
+ rows: number;
39
+ /** @type {Record<string, any>} */
40
+ capabilities: Record<string, any>;
41
+ /** @type {Record<string, any>} */
42
+ _capabilities: Record<string, any>;
43
+ /**
44
+ * @param {any} chunk
45
+ * @param {string} encoding
46
+ * @param {() => void} callback
47
+ */
48
+ _write(chunk: any, encoding: string, callback: () => void): void;
49
+ clear(): void;
50
+ getColorDepth(): 24 | 1 | 8 | 4;
51
+ }
52
+ export class VirtualTerminal {
53
+ /**
54
+ * @param {Object} [options]
55
+ * @param {number} [options.columns=80]
56
+ * @param {number} [options.rows=24]
57
+ * @param {boolean} [options.isTTY=true]
58
+ * @param {Partial<import('../core/caps/detect.js').TerminalCapabilities>} [options.capabilities]
59
+ */
60
+ constructor(options?: {
61
+ columns?: number | undefined;
62
+ rows?: number | undefined;
63
+ isTTY?: boolean | undefined;
64
+ capabilities?: Partial<import("../core/caps/detect.js").TerminalCapabilities> | undefined;
65
+ });
66
+ /** @type {MockReadableStream} */
67
+ stdin: MockReadableStream;
68
+ /** @type {MockWritableStream} */
69
+ stdout: MockWritableStream;
70
+ /** @type {MockWritableStream} */
71
+ stderr: MockWritableStream;
72
+ /**
73
+ * Type text into stdin.
74
+ * @param {string} text
75
+ * @returns {Promise<void>}
76
+ */
77
+ type(text: string): Promise<void>;
78
+ /**
79
+ * Send key event sequence into stdin.
80
+ * @param {string} name
81
+ * @param {Object} [modifiers]
82
+ * @param {boolean} [modifiers.ctrl]
83
+ * @param {boolean} [modifiers.meta]
84
+ * @param {boolean} [modifiers.shift]
85
+ * @returns {Promise<void>}
86
+ */
87
+ pressKey(name: string, modifiers?: {
88
+ ctrl?: boolean | undefined;
89
+ meta?: boolean | undefined;
90
+ shift?: boolean | undefined;
91
+ }): Promise<void>;
92
+ pressEnter(): Promise<void>;
93
+ pressArrowDown(): Promise<void>;
94
+ pressArrowUp(): Promise<void>;
95
+ pressSpace(): Promise<void>;
96
+ pressCtrlC(): Promise<void>;
97
+ pressEscape(): Promise<void>;
98
+ /**
99
+ * Get output text with ANSI sequences stripped.
100
+ * Pass { raw: true } to preserve raw ANSI escape sequences.
101
+ * @param {'stdout' | 'stderr'} [stream='stderr']
102
+ * @param {Object} [options]
103
+ * @param {boolean} [options.raw=false]
104
+ * @returns {string}
105
+ */
106
+ getText(stream?: "stdout" | "stderr", options?: {
107
+ raw?: boolean | undefined;
108
+ }): string;
109
+ /**
110
+ * Get raw unstripped output text including ANSI escape sequences.
111
+ * @param {'stdout' | 'stderr'} [stream='stderr']
112
+ * @returns {string}
113
+ */
114
+ getRawText(stream?: "stdout" | "stderr"): string;
115
+ /**
116
+ * Get cleaned output lines with ANSI stripped.
117
+ * @param {'stdout' | 'stderr'} [stream='stderr']
118
+ * @returns {string[]}
119
+ */
120
+ getLines(stream?: "stdout" | "stderr"): string[];
121
+ /**
122
+ * Clear capture buffers.
123
+ */
124
+ clear(): void;
125
+ }
126
+ import { Readable } from 'node:stream';
127
+ import { Writable } from 'node:stream';
package/package.json CHANGED
@@ -1,6 +1,79 @@
1
1
  {
2
2
  "name": "termkit-ui",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Zero-dependency, cohesive TypeScript/ESM toolkit for building robust Node.js CLI user interfaces",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "author": "Sagar <incrediblesagar77@gmail.com>",
8
+ "license": "MIT",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/hexqbv/TermKit.git"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/hexqbv/TermKit/issues"
15
+ },
16
+ "homepage": "https://github.com/hexqbv/TermKit#readme",
17
+ "engines": {
18
+ "node": ">=22.0.0"
19
+ },
20
+ "files": [
21
+ "dist",
22
+ "src",
23
+ "README.md",
24
+ "LICENSE",
25
+ "CHANGELOG.md"
26
+ ],
27
+ "exports": {
28
+ ".": {
29
+ "types": "./dist/index.d.ts",
30
+ "default": "./src/index.js"
31
+ },
32
+ "./prompts": {
33
+ "types": "./dist/components/prompts/index.d.ts",
34
+ "default": "./src/components/prompts/index.js"
35
+ },
36
+ "./progress": {
37
+ "types": "./dist/components/progress/index.d.ts",
38
+ "default": "./src/components/progress/index.js"
39
+ },
40
+ "./styles": {
41
+ "types": "./dist/core/styles/index.d.ts",
42
+ "default": "./src/core/styles/index.js"
43
+ },
44
+ "./layout": {
45
+ "types": "./dist/components/display/layout.d.ts",
46
+ "default": "./src/components/display/layout.js"
47
+ },
48
+ "./tables": {
49
+ "types": "./dist/components/display/table.d.ts",
50
+ "default": "./src/components/display/table.js"
51
+ },
52
+ "./testing": {
53
+ "types": "./dist/testing/index.d.ts",
54
+ "default": "./src/testing/index.js"
55
+ },
56
+ "./package.json": "./package.json"
57
+ },
58
+ "scripts": {
59
+ "test": "node --test \"test/**/*.test.js\"",
60
+ "test:matrix": "node scripts/test-matrix.js",
61
+ "test:package": "node scripts/test-package.js",
62
+ "typecheck": "tsc --noEmit",
63
+ "build:types": "tsc --emitDeclarationOnly",
64
+ "prepack": "npm run build:types",
65
+ "verify:docs": "node scripts/verify-api-docs.js"
66
+ },
67
+ "peerDependencies": {
68
+ "@types/node": ">=22.0.0"
69
+ },
70
+ "peerDependenciesMeta": {
71
+ "@types/node": {
72
+ "optional": true
73
+ }
74
+ },
75
+ "devDependencies": {
76
+ "@types/node": "^26.6.6",
77
+ "typescript": "^5.9.3"
78
+ }
79
+ }
@@ -0,0 +1,224 @@
1
+ /**
2
+ * @fileoverview Box and Divider layout components.
3
+ */
4
+
5
+ import { detectCapabilities } from '../../core/caps/detect.js';
6
+ import { style } from '../../core/styles/index.js';
7
+ import { stringWidth, truncate } from '../../core/width/string-width.js';
8
+
9
+ const BORDER_STYLES = {
10
+ single: {
11
+ topLeft: '┌',
12
+ topRight: '┐',
13
+ bottomLeft: '└',
14
+ bottomRight: '┘',
15
+ horizontal: '─',
16
+ vertical: '│'
17
+ },
18
+ double: {
19
+ topLeft: '╔',
20
+ topRight: '╗',
21
+ bottomLeft: '╚',
22
+ bottomRight: '╝',
23
+ horizontal: '═',
24
+ vertical: '║'
25
+ },
26
+ rounded: {
27
+ topLeft: '╭',
28
+ topRight: '╮',
29
+ bottomLeft: '╰',
30
+ bottomRight: '╯',
31
+ horizontal: '─',
32
+ vertical: '│'
33
+ },
34
+ bold: {
35
+ topLeft: '┏',
36
+ topRight: '┓',
37
+ bottomLeft: '┗',
38
+ bottomRight: '┛',
39
+ horizontal: '━',
40
+ vertical: '┃'
41
+ },
42
+ ascii: {
43
+ topLeft: '+',
44
+ topRight: '+',
45
+ bottomLeft: '+',
46
+ bottomRight: '+',
47
+ horizontal: '-',
48
+ vertical: '|'
49
+ }
50
+ };
51
+
52
+ /**
53
+ * @typedef {Object} BoxPadding
54
+ * @property {number} [top=0]
55
+ * @property {number} [bottom=0]
56
+ * @property {number} [left=1]
57
+ * @property {number} [right=1]
58
+ */
59
+
60
+ /**
61
+ * @typedef {Object} BoxOptions
62
+ * @property {string} [title] - Optional box title
63
+ * @property {'left' | 'center' | 'right'} [titleAlign='left']
64
+ * @property {'single' | 'double' | 'rounded' | 'bold' | 'ascii'} [borderStyle='rounded']
65
+ * @property {string} [borderColor] - Border color (e.g. 'cyan', 'green', 'dim')
66
+ * @property {number | BoxPadding} [padding=0]
67
+ * @property {number} [width] - Explicit box width
68
+ * @property {'left' | 'center' | 'right'} [align='left']
69
+ * @property {Partial<import('../../core/caps/detect.js').TerminalCapabilities>} [capabilities] - Override detected capabilities (testing only)
70
+ */
71
+
72
+ /**
73
+ * Format string content inside a styled terminal box.
74
+ * @param {string} content
75
+ * @param {BoxOptions} [options={}]
76
+ * @returns {string}
77
+ */
78
+ export function box(content, options = {}) {
79
+ const caps = options.capabilities || detectCapabilities();
80
+ const borderName = !caps.unicode ? 'ascii' : (options.borderStyle || 'rounded');
81
+ const b = BORDER_STYLES[borderName] || BORDER_STYLES.single;
82
+
83
+ const pad =
84
+ typeof options.padding === 'number'
85
+ ? { top: options.padding, bottom: options.padding, left: options.padding, right: options.padding }
86
+ : {
87
+ top: options.padding?.top || 0,
88
+ bottom: options.padding?.bottom || 0,
89
+ left: options.padding?.left !== undefined ? options.padding.left : 1,
90
+ right: options.padding?.right !== undefined ? options.padding.right : 1
91
+ };
92
+
93
+ const rawLines = content.split('\n');
94
+ let maxContentWidth = 0;
95
+ for (const line of rawLines) {
96
+ maxContentWidth = Math.max(maxContentWidth, stringWidth(line));
97
+ }
98
+
99
+ const titleWidth = options.title ? stringWidth(options.title) + 2 : 0;
100
+ const innerWidth = options.width
101
+ ? Math.max(1, options.width - 2 - pad.left - pad.right)
102
+ : Math.max(maxContentWidth, titleWidth);
103
+
104
+ // Border styler
105
+ const colorFn = options.borderColor && typeof /** @type {any} */ (style)[options.borderColor] === 'function'
106
+ ? /** @type {any} */ (style)[options.borderColor]
107
+ : (/** @type {string} */ s) => s;
108
+
109
+ const result = [];
110
+
111
+ // Top Border with Title
112
+ let topBorder = '';
113
+ if (options.title) {
114
+ const rawTitleStr = ` ${options.title} `;
115
+ const maxTitleSpace = innerWidth + pad.left + pad.right;
116
+ const ellipsis = caps.unicode ? '…' : '...';
117
+ const titleStr = stringWidth(rawTitleStr) > maxTitleSpace ? truncate(rawTitleStr, maxTitleSpace, ellipsis) : rawTitleStr;
118
+ const availSpace = Math.max(0, maxTitleSpace - stringWidth(titleStr));
119
+ let leftDashes = 1;
120
+ let rightDashes = Math.max(0, availSpace - leftDashes);
121
+
122
+ if (options.titleAlign === 'center') {
123
+ leftDashes = Math.floor(availSpace / 2);
124
+ rightDashes = Math.max(0, availSpace - leftDashes);
125
+ } else if (options.titleAlign === 'right') {
126
+ rightDashes = 1;
127
+ leftDashes = Math.max(0, availSpace - rightDashes);
128
+ }
129
+
130
+ topBorder =
131
+ colorFn(b.topLeft + b.horizontal.repeat(leftDashes)) +
132
+ style.bold(titleStr) +
133
+ colorFn(b.horizontal.repeat(rightDashes) + b.topRight);
134
+ } else {
135
+ topBorder = colorFn(b.topLeft + b.horizontal.repeat(innerWidth + pad.left + pad.right) + b.topRight);
136
+ }
137
+ result.push(topBorder);
138
+
139
+ // Top Padding
140
+ const emptyRow = colorFn(b.vertical) + ' '.repeat(innerWidth + pad.left + pad.right) + colorFn(b.vertical);
141
+ for (let i = 0; i < pad.top; i++) {
142
+ result.push(emptyRow);
143
+ }
144
+
145
+ // Content Lines
146
+ for (const line of rawLines) {
147
+ const ellipsisChar = caps.unicode ? '…' : '...';
148
+ const displayLine = options.width && stringWidth(line) > innerWidth ? truncate(line, innerWidth, ellipsisChar) : line;
149
+ const lineWidth = stringWidth(displayLine);
150
+ const spaceToFill = Math.max(0, innerWidth - lineWidth);
151
+
152
+ let leftPad = pad.left;
153
+ let rightPad = pad.right + spaceToFill;
154
+
155
+ if (options.align === 'center') {
156
+ const extraLeft = Math.floor(spaceToFill / 2);
157
+ leftPad += extraLeft;
158
+ rightPad = pad.right + (spaceToFill - extraLeft);
159
+ } else if (options.align === 'right') {
160
+ leftPad += spaceToFill;
161
+ rightPad = pad.right;
162
+ }
163
+
164
+ result.push(colorFn(b.vertical) + ' '.repeat(leftPad) + displayLine + ' '.repeat(rightPad) + colorFn(b.vertical));
165
+ }
166
+
167
+ // Bottom Padding
168
+ for (let i = 0; i < pad.bottom; i++) {
169
+ result.push(emptyRow);
170
+ }
171
+
172
+ // Bottom Border
173
+ result.push(colorFn(b.bottomLeft + b.horizontal.repeat(innerWidth + pad.left + pad.right) + b.bottomRight));
174
+
175
+ return result.join('\n');
176
+ }
177
+
178
+ /**
179
+ * @typedef {Object} DividerOptions
180
+ * @property {string} [title] - Optional title
181
+ * @property {'left' | 'center' | 'right'} [titleAlign='center']
182
+ * @property {string} [character='─'] - Divider character
183
+ * @property {string} [color='dim'] - Color style
184
+ * @property {number} [width] - Divider length (defaults to terminal columns)
185
+ * @property {Partial<import('../../core/caps/detect.js').TerminalCapabilities>} [capabilities] - Override detected capabilities (testing only)
186
+ */
187
+
188
+ /**
189
+ * Create a horizontal divider rule.
190
+ * @param {DividerOptions | string} [options='']
191
+ * @returns {string}
192
+ */
193
+ export function divider(options = '') {
194
+ const opts = typeof options === 'string' ? { title: options } : options;
195
+ const caps = opts.capabilities || detectCapabilities();
196
+ const width = opts.width || caps.columns || 80;
197
+ const rawChar = !caps.unicode
198
+ ? (opts.character && /^[\x00-\x7F]+$/.test(opts.character) ? opts.character : '-')
199
+ : (opts.character || '─');
200
+ const colorFn = opts.color && typeof /** @type {any} */ (style)[opts.color] === 'function'
201
+ ? /** @type {any} */ (style)[opts.color]
202
+ : style.dim;
203
+
204
+ if (!opts.title) {
205
+ return colorFn(rawChar.repeat(width));
206
+ }
207
+
208
+ const titleStr = ` ${opts.title} `;
209
+ const titleWidth = stringWidth(titleStr);
210
+ const remaining = Math.max(0, width - titleWidth);
211
+
212
+ let leftCount = Math.floor(remaining / 2);
213
+ let rightCount = remaining - leftCount;
214
+
215
+ if (opts.titleAlign === 'left') {
216
+ leftCount = 2;
217
+ rightCount = Math.max(0, remaining - leftCount);
218
+ } else if (opts.titleAlign === 'right') {
219
+ rightCount = 2;
220
+ leftCount = Math.max(0, remaining - rightCount);
221
+ }
222
+
223
+ return colorFn(rawChar.repeat(leftCount)) + style.bold(titleStr) + colorFn(rawChar.repeat(rightCount));
224
+ }