diff --git a/package-lock.json b/package-lock.json index 3ff6f02..010f476 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,6 +9,8 @@ "version": "0.1.0", "dependencies": { "@simplewebauthn/server": "^13.1.1", + "@xterm/addon-fit": "^0.11.0", + "@xterm/xterm": "^6.0.0", "argon2": "^0.41.1", "better-sqlite3": "^11.8.1", "chokidar": "^4.0.3", @@ -1420,6 +1422,21 @@ "url": "https://opencollective.com/vitest" } }, + "node_modules/@xterm/addon-fit": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.11.0.tgz", + "integrity": "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==", + "license": "MIT" + }, + "node_modules/@xterm/xterm": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.0.0.tgz", + "integrity": "sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==", + "license": "MIT", + "workspaces": [ + "addons/*" + ] + }, "node_modules/accepts": { "version": "1.3.8", "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", diff --git a/package.json b/package.json index 7533a37..24db5a4 100644 --- a/package.json +++ b/package.json @@ -20,6 +20,8 @@ }, "dependencies": { "@simplewebauthn/server": "^13.1.1", + "@xterm/addon-fit": "^0.11.0", + "@xterm/xterm": "^6.0.0", "argon2": "^0.41.1", "better-sqlite3": "^11.8.1", "chokidar": "^4.0.3", diff --git a/src/server/api/ws-hub.ts b/src/server/api/ws-hub.ts index 1536556..953d5ab 100644 --- a/src/server/api/ws-hub.ts +++ b/src/server/api/ws-hub.ts @@ -1,3 +1,4 @@ +import type { Duplex } from 'node:stream'; import type { IncomingMessage, Server as HttpServer } from 'node:http'; import { WebSocket, WebSocketServer } from 'ws'; import { @@ -17,10 +18,32 @@ interface WsClientMeta { alive: boolean; } +export type WsUpgradeHandler = ( + req: IncomingMessage, + socket: Duplex, + head: Buffer, +) => void; + +export type WsSubscribeListener = ( + ctx: { + send: (frame: ServerWsFrame) => void; + sessionIdHash: string; + }, + channel: string, +) => void; + +export interface WsPtyHandlers { + onInput: (sessionId: string, data: string) => void; + onResize: (sessionId: string, cols: number, rows: number) => void; +} + export class WsHub { private readonly wss = new WebSocketServer({ noServer: true }); private readonly clients = new Set(); private readonly pingTimer: NodeJS.Timeout; + private readonly upgradeHandlers: Array<{ prefix: string; handler: WsUpgradeHandler }> = []; + private readonly subscribeListeners = new Set(); + private ptyHandlers: WsPtyHandlers | null = null; constructor( httpServer: HttpServer, @@ -45,6 +68,21 @@ export class WsHub { this.pingTimer.unref(); } + registerUpgradeHandler(prefix: string, handler: WsUpgradeHandler): void { + this.upgradeHandlers.push({ prefix, handler }); + } + + onChannelSubscribe(listener: WsSubscribeListener): () => void { + this.subscribeListeners.add(listener); + return () => { + this.subscribeListeners.delete(listener); + }; + } + + attachPtyHandlers(handlers: WsPtyHandlers): void { + this.ptyHandlers = handlers; + } + close(): void { clearInterval(this.pingTimer); for (const client of this.clients) { @@ -92,10 +130,16 @@ export class WsHub { private handleUpgrade( req: IncomingMessage, - socket: import('node:stream').Duplex, + socket: Duplex, head: Buffer, ): void { - const urlPath = (req.url ?? '').split('?')[0]; + const urlPath = (req.url ?? '').split('?')[0] ?? ''; + for (const entry of this.upgradeHandlers) { + if (urlPath.startsWith(entry.prefix)) { + entry.handler(req, socket, head); + return; + } + } if (urlPath !== '/ws') { socket.write('HTTP/1.1 404 Not Found\r\n\r\n'); socket.destroy(); @@ -198,11 +242,23 @@ export class WsHub { serverTs: Date.now(), }); break; - case 'sub': + case 'sub': { + const ctx = { + send: (outFrame: ServerWsFrame) => this.sendFrame(meta.ws, outFrame), + sessionIdHash: meta.sessionIdHash, + }; for (const ch of frame.channels) { meta.channels.add(ch); + for (const listener of this.subscribeListeners) { + try { + listener(ctx, ch); + } catch { + // Isolate subscriber replay errors + } + } } break; + } case 'unsub': for (const ch of frame.channels) { meta.channels.delete(ch); @@ -225,12 +281,20 @@ export class WsHub { }); return; } - // Phase 3 PTYManager attaches here + this.ptyHandlers?.onInput(frame.sessionId, frame.data); + break; + } + case 'pty:resize': { + const latestSession = this.authService.getSessionByToken(meta.sessionToken); + if (!latestSession) { + meta.ws.close(4001, 'Session expired'); + return; + } + this.ptyHandlers?.onResize(frame.sessionId, frame.cols, frame.rows); break; } - case 'pty:resize': case 'ai:cancel': - // Wired in Phases 3 and 5 + // Wired in Phase 5 break; } } diff --git a/src/server/config/diff.ts b/src/server/config/diff.ts index 4d7c424..229cd3a 100644 --- a/src/server/config/diff.ts +++ b/src/server/config/diff.ts @@ -1,98 +1 @@ -export interface DiffLine { - type: 'equal' | 'add' | 'del'; - oldLine?: number; - newLine?: number; - text: string; -} - -export interface DiffResult { - lines: DiffLine[]; - unified: string; - additions: number; - deletions: number; -} - -export function computeLineDiff( - oldText: string, - newText: string, - oldLabel = 'revision', - newLabel = 'current', -): DiffResult { - const a = oldText.replace(/\r\n/g, '\n').split('\n'); - const b = newText.replace(/\r\n/g, '\n').split('\n'); - const m = a.length; - const n = b.length; - - let lines: DiffLine[]; - - // DP LCS works cleanly for config files up to a few thousand lines - if (m * n <= 2_500_000) { - const dp = new Int32Array((m + 1) * (n + 1)); - const stride = n + 1; - - for (let i = m - 1; i >= 0; i--) { - for (let j = n - 1; j >= 0; j--) { - if (a[i] === b[j]) { - dp[i * stride + j] = dp[(i + 1) * stride + (j + 1)]! + 1; - } else { - const down = dp[(i + 1) * stride + j]!; - const right = dp[i * stride + (j + 1)]!; - dp[i * stride + j] = down >= right ? down : right; - } - } - } - - lines = []; - let i = 0; - let j = 0; - while (i < m && j < n) { - if (a[i] === b[j]) { - lines.push({ type: 'equal', oldLine: i + 1, newLine: j + 1, text: a[i]! }); - i++; - j++; - } else if (dp[(i + 1) * stride + j]! >= dp[i * stride + (j + 1)]!) { - lines.push({ type: 'del', oldLine: i + 1, text: a[i]! }); - i++; - } else { - lines.push({ type: 'add', newLine: j + 1, text: b[j]! }); - j++; - } - } - while (i < m) { - lines.push({ type: 'del', oldLine: i + 1, text: a[i]! }); - i++; - } - while (j < n) { - lines.push({ type: 'add', newLine: j + 1, text: b[j]! }); - j++; - } - } else { - // Fallback linear diff for unexpectedly massive inputs - lines = [ - ...a.map((text, idx) => ({ type: 'del' as const, oldLine: idx + 1, text })), - ...b.map((text, idx) => ({ type: 'add' as const, newLine: idx + 1, text })), - ]; - } - - let additions = 0; - let deletions = 0; - const body: string[] = [`--- ${oldLabel}`, `+++ ${newLabel}`]; - for (const line of lines) { - if (line.type === 'add') { - additions++; - body.push(`+${line.text}`); - } else if (line.type === 'del') { - deletions++; - body.push(`-${line.text}`); - } else { - body.push(` ${line.text}`); - } - } - - return { - lines, - unified: body.join('\n'), - additions, - deletions, - }; -} +export * from '../../shared/diff.js'; diff --git a/src/server/ssh/pty-manager.ts b/src/server/ssh/pty-manager.ts new file mode 100644 index 0000000..87bf2b9 --- /dev/null +++ b/src/server/ssh/pty-manager.ts @@ -0,0 +1,331 @@ +import crypto from 'node:crypto'; +import { StringDecoder } from 'node:string_decoder'; +import type { ClientChannel } from 'ssh2'; +import { WS_CHANNELS } from '../../shared/ws-protocol.js'; +import type { WsHub } from '../api/ws-hub.js'; +import type { ConfigManager } from '../config/config-manager.js'; +import type { SSHPool } from './ssh-pool.js'; +import { posixSingleQuote } from './sudo.js'; + +export interface PtySessionInfo { + sessionId: string; + serverId: string; + title: string; + cwd?: string; + command?: string; + cols: number; + rows: number; + createdAt: number; + lastActivityAt: number; + exited: boolean; + exitCode: number | null; + scrollbackBytes: number; +} + +export interface OpenPtyParams { + serverId: string; + cols?: number; + rows?: number; + cwd?: string; + command?: string; + env?: Record; + sudo?: boolean; + title?: string; +} + +interface ScrollChunk { + text: string; + bytes: number; +} + +interface InternalPtySession { + info: PtySessionInfo; + channel: ClientChannel; + chunks: ScrollChunk[]; + stdoutDecoder: StringDecoder; + stderrDecoder: StringDecoder; +} + +const MAX_RETAINED_EXITED_SESSIONS = 20; + +export function formatRemoteCd(cwd: string): string { + const trimmed = cwd.trim(); + if (trimmed === '~' || trimmed === '~/') { + return 'cd -- "$HOME"'; + } + if (trimmed.startsWith('~/')) { + return `cd -- "$HOME/"${posixSingleQuote(trimmed.slice(2))}`; + } + return `cd -- ${posixSingleQuote(trimmed)}`; +} + +export function stripAnsiSequences(input: string): string { + return input + .replace(/\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]/g, '') + .replace(/\r\n/g, '\n'); +} + +function sliceTrailingUtf8(text: string, maxBytes: number): { text: string; bytes: number } { + const buf = Buffer.from(text, 'utf8'); + if (buf.length <= maxBytes) { + return { text, bytes: buf.length }; + } + let start = buf.length - maxBytes; + // Skip UTF-8 continuation bytes (10xxxxxx) so we never cut inside a codepoint + while (start < buf.length && (buf[start]! & 0b1100_0000) === 0b1000_0000) { + start++; + } + const sliced = buf.subarray(start); + return { text: sliced.toString('utf8'), bytes: sliced.length }; +} + +export class PTYManager { + private readonly sessions = new Map(); + private readonly reaperTimer: NodeJS.Timeout; + + constructor( + private readonly sshPool: SSHPool, + private readonly configManager: ConfigManager, + private readonly wsHub: WsHub, + ) { + this.reaperTimer = setInterval(() => { + this.reapIdleSessions(); + }, 30_000); + this.reaperTimer.unref(); + } + + async openSession(params: OpenPtyParams): Promise { + const cols = Math.max(10, Math.min(500, Math.floor(params.cols ?? 80))); + const rows = Math.max(4, Math.min(200, Math.floor(params.rows ?? 24))); + const now = Date.now(); + const sessionId = `pty-${crypto.randomBytes(6).toString('hex')}`; + const trimmedCwd = params.cwd?.trim(); + + let channel: ClientChannel; + if (params.command) { + const cmd = trimmedCwd + ? `${formatRemoteCd(trimmedCwd)} && (${params.command})` + : params.command; + const stream = await this.sshPool.execStream(params.serverId, cmd, { + env: params.env, + sudo: params.sudo, + pty: { cols, rows, term: 'xterm-256color' }, + }); + channel = stream.channel; + } else { + channel = await this.sshPool.openShell(params.serverId, { + cols, + rows, + term: 'xterm-256color', + }); + if (trimmedCwd && trimmedCwd !== '~') { + channel.write(`${formatRemoteCd(trimmedCwd)}\n`); + } + } + + const title = + params.title?.trim() || + (params.command + ? `${params.serverId}: ${params.command.slice(0, 32)}` + : `${params.serverId} shell`); + + const internal: InternalPtySession = { + info: { + sessionId, + serverId: params.serverId, + title, + cwd: trimmedCwd || undefined, + command: params.command, + cols, + rows, + createdAt: now, + lastActivityAt: now, + exited: false, + exitCode: null, + scrollbackBytes: 0, + }, + channel, + chunks: [], + stdoutDecoder: new StringDecoder('utf8'), + stderrDecoder: new StringDecoder('utf8'), + }; + this.sessions.set(sessionId, internal); + + channel.on('data', (chunk: Buffer) => { + const text = internal.stdoutDecoder.write(chunk); + if (text) this.appendOutput(internal, text); + }); + + channel.stderr?.on('data', (chunk: Buffer) => { + const text = internal.stderrDecoder.write(chunk); + if (text) this.appendOutput(internal, text); + }); + + const finalizeExit = (code: number | null) => { + if (internal.info.exited) return; + const tailOut = internal.stdoutDecoder.end(); + if (tailOut) this.appendOutput(internal, tailOut); + const tailErr = internal.stderrDecoder.end(); + if (tailErr) this.appendOutput(internal, tailErr); + + internal.info.exited = true; + internal.info.exitCode = code; + internal.info.lastActivityAt = Date.now(); + this.wsHub.broadcastChannel(WS_CHANNELS.pty(sessionId), { + type: 'pty:exit', + sessionId, + exitCode: code, + }); + this.pruneExcessExited(); + }; + + channel.on('exit', (code: number | null) => { + finalizeExit(typeof code === 'number' ? code : null); + }); + channel.on('close', () => { + finalizeExit(internal.info.exitCode); + }); + + return { ...internal.info }; + } + + listSessions(): PtySessionInfo[] { + return [...this.sessions.values()] + .map((s) => ({ ...s.info })) + .sort((a, b) => b.createdAt - a.createdAt); + } + + getSession(sessionId: string): PtySessionInfo | undefined { + const entry = this.sessions.get(sessionId); + return entry ? { ...entry.info } : undefined; + } + + writeInput(sessionId: string, data: string): boolean { + const entry = this.sessions.get(sessionId); + if (!entry || entry.info.exited) return false; + entry.info.lastActivityAt = Date.now(); + return entry.channel.write(data); + } + + resize(sessionId: string, cols: number, rows: number): boolean { + const entry = this.sessions.get(sessionId); + if (!entry || entry.info.exited) return false; + const clampedCols = Math.max(10, Math.min(500, Math.floor(cols))); + const clampedRows = Math.max(4, Math.min(200, Math.floor(rows))); + entry.info.cols = clampedCols; + entry.info.rows = clampedRows; + entry.info.lastActivityAt = Date.now(); + // @types/ssh2: Channel.setWindow(rows, cols, height, width) + entry.channel.setWindow(clampedRows, clampedCols, 0, 0); + return true; + } + + getScrollback(sessionId: string): string | null { + const entry = this.sessions.get(sessionId); + if (!entry) return null; + return entry.chunks.map((c) => c.text).join(''); + } + + exportScrollback( + sessionId: string, + format: 'plain' | 'ansi' = 'plain', + ): { filename: string; content: string } | null { + const entry = this.sessions.get(sessionId); + if (!entry) return null; + const raw = entry.chunks.map((c) => c.text).join(''); + const content = format === 'ansi' ? raw : stripAnsiSequences(raw); + const ext = format === 'ansi' ? 'ansi.log' : 'txt'; + return { + filename: `${entry.info.serverId}-${sessionId}.${ext}`, + content, + }; + } + + closeSession(sessionId: string): boolean { + const entry = this.sessions.get(sessionId); + if (!entry) return false; + this.sessions.delete(sessionId); + this.destroyChannel(entry); + return true; + } + + closeServerSessions(serverId: string): void { + for (const [id, entry] of this.sessions.entries()) { + if (entry.info.serverId === serverId) { + this.sessions.delete(id); + this.destroyChannel(entry); + } + } + } + + closeAll(wipeScrollback = true): void { + for (const [id, entry] of this.sessions.entries()) { + this.sessions.delete(id); + if (wipeScrollback) { + entry.chunks = []; + entry.info.scrollbackBytes = 0; + } + this.destroyChannel(entry); + } + } + + close(): void { + clearInterval(this.reaperTimer); + this.closeAll(true); + } + + private appendOutput(entry: InternalPtySession, text: string): void { + const maxBytes = Math.max(16_384, this.configManager.getSettings().ptyScrollbackBytes); + const rawBytes = Buffer.byteLength(text, 'utf8'); + + if (rawBytes >= maxBytes) { + const trimmed = sliceTrailingUtf8(text, maxBytes); + entry.chunks = [{ text: trimmed.text, bytes: trimmed.bytes }]; + entry.info.scrollbackBytes = trimmed.bytes; + } else { + entry.chunks.push({ text, bytes: rawBytes }); + entry.info.scrollbackBytes += rawBytes; + while (entry.info.scrollbackBytes > maxBytes && entry.chunks.length > 0) { + const dropped = entry.chunks.shift()!; + entry.info.scrollbackBytes -= dropped.bytes; + } + } + + entry.info.lastActivityAt = Date.now(); + this.wsHub.broadcastChannel(WS_CHANNELS.pty(entry.info.sessionId), { + type: 'pty:output', + sessionId: entry.info.sessionId, + data: text, + }); + } + + private destroyChannel(entry: InternalPtySession): void { + try { + entry.channel.close(); + entry.channel.destroy(); + } catch { + // Ignore close errors + } + } + + private reapIdleSessions(): void { + const ttlMs = Math.max(60, this.configManager.getSettings().ptyIdleTtlSec) * 1000; + const cutoff = Date.now() - ttlMs; + for (const [id, entry] of this.sessions.entries()) { + if (entry.info.lastActivityAt < cutoff) { + this.sessions.delete(id); + this.destroyChannel(entry); + } + } + } + + private pruneExcessExited(): void { + const exited = [...this.sessions.values()] + .filter((s) => s.info.exited) + .sort((a, b) => a.info.lastActivityAt - b.info.lastActivityAt); + while (exited.length > MAX_RETAINED_EXITED_SESSIONS) { + const oldest = exited.shift()!; + this.sessions.delete(oldest.info.sessionId); + } + } +} diff --git a/src/server/ssh/ssh-pool.ts b/src/server/ssh/ssh-pool.ts index d8198aa..9c83360 100644 --- a/src/server/ssh/ssh-pool.ts +++ b/src/server/ssh/ssh-pool.ts @@ -1,5 +1,10 @@ import type { Duplex } from 'node:stream'; -import ssh2, { type Client, type ConnectConfig } from 'ssh2'; +import ssh2, { + type Client, + type ClientChannel, + type ConnectConfig, + type SFTPWrapper, +} from 'ssh2'; import type { ServerConfig } from '../../shared/schemas/server.schema.js'; import type { ServerConnectionStatus, @@ -26,6 +31,19 @@ export interface ExecOptions { maxBytes?: number; } +export interface ExecStreamOptions { + sudo?: boolean; + env?: Record; + pty?: { cols: number; rows: number; term?: string }; + stdin?: Buffer | string; +} + +export interface ExecStreamHandle { + channel: ClientChannel; + done: Promise<{ exitCode: number | null; signal?: string }>; + abort: () => void; +} + interface PooledConnection { serverId: string; client: Client; @@ -135,17 +153,11 @@ export class SSHPool { return connectPromise; } - async exec( - serverId: string, + private prepareCommand( + server: ServerConfig, command: string, - opts: ExecOptions = {}, - ): Promise { - const client = await this.acquireClient(serverId); - const server = this.configManager.getServer(serverId); - if (!server) { - throw new Error(`Unknown server "${serverId}"`); - } - + opts: { sudo?: boolean; env?: Record; stdin?: Buffer | string }, + ): { finalCommand: string; stdinBuf?: Buffer } { const envPrefix = buildEnvPrefix(opts.env); let finalCommand = `${envPrefix}${command}`; let stdinBuf: Buffer | undefined = @@ -172,6 +184,127 @@ export class SSHPool { stdinBuf = prepared.stdin; } + return { finalCommand, stdinBuf }; + } + + async openShell( + serverId: string, + opts: { cols: number; rows: number; term?: string } = { cols: 80, rows: 24 }, + ): Promise { + const client = await this.acquireClient(serverId); + return new Promise((resolve, reject) => { + client.shell( + { + term: opts.term ?? 'xterm-256color', + cols: opts.cols, + rows: opts.rows, + }, + (err, channel) => { + if (err) reject(err); + else resolve(channel); + }, + ); + }); + } + + async openSftp(serverId: string): Promise { + const client = await this.acquireClient(serverId); + return new Promise((resolve, reject) => { + client.sftp((err, sftp) => { + if (err) reject(err); + else resolve(sftp); + }); + }); + } + + async execStream( + serverId: string, + command: string, + opts: ExecStreamOptions = {}, + ): Promise { + const client = await this.acquireClient(serverId); + const server = this.configManager.getServer(serverId); + if (!server) { + throw new Error(`Unknown server "${serverId}"`); + } + + const { finalCommand, stdinBuf } = this.prepareCommand(server, command, opts); + + return new Promise((resolve, reject) => { + const execOpts = opts.pty + ? { + pty: { + term: opts.pty.term ?? 'xterm-256color', + cols: opts.pty.cols, + rows: opts.pty.rows, + }, + } + : {}; + + client.exec(finalCommand, execOpts, (err, channel) => { + if (err) { + if (stdinBuf) stdinBuf.fill(0); + reject(err); + return; + } + + let exitCode: number | null = null; + let signal: string | undefined; + const done = new Promise<{ exitCode: number | null; signal?: string }>( + (resolveDone, rejectDone) => { + channel.on('exit', (code: number | null, sig?: string) => { + exitCode = typeof code === 'number' ? code : null; + signal = sig; + }); + channel.on('close', () => { + resolveDone({ exitCode, signal }); + }); + channel.on('error', (streamErr: Error) => { + rejectDone(streamErr); + }); + }, + ); + + if (stdinBuf && stdinBuf.length > 0) { + channel.stdin.write(stdinBuf); + stdinBuf.fill(0); + } + if (!opts.pty) { + channel.stdin.end(); + } + + const abort = () => { + try { + channel.signal?.('TERM'); + } catch { + // Ignore signal errors on unsupported servers + } + try { + channel.close(); + channel.destroy(); + } catch { + // Ignore close errors + } + }; + + resolve({ channel, done, abort }); + }); + }); + } + + async exec( + serverId: string, + command: string, + opts: ExecOptions = {}, + ): Promise { + const client = await this.acquireClient(serverId); + const server = this.configManager.getServer(serverId); + if (!server) { + throw new Error(`Unknown server "${serverId}"`); + } + + const { finalCommand, stdinBuf } = this.prepareCommand(server, command, opts); + const timeoutMs = opts.timeoutMs ?? DEFAULT_EXEC_TIMEOUT_MS; const maxBytes = opts.maxBytes ?? DEFAULT_MAX_BYTES; const started = Date.now(); diff --git a/src/shared/diff.ts b/src/shared/diff.ts new file mode 100644 index 0000000..d1b8e3e --- /dev/null +++ b/src/shared/diff.ts @@ -0,0 +1,97 @@ +export interface DiffLine { + type: 'equal' | 'add' | 'del'; + oldLine?: number; + newLine?: number; + text: string; +} + +export interface DiffResult { + lines: DiffLine[]; + unified: string; + additions: number; + deletions: number; +} + +export function computeLineDiff( + oldText: string, + newText: string, + oldLabel = 'revision', + newLabel = 'current', +): DiffResult { + const a = oldText.replace(/\r\n/g, '\n').split('\n'); + const b = newText.replace(/\r\n/g, '\n').split('\n'); + const m = a.length; + const n = b.length; + + let lines: DiffLine[]; + + // DP LCS works cleanly for config and remote text files up to a few thousand lines + if (m * n <= 2_500_000) { + const dp = new Int32Array((m + 1) * (n + 1)); + const stride = n + 1; + + for (let i = m - 1; i >= 0; i--) { + for (let j = n - 1; j >= 0; j--) { + if (a[i] === b[j]) { + dp[i * stride + j] = dp[(i + 1) * stride + (j + 1)]! + 1; + } else { + const down = dp[(i + 1) * stride + j]!; + const right = dp[i * stride + (j + 1)]!; + dp[i * stride + j] = down >= right ? down : right; + } + } + } + + lines = []; + let i = 0; + let j = 0; + while (i < m && j < n) { + if (a[i] === b[j]) { + lines.push({ type: 'equal', oldLine: i + 1, newLine: j + 1, text: a[i]! }); + i++; + j++; + } else if (dp[(i + 1) * stride + j]! >= dp[i * stride + (j + 1)]!) { + lines.push({ type: 'del', oldLine: i + 1, text: a[i]! }); + i++; + } else { + lines.push({ type: 'add', newLine: j + 1, text: b[j]! }); + j++; + } + } + while (i < m) { + lines.push({ type: 'del', oldLine: i + 1, text: a[i]! }); + i++; + } + while (j < n) { + lines.push({ type: 'add', newLine: j + 1, text: b[j]! }); + j++; + } + } else { + lines = [ + ...a.map((text, idx) => ({ type: 'del' as const, oldLine: idx + 1, text })), + ...b.map((text, idx) => ({ type: 'add' as const, newLine: idx + 1, text })), + ]; + } + + let additions = 0; + let deletions = 0; + const body: string[] = [`--- ${oldLabel}`, `+++ ${newLabel}`]; + for (const line of lines) { + if (line.type === 'add') { + additions++; + body.push(`+${line.text}`); + } else if (line.type === 'del') { + deletions++; + body.push(`-${line.text}`); + } else { + body.push(` ${line.text}`); + } + } + + return { + lines, + unified: body.join('\n'), + additions, + deletions, + }; +}