From b4bc6756b8f8aae32e2a8153def808d76d47a230 Mon Sep 17 00:00:00 2001 From: Taki Date: Wed, 18 Nov 2026 08:28:06 +0700 Subject: [PATCH 1/4] feat(sidecar): implement standalone http server with dynamic port and rest api --- package.json | 3 +- src/antigravity/sidecar-server.ts | 713 ++++++++++++++++++++++++++++++ 2 files changed, 715 insertions(+), 1 deletion(-) create mode 100644 src/antigravity/sidecar-server.ts diff --git a/package.json b/package.json index f3eeaa1..1ab1bbb 100644 --- a/package.json +++ b/package.json @@ -98,7 +98,8 @@ ] }, "scripts": { - "build": "esbuild src/vscode/extension.ts --bundle --platform=node --format=cjs --external:vscode --outfile=dist/extension.js && esbuild src/core/xhtml.ts --bundle --platform=node --format=cjs --outfile=dist/xhtml.js && esbuild src/core/epub.ts --bundle --platform=node --format=cjs --external:vscode --outfile=dist/epub.js && esbuild src/core/state-manager.ts --bundle --platform=node --format=cjs --outfile=dist/state-manager.js && esbuild src/core/archive.ts --bundle --platform=node --format=cjs --outfile=dist/archive.js", + "build": "esbuild src/vscode/extension.ts --bundle --platform=node --format=cjs --external:vscode --outfile=dist/extension.js && esbuild src/core/xhtml.ts --bundle --platform=node --format=cjs --outfile=dist/xhtml.js && esbuild src/core/epub.ts --bundle --platform=node --format=cjs --external:vscode --outfile=dist/epub.js && esbuild src/core/state-manager.ts --bundle --platform=node --format=cjs --outfile=dist/state-manager.js && esbuild src/core/archive.ts --bundle --platform=node --format=cjs --outfile=dist/archive.js && npm run build:sidecar", + "build:sidecar": "esbuild src/antigravity/sidecar-server.ts --bundle --platform=node --format=cjs --outfile=dist/sidecar-server.cjs", "check": "tsc --noEmit", "check:core": "tsc -p tsconfig.core.json --noEmit", "test": "npm run build && node --test test/*.test.mjs", diff --git a/src/antigravity/sidecar-server.ts b/src/antigravity/sidecar-server.ts new file mode 100644 index 0000000..1d02520 --- /dev/null +++ b/src/antigravity/sidecar-server.ts @@ -0,0 +1,713 @@ +import * as http from 'node:http'; +import * as fs from 'node:fs'; +import * as fsp from 'node:fs/promises'; +import * as path from 'node:path'; +import * as os from 'node:os'; +import { sanitizeXhtml, extractElementById } from '../core/xhtml'; +import { readerShell, ReaderNavInfo, ReaderSpineNavInfo, ReaderTocItem } from '../core/reader-shell'; +import { + parseContainerXml, + parseOpfXml, + loadEpubToc, + locateEpubContainer, + parentUri, + createResourceUri, + EpubPackage, + ResourceUri +} from '../core/epub'; +import { + StateManager, + JsonFileStorageAdapter, + InMemoryStorageAdapter, + ReadingLocation, + NavigationHistory +} from '../core/state-manager'; +import { EpubCacheManager } from '../core/archive'; + +export interface SidecarServerOptions { + port?: number; + host?: string; + storageDir?: string; + cacheDir?: string; +} + +export interface LoadedBookState { + filePath: string; + fileName: string; + isEpub: boolean; + title: string; + cacheDir?: string; + bookRootDir: string; + epubPackage?: EpubPackage; + currentSpineIndex: number; + currentChapterPath: string; + currentFragment?: string; +} + +const MIME_TYPES: Record = { + '.html': 'text/html; charset=utf-8', + '.xhtml': 'application/xhtml+xml; charset=utf-8', + '.css': 'text/css; charset=utf-8', + '.js': 'application/javascript; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.png': 'image/png', + '.jpg': 'image/jpeg', + '.jpeg': 'image/jpeg', + '.gif': 'image/gif', + '.svg': 'image/svg+xml', + '.webp': 'image/webp', + '.woff': 'font/woff', + '.woff2': 'font/woff2', + '.ttf': 'font/ttf', + '.otf': 'font/otf' +}; + +const resourceAttributes = /(<(?:img|source|video|audio|link)\b[^>]*?\b(?:src|href)\s*=\s*)(["'])([^"']+)\2/gi; + +export class SidecarServer { + private server: http.Server | undefined; + private sseClients = new Set(); + private cacheManager: EpubCacheManager; + private stateManager: StateManager; + private navigationHistory = new NavigationHistory(); + private loadedBook: LoadedBookState | undefined; + private lastFootnoteResponse: { requestId: string; html?: string; error?: string } | undefined; + + public readonly port: number; + public readonly host: string; + + constructor(options: SidecarServerOptions = {}) { + const envPort = process.env.ANTIGRAVITY_SIDECAR_WEB_PORT; + this.port = options.port ?? (envPort ? parseInt(envPort, 10) : 5890); + this.host = options.host ?? '127.0.0.1'; + + const cacheBase = options.cacheDir ?? path.join(os.tmpdir(), 'xhtml-reader-sidecar'); + this.cacheManager = new EpubCacheManager(cacheBase); + + const storagePath = options.storageDir + ? path.join(options.storageDir, 'state.json') + : path.join(os.homedir(), '.xhtml-reader', 'sidecar-state.json'); + + try { + this.stateManager = new StateManager(new JsonFileStorageAdapter(storagePath)); + } catch { + this.stateManager = new StateManager(new InMemoryStorageAdapter()); + } + } + + public getLoadedBook(): LoadedBookState | undefined { + return this.loadedBook; + } + + public async start(): Promise { + return new Promise((resolve, reject) => { + this.server = http.createServer((req, res) => { + void this.handleRequest(req, res); + }); + + this.server.on('error', (err) => { + reject(err); + }); + + this.server.listen(this.port, this.host, () => { + const url = `http://${this.host}:${this.port}`; + resolve(url); + }); + }); + } + + public async stop(): Promise { + // Notify and close SSE clients + for (const client of this.sseClients) { + try { + client.end(); + } catch { + // ignore + } + } + this.sseClients.clear(); + + // Clean up temporary extracted archives + try { + this.cacheManager.cleanupAll(); + } catch { + // ignore + } + + if (this.server) { + await new Promise((resolve) => { + this.server?.close(() => resolve()); + }); + this.server = undefined; + } + } + + private isSafePath(baseDir: string, targetPath: string): boolean { + const resolvedBase = path.resolve(baseDir); + const resolvedTarget = path.resolve(targetPath); + return resolvedTarget.startsWith(resolvedBase + path.sep) || resolvedTarget === resolvedBase; + } + + private broadcastEvent(eventType: string, data: unknown): void { + const payload = `event: ${eventType}\ndata: ${JSON.stringify(data)}\n\n`; + for (const client of this.sseClients) { + try { + client.write(payload); + } catch { + this.sseClients.delete(client); + } + } + } + + public async openBook(filePath: string, spineIndex = 0, targetId?: string): Promise { + const absolutePath = path.resolve(filePath); + await fsp.access(absolutePath, fs.constants.R_OK); + + const ext = path.extname(absolutePath).toLowerCase(); + const fileName = path.basename(absolutePath); + const stat = await fsp.stat(absolutePath); + let containerRootPath: string | undefined; + + if (ext === '.epub') { + const buffer = await fsp.readFile(absolutePath); + containerRootPath = this.cacheManager.extractEpubToCache(absolutePath, buffer); + } else if (stat.isDirectory()) { + const containerFile = path.join(absolutePath, 'META-INF', 'container.xml'); + try { + await fsp.access(containerFile, fs.constants.R_OK); + containerRootPath = absolutePath; + } catch { + // Not a container + } + } else { + const foundContainer = await locateEpubContainer(createResourceUri(absolutePath)); + if (foundContainer) { + containerRootPath = foundContainer.fsPath || foundContainer.path; + } + } + + if (containerRootPath) { + const containerUri = createResourceUri(path.join(containerRootPath, 'META-INF', 'container.xml')); + const containerXml = await fsp.readFile(containerUri.fsPath!, 'utf-8'); + const opfRelPath = parseContainerXml(containerXml); + + if (!opfRelPath) { + throw new Error('Invalid EPUB: META-INF/container.xml has no valid rootfile full-path'); + } + + const opfPath = path.join(containerRootPath, ...opfRelPath.split('/').filter(Boolean)); + const opfUri = createResourceUri(opfPath); + const containerRootUri = createResourceUri(containerRootPath); + const opfXml = await fsp.readFile(opfPath, 'utf-8'); + const epubPackage = parseOpfXml(opfXml, opfUri, containerRootUri); + + epubPackage.toc = await loadEpubToc(epubPackage, async (uri) => { + return fsp.readFile(uri.fsPath || uri.path, 'utf-8'); + }); + + // Find spine index if opening a specific chapter file + let safeSpineIndex = Math.max(0, Math.min(spineIndex, epubPackage.spine.length - 1)); + if (!stat.isDirectory() && ext !== '.epub') { + const foundIdx = epubPackage.spine.findIndex( + (item) => path.resolve(item.uri.fsPath || item.uri.path) === absolutePath + ); + if (foundIdx >= 0) { + safeSpineIndex = foundIdx; + } + } + + const initialChapter = epubPackage.spine[safeSpineIndex]; + const currentChapterPath = initialChapter ? (initialChapter.uri.fsPath || initialChapter.uri.path) : ''; + + this.loadedBook = { + filePath: absolutePath, + fileName, + isEpub: true, + title: epubPackage.title, + cacheDir: ext === '.epub' ? containerRootPath : undefined, + bookRootDir: containerRootPath, + epubPackage, + currentSpineIndex: safeSpineIndex, + currentChapterPath, + currentFragment: targetId + }; + } else { + // Standalone XHTML / HTML file + const bookRootDir = path.dirname(absolutePath); + this.loadedBook = { + filePath: absolutePath, + fileName, + isEpub: false, + title: fileName, + bookRootDir, + currentSpineIndex: 0, + currentChapterPath: absolutePath, + currentFragment: targetId + }; + } + + this.broadcastEvent('bookLoaded', { + title: this.loadedBook.title, + fileName: this.loadedBook.fileName, + currentSpineIndex: this.loadedBook.currentSpineIndex, + isEpub: this.loadedBook.isEpub + }); + + return this.loadedBook; + } + + private async rewriteAssets(markup: string, chapterDir: string, bookRootDir: string): Promise { + const resources = new Map(); + const matches = [...markup.matchAll(resourceAttributes)]; + + for (const match of matches) { + const raw = match[3]; + if (resources.has(raw)) continue; + + const cleanPath = raw.split(/[?#]/, 1)[0]; + if (!cleanPath || /^(?:[a-z][a-z0-9+.-]*:|\/\/|#)/i.test(cleanPath)) { + continue; + } + + const decoded = decodeURIComponent(cleanPath); + const candidatePath = path.resolve(chapterDir, decoded); + + if (this.isSafePath(bookRootDir, candidatePath)) { + try { + await fsp.access(candidatePath, fs.constants.R_OK); + const relToRoot = path.relative(bookRootDir, candidatePath).replace(/\\/g, '/'); + resources.set(raw, `/assets/${relToRoot}`); + } catch { + // ignore missing asset + } + } + } + + return markup.replace(resourceAttributes, (full, prefix: string, quote: string, raw: string) => { + const replacement = resources.get(raw); + return replacement ? `${prefix}${quote}${replacement}${quote}` : full; + }); + } + + private async handleRequest(req: http.IncomingMessage, res: http.ServerResponse): Promise { + // Add CORS headers for local host interactions + res.setHeader('Access-Control-Allow-Origin', '*'); + res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); + res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); + + if (req.method === 'OPTIONS') { + res.writeHead(204); + res.end(); + return; + } + + const parsedUrl = new URL(req.url || '/', `http://${this.host}:${this.port}`); + const pathname = parsedUrl.pathname; + + // 1. Root: Serves Reader Shell UI + if (pathname === '/' && req.method === 'GET') { + await this.serveReaderUi(req, res); + return; + } + + // 2. Status API + if (pathname === '/api/status' && req.method === 'GET') { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end( + JSON.stringify({ + status: 'ok', + loaded: Boolean(this.loadedBook), + port: this.port, + book: this.loadedBook + ? { + filePath: this.loadedBook.filePath, + title: this.loadedBook.title, + fileName: this.loadedBook.fileName, + isEpub: this.loadedBook.isEpub, + currentSpineIndex: this.loadedBook.currentSpineIndex, + totalChapters: this.loadedBook.epubPackage?.spine.length ?? 1, + currentChapterPath: this.loadedBook.currentChapterPath, + currentFragment: this.loadedBook.currentFragment + } + : null + }) + ); + return; + } + + // 3. Open Book API + if (pathname === '/api/open' && req.method === 'POST') { + await this.handleOpenApi(req, res); + return; + } + + // 4. Server-Sent Events (SSE) Stream + if (pathname === '/api/events' && req.method === 'GET') { + this.handleSseStream(req, res); + return; + } + + // 5. Message Dispatch API (from client reader-shell) + if (pathname === '/api/message' && req.method === 'POST') { + await this.handleMessageApi(req, res); + return; + } + + // 6. Static Asset Serving: /assets/* + const rawUrl = req.url || '/'; + if ((rawUrl.startsWith('/assets') || pathname.startsWith('/assets')) && req.method === 'GET') { + if (rawUrl.includes('..') || pathname.includes('..') || rawUrl.toLowerCase().includes('%2e%2e')) { + res.writeHead(403, { 'Content-Type': 'text/plain' }); + res.end('Forbidden: Path traversal detected'); + return; + } + const assetRelPath = rawUrl.replace(/^\/assets\/?/, '').split('?')[0]; + await this.serveAsset(assetRelPath, res); + return; + } + + res.writeHead(404, { 'Content-Type': 'text/plain' }); + res.end('Not Found'); + } + + private handleSseStream(_req: http.IncomingMessage, res: http.ServerResponse): void { + res.writeHead(200, { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + Connection: 'keep-alive' + }); + + res.write(': connected\n\n'); + this.sseClients.add(res); + + _req.on('close', () => { + this.sseClients.delete(res); + }); + } + + private async handleOpenApi(req: http.IncomingMessage, res: http.ServerResponse): Promise { + try { + const body = await this.readRequestBody(req); + const parsed = JSON.parse(body || '{}'); + + if (!parsed.filePath || typeof parsed.filePath !== 'string') { + res.writeHead(400, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'Missing or invalid "filePath" property' })); + return; + } + + const book = await this.openBook(parsed.filePath, parsed.spineIndex, parsed.targetId); + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end( + JSON.stringify({ + success: true, + title: book.title, + isEpub: book.isEpub, + totalChapters: book.epubPackage?.spine.length ?? 1 + }) + ); + } catch (err) { + console.error('[Sidecar] openBook error:', err); + res.writeHead(500, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: String(err) })); + } + } + + private async handleMessageApi(req: http.IncomingMessage, res: http.ServerResponse): Promise { + try { + const body = await this.readRequestBody(req); + const msg = JSON.parse(body || '{}'); + + if (!this.loadedBook) { + res.writeHead(400, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'No book loaded' })); + return; + } + + if (msg.type === 'prevChapter') { + if (this.loadedBook.isEpub && this.loadedBook.epubPackage && this.loadedBook.currentSpineIndex > 0) { + this.loadedBook.currentSpineIndex -= 1; + const chapter = this.loadedBook.epubPackage.spine[this.loadedBook.currentSpineIndex]; + this.loadedBook.currentChapterPath = chapter.uri.fsPath || chapter.uri.path; + this.loadedBook.currentFragment = undefined; + this.broadcastEvent('chapterChanged', { + spineIndex: this.loadedBook.currentSpineIndex, + chapterPath: this.loadedBook.currentChapterPath + }); + } + } else if (msg.type === 'nextChapter') { + if ( + this.loadedBook.isEpub && + this.loadedBook.epubPackage && + this.loadedBook.currentSpineIndex < this.loadedBook.epubPackage.spine.length - 1 + ) { + this.loadedBook.currentSpineIndex += 1; + const chapter = this.loadedBook.epubPackage.spine[this.loadedBook.currentSpineIndex]; + this.loadedBook.currentChapterPath = chapter.uri.fsPath || chapter.uri.path; + this.loadedBook.currentFragment = undefined; + this.broadcastEvent('chapterChanged', { + spineIndex: this.loadedBook.currentSpineIndex, + chapterPath: this.loadedBook.currentChapterPath + }); + } + } else if (msg.type === 'savePreferences') { + if (msg.preferences) { + await this.stateManager.savePreferences(msg.preferences); + } + } else if (msg.type === 'saveReadingPosition') { + await this.stateManager.saveReadingLocation(this.loadedBook.currentChapterPath, { + scrollRatio: msg.scrollRatio, + scrollY: msg.scrollY, + anchorId: msg.anchorId + }); + } else if (msg.type === 'requestFootnote') { + await this.handleFootnoteRequest(msg); + } + + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ received: true, lastFootnote: this.lastFootnoteResponse })); + } catch (err) { + console.error('[Sidecar] openBook error:', err); + res.writeHead(500, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: String(err) })); + } + } + + private async handleFootnoteRequest(msg: { href: string; requestId: string }): Promise { + if (!this.loadedBook) return; + + try { + const parts = msg.href.split('#'); + const filePart = parts[0]; + const fragment = parts[1]; + + if (!fragment) { + this.lastFootnoteResponse = { requestId: msg.requestId, error: 'Missing fragment' }; + return; + } + + let targetPath = this.loadedBook.currentChapterPath; + if (filePart) { + const decoded = decodeURIComponent(filePart); + targetPath = path.resolve(path.dirname(this.loadedBook.currentChapterPath), decoded); + } + + if (!this.isSafePath(this.loadedBook.bookRootDir, targetPath)) { + this.lastFootnoteResponse = { requestId: msg.requestId, error: 'Path traversal blocked' }; + return; + } + + const raw = await fsp.readFile(targetPath, 'utf-8'); + const extracted = extractElementById(raw, fragment); + + if (!extracted) { + this.lastFootnoteResponse = { requestId: msg.requestId, error: 'Footnote element not found' }; + return; + } + + const rewritten = await this.rewriteAssets(extracted, path.dirname(targetPath), this.loadedBook.bookRootDir); + this.lastFootnoteResponse = { requestId: msg.requestId, html: rewritten }; + } catch (err) { + this.lastFootnoteResponse = { requestId: msg.requestId, error: String(err) }; + } + } + + private async serveAsset(assetRelPath: string, res: http.ServerResponse): Promise { + if (!this.loadedBook) { + res.writeHead(404, { 'Content-Type': 'text/plain' }); + res.end('No book loaded'); + return; + } + + const decoded = decodeURIComponent(assetRelPath); + const fullPath = path.resolve(this.loadedBook.bookRootDir, decoded); + + // Strict Path Traversal Guard + if (!this.isSafePath(this.loadedBook.bookRootDir, fullPath)) { + res.writeHead(403, { 'Content-Type': 'text/plain' }); + res.end('Forbidden: Access outside book directory is blocked'); + return; + } + + try { + const stat = await fsp.stat(fullPath); + if (!stat.isFile()) { + res.writeHead(404, { 'Content-Type': 'text/plain' }); + res.end('Not Found'); + return; + } + + const ext = path.extname(fullPath).toLowerCase(); + const contentType = MIME_TYPES[ext] || 'application/octet-stream'; + + res.writeHead(200, { + 'Content-Type': contentType, + 'Content-Length': stat.size, + 'Cache-Control': 'public, max-age=3600' + }); + + fs.createReadStream(fullPath).pipe(res); + } catch { + res.writeHead(404, { 'Content-Type': 'text/plain' }); + res.end('Asset Not Found'); + } + } + + private async serveReaderUi(_req: http.IncomingMessage, res: http.ServerResponse): Promise { + const preferences = this.stateManager.getPreferences(); + + if (!this.loadedBook) { + // Empty state + const emptyHtml = ` + + + + XHTML Reader Previewer + + + + +
+
📖
+

XHTML & EPUB Reader

+

Belum ada buku atau berkas XHTML yang dimuat ke dalam Auxiliary Pane.

+
Gunakan perintah Agent atau panggil /api/open
+
+ +`; + res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); + res.end(emptyHtml); + return; + } + + try { + const chapterContentRaw = await fsp.readFile(this.loadedBook.currentChapterPath, 'utf-8'); + const sanitized = sanitizeXhtml(chapterContentRaw); + const chapterDir = path.dirname(this.loadedBook.currentChapterPath); + const rewrittenContent = await this.rewriteAssets(sanitized, chapterDir, this.loadedBook.bookRootDir); + + const tocItems: ReaderTocItem[] | undefined = this.loadedBook.epubPackage?.toc.map((t) => ({ + label: t.label, + href: t.href, + active: t.href.includes(path.basename(this.loadedBook!.currentChapterPath)) + })); + + const navInfo: ReaderNavInfo = { + hasPrev: this.loadedBook.isEpub ? this.loadedBook.currentSpineIndex > 0 : false, + hasNext: this.loadedBook.isEpub + ? this.loadedBook.currentSpineIndex < (this.loadedBook.epubPackage?.spine.length ?? 1) - 1 + : false, + bookTitle: this.loadedBook.title, + chapterIndex: this.loadedBook.currentSpineIndex + 1, + totalChapters: this.loadedBook.epubPackage?.spine.length ?? 1, + currentFileName: path.basename(this.loadedBook.currentChapterPath), + isLinear: true, + toc: tocItems + }; + + if (this.loadedBook.epubPackage) { + navInfo.spineItems = this.loadedBook.epubPackage.spine.map((sp, idx) => ({ + index: idx + 1, + idref: sp.idref, + href: sp.href, + fileName: path.basename(sp.href), + linear: sp.linear !== false, + active: idx === this.loadedBook!.currentSpineIndex + })); + } + + const initialLocation = this.stateManager.getReadingLocation(this.loadedBook.currentChapterPath); + + // Inject SSE live listener directly into HTML reader shell + let html = readerShell( + rewrittenContent, + this.loadedBook.currentChapterPath, + this.loadedBook.currentFragment, + { cspSource: `http://${this.host}:*` }, + navInfo, + preferences, + initialLocation, + false, + false + ); + + // Inject client SSE hot-reload script before + const sseScript = ` + +`; + html = html.replace('', sseScript); + + res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); + res.end(html); + } catch (err) { + res.writeHead(500, { 'Content-Type': 'text/plain' }); + res.end(`Error rendering reader UI: ${String(err)}`); + } + } + + private readRequestBody(req: http.IncomingMessage): Promise { + return new Promise((resolve, reject) => { + let body = ''; + req.on('data', (chunk) => { + body += chunk; + if (body.length > 5 * 1024 * 1024) { + reject(new Error('Request body too large')); + } + }); + req.on('end', () => resolve(body)); + req.on('error', (err) => reject(err)); + }); + } +} + +// CLI Launcher entry point +if (require.main === module) { + const server = new SidecarServer(); + server + .start() + .then((url) => { + console.log(`[XHTML Sidecar] Server listening at ${url}`); + console.log(`[XHTML Sidecar] Auxiliary Pane Ready (PID: ${process.pid})`); + + const shutdown = async () => { + console.log('[XHTML Sidecar] Shutting down...'); + await server.stop(); + process.exit(0); + }; + + process.on('SIGINT', () => void shutdown()); + process.on('SIGTERM', () => void shutdown()); + }) + .catch((err) => { + console.error('[XHTML Sidecar] Failed to start:', err); + process.exit(1); + }); +} From 04ba885f9c40330aff9a16fda7bca123aa3bc901 Mon Sep 17 00:00:00 2001 From: Taki Date: Wed, 18 Nov 2026 08:28:10 +0700 Subject: [PATCH 2/4] feat(shell): add responsive auxiliary pane layout and sse hot-reload client --- src/core/reader-shell.ts | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/src/core/reader-shell.ts b/src/core/reader-shell.ts index b05e4fc..effff93 100644 --- a/src/core/reader-shell.ts +++ b/src/core/reader-shell.ts @@ -1372,6 +1372,27 @@ export function readerShell( color: #991b1b; border-color: #f8b4b4; } + + @media (max-width: 520px) { + #toolbar { + padding: 0.35rem 0.5rem; + } + .toolbar-center { + position: static; + transform: none; + max-width: 140px; + } + .chapter-title-text, .chapter-badge-file { + max-width: 90px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + .settings-popover { + right: 0.25rem; + width: min(19rem, calc(100vw - 0.5rem)); + } + } @@ -1526,6 +1547,17 @@ export function readerShell( } } }; + + // Live Server-Sent Events (SSE) listener for Antigravity Sidecar + if (typeof EventSource === 'function' && typeof acquireVsCodeApi !== 'function') { + try { + const sse = new EventSource('/api/events'); + sse.addEventListener('chapterChanged', function() { location.reload(); }); + sse.addEventListener('bookLoaded', function() { location.reload(); }); + } catch (err) { + // Standalone or offline mode + } + } const popover = document.getElementById('footnote-popover'); const caret = document.getElementById('footnote-caret'); const noteContent = document.getElementById('footnote-content'); From 784ff3497143c32dac97ad9996b647106696d0f1 Mon Sep 17 00:00:00 2001 From: Taki Date: Wed, 18 Nov 2026 08:28:15 +0700 Subject: [PATCH 3/4] test(sidecar): add comprehensive integration test suite for sidecar server lifecycle --- test/sidecar-server.test.mjs | 128 +++++++++++++++++++++++++++++++++++ 1 file changed, 128 insertions(+) create mode 100644 test/sidecar-server.test.mjs diff --git a/test/sidecar-server.test.mjs b/test/sidecar-server.test.mjs new file mode 100644 index 0000000..f7e574b --- /dev/null +++ b/test/sidecar-server.test.mjs @@ -0,0 +1,128 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import path from 'node:path'; +import os from 'node:os'; +import { SidecarServer } from '../dist/sidecar-server.cjs'; + +test('SidecarServer lifecycle and REST API test suite', async (t) => { + const tempCacheDir = path.join(os.tmpdir(), `test-sidecar-cache-${Date.now()}`); + const tempStorageDir = path.join(os.tmpdir(), `test-sidecar-storage-${Date.now()}`); + const server = new SidecarServer({ + port: 5892, + host: '127.0.0.1', + cacheDir: tempCacheDir, + storageDir: tempStorageDir + }); + + let serverUrl = ''; + + await t.test('1. Start server successfully', async () => { + serverUrl = await server.start(); + assert.match(serverUrl, /http:\/\/127\.0\.0\.1:5892/); + }); + + await t.test('2. GET / returns initial empty state HTML', async () => { + const res = await fetch(`${serverUrl}/`); + assert.equal(res.status, 200); + const html = await res.text(); + assert.match(html, /XHTML & EPUB Reader/); + assert.match(html, /Belum ada buku atau berkas XHTML yang dimuat/); + }); + + await t.test('3. GET /api/status returns not loaded initially', async () => { + const res = await fetch(`${serverUrl}/api/status`); + assert.equal(res.status, 200); + const json = await res.json(); + assert.equal(json.status, 'ok'); + assert.equal(json.loaded, false); + assert.equal(json.book, null); + }); + + await t.test('4. POST /api/open opens sample-book/OEBPS/ch_1.xhtml', async () => { + const epubPath = path.resolve('sample-book/OEBPS/ch_1.xhtml'); + const res = await fetch(`${serverUrl}/api/open`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ filePath: epubPath }) + }); + assert.equal(res.status, 200); + const json = await res.json(); + assert.equal(json.success, true); + assert.equal(json.isEpub, true); + assert.match(json.title, /Sample EPUB/i); + assert.ok(json.totalChapters > 0); + }); + + await t.test('5. GET /api/status returns loaded book details', async () => { + const res = await fetch(`${serverUrl}/api/status`); + assert.equal(res.status, 200); + const json = await res.json(); + assert.equal(json.status, 'ok'); + assert.equal(json.loaded, true); + assert.ok(json.book); + assert.match(json.book.title, /Sample EPUB/i); + assert.equal(json.book.currentSpineIndex, 0); + }); + + await t.test('6. GET / renders active reader shell with book content', async () => { + const res = await fetch(`${serverUrl}/`); + assert.equal(res.status, 200); + const html = await res.text(); + assert.match(html, /id=["']toolbar["']/); + assert.match(html, /id=["']content["']/); + assert.match(html, /Sample EPUB/i); + }); + + await t.test('7. Path Traversal Guard blocks outside file access', async () => { + const http = await import('node:http'); + const statusCode = await new Promise((resolve, reject) => { + const req = http.get( + { + host: '127.0.0.1', + port: 5892, + path: '/assets/../../package.json' + }, + (res) => { + resolve(res.statusCode); + } + ); + req.on('error', reject); + }); + assert.equal(statusCode, 403); + }); + + await t.test('8. POST /api/message handles nextChapter navigation', async () => { + const res = await fetch(`${serverUrl}/api/message`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ type: 'nextChapter' }) + }); + assert.equal(res.status, 200); + const json = await res.json(); + assert.equal(json.received, true); + + const statusRes = await fetch(`${serverUrl}/api/status`); + const statusJson = await statusRes.json(); + assert.equal(statusJson.book.currentSpineIndex, 1); + }); + + await t.test('9. POST /api/message saves preferences', async () => { + const res = await fetch(`${serverUrl}/api/message`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + type: 'savePreferences', + preferences: { theme: 'sepia', fontSize: 22 } + }) + }); + assert.equal(res.status, 200); + }); + + await t.test('10. Stop server cleans up smoothly', async () => { + await server.stop(); + // Verify server is closed + await assert.rejects(async () => { + await fetch(`${serverUrl}/api/status`); + }); + }); +}); From d93690d5fa5e4ac67b079f679eef918c4ead125f Mon Sep 17 00:00:00 2001 From: Taki Date: Wed, 18 Nov 2026 08:44:05 +0700 Subject: [PATCH 4/4] fix(sidecar): resolve csp connect-src, footnote response dispatch, and inter-chapter transition --- src/antigravity/sidecar-server.ts | 74 +++++++++++++++++++++++-------- src/core/reader-shell.ts | 26 ++++++++++- test/sidecar-server.test.mjs | 39 +++++++++++++++- 3 files changed, 119 insertions(+), 20 deletions(-) diff --git a/src/antigravity/sidecar-server.ts b/src/antigravity/sidecar-server.ts index 1d02520..b638464 100644 --- a/src/antigravity/sidecar-server.ts +++ b/src/antigravity/sidecar-server.ts @@ -42,6 +42,8 @@ export interface LoadedBookState { currentSpineIndex: number; currentChapterPath: string; currentFragment?: string; + resetToTop?: boolean; + startAtBottom?: boolean; } const MIME_TYPES: Record = { @@ -424,12 +426,17 @@ export class SidecarServer { return; } + let chapterChanged = false; + if (msg.type === 'prevChapter') { if (this.loadedBook.isEpub && this.loadedBook.epubPackage && this.loadedBook.currentSpineIndex > 0) { this.loadedBook.currentSpineIndex -= 1; const chapter = this.loadedBook.epubPackage.spine[this.loadedBook.currentSpineIndex]; this.loadedBook.currentChapterPath = chapter.uri.fsPath || chapter.uri.path; this.loadedBook.currentFragment = undefined; + this.loadedBook.startAtBottom = Boolean(msg.startAtBottom); + this.loadedBook.resetToTop = !msg.startAtBottom; + chapterChanged = true; this.broadcastEvent('chapterChanged', { spineIndex: this.loadedBook.currentSpineIndex, chapterPath: this.loadedBook.currentChapterPath @@ -445,11 +452,50 @@ export class SidecarServer { const chapter = this.loadedBook.epubPackage.spine[this.loadedBook.currentSpineIndex]; this.loadedBook.currentChapterPath = chapter.uri.fsPath || chapter.uri.path; this.loadedBook.currentFragment = undefined; + this.loadedBook.resetToTop = true; + this.loadedBook.startAtBottom = false; + chapterChanged = true; this.broadcastEvent('chapterChanged', { spineIndex: this.loadedBook.currentSpineIndex, chapterPath: this.loadedBook.currentChapterPath }); } + } else if (msg.type === 'openLink' && msg.href) { + if (msg.currentPosition) { + await this.stateManager.saveReadingLocation(this.loadedBook.currentChapterPath, { + scrollRatio: msg.currentPosition.scrollRatio, + scrollY: msg.currentPosition.scrollY, + anchorId: msg.currentPosition.anchorId + }); + } + + const [filePart, fragment] = msg.href.split('#'); + let targetPath = this.loadedBook.currentChapterPath; + if (filePart) { + const decoded = decodeURIComponent(filePart); + targetPath = path.resolve(path.dirname(this.loadedBook.currentChapterPath), decoded); + } + + if (this.isSafePath(this.loadedBook.bookRootDir, targetPath)) { + if (this.loadedBook.isEpub && this.loadedBook.epubPackage) { + const foundIdx = this.loadedBook.epubPackage.spine.findIndex( + (item) => path.resolve(item.uri.fsPath || item.uri.path) === path.resolve(targetPath) + ); + if (foundIdx >= 0) { + this.loadedBook.currentSpineIndex = foundIdx; + } + } + this.loadedBook.currentChapterPath = targetPath; + this.loadedBook.currentFragment = fragment; + this.loadedBook.resetToTop = !fragment; + this.loadedBook.startAtBottom = false; + chapterChanged = true; + this.broadcastEvent('chapterChanged', { + spineIndex: this.loadedBook.currentSpineIndex, + chapterPath: this.loadedBook.currentChapterPath, + fragment: this.loadedBook.currentFragment + }); + } } else if (msg.type === 'savePreferences') { if (msg.preferences) { await this.stateManager.savePreferences(msg.preferences); @@ -465,9 +511,9 @@ export class SidecarServer { } res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ received: true, lastFootnote: this.lastFootnoteResponse })); + res.end(JSON.stringify({ received: true, chapterChanged, lastFootnote: this.lastFootnoteResponse })); } catch (err) { - console.error('[Sidecar] openBook error:', err); + console.error('[Sidecar] message error:', err); res.writeHead(500, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: String(err) })); } @@ -640,8 +686,12 @@ export class SidecarServer { const initialLocation = this.stateManager.getReadingLocation(this.loadedBook.currentChapterPath); - // Inject SSE live listener directly into HTML reader shell - let html = readerShell( + const resetToTop = Boolean(this.loadedBook.resetToTop); + const startAtBottom = Boolean(this.loadedBook.startAtBottom); + this.loadedBook.resetToTop = false; + this.loadedBook.startAtBottom = false; + + const html = readerShell( rewrittenContent, this.loadedBook.currentChapterPath, this.loadedBook.currentFragment, @@ -649,22 +699,10 @@ export class SidecarServer { navInfo, preferences, initialLocation, - false, - false + resetToTop, + startAtBottom ); - // Inject client SSE hot-reload script before - const sseScript = ` - -`; - html = html.replace('', sseScript); - res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); res.end(html); } catch (err) { diff --git a/src/core/reader-shell.ts b/src/core/reader-shell.ts index effff93..62c24eb 100644 --- a/src/core/reader-shell.ts +++ b/src/core/reader-shell.ts @@ -217,7 +217,7 @@ export function readerShell( - + ${title}