browser-debugger-cli
Version:
DevTools telemetry in your terminal. For humans and agents. Direct WebSocket to Chrome's debugging port.
243 lines • 7.95 kB
JavaScript
/**
* IPC Client
*
* Public API for communicating with the daemon via Unix socket.
* Provides high-level functions for session lifecycle and queries.
*/
import { sendRequest } from './transport/index.js';
import { withSession } from './utils/index.js';
/**
* Connect to the daemon and perform handshake.
* Verifies daemon is running and ready to accept commands.
*
* @returns Handshake response with connection status
* @throws Error if connection fails or times out
*
* @example
* ```typescript
* const response = await connectToDaemon();
* if (response.status === 'ok') {
* console.log('Connected:', response.message);
* }
* ```
*/
export async function connectToDaemon() {
const request = withSession({ type: 'handshake_request' });
return sendRequest(request, 'handshake', 'handshake_response');
}
/**
* Request status information from the daemon.
* Returns daemon state, session metadata, and activity metrics.
*
* @returns Status response with daemon and session information
* @throws Error if connection fails or times out
*
* @example
* ```typescript
* const response = await getStatus();
* if (response.status === 'ok' && response.data) {
* console.log('Daemon PID:', response.data.daemonPid);
* console.log('Session active:', !!response.data.sessionPid);
* }
* ```
*/
export async function getStatus() {
const request = withSession({ type: 'status_request' });
return sendRequest(request, 'status', 'status_response');
}
/**
* Request preview data from the daemon.
* Returns snapshot of collected telemetry without stopping session.
*
* @param options - Optional parameters for the peek request (lastN: number of items, 0 = all)
* @returns Peek response with preview data
* @throws Error if connection fails, times out, or no active session
*
* @example
* ```typescript
* const response = await getPeek();
* if (response.status === 'ok' && response.data) {
* console.log('Network requests:', response.data.preview.data.network?.length);
* console.log('Console messages:', response.data.preview.data.console?.length);
* }
* ```
*
* @example
* ```typescript
* // Get all messages (no limit)
* const response = await getPeek({ lastN: 0 });
* ```
*/
export async function getPeek(options) {
const request = withSession({
type: 'peek_request',
...(options?.lastN !== undefined && { lastN: options.lastN }),
});
return sendRequest(request, 'peek', 'peek_response');
}
/**
* Request network data for HAR export from the daemon.
* Returns all collected network requests without stopping session.
*
* @returns HAR data response with network requests
* @throws Error if connection fails, times out, or no active session
*
* @example
* ```typescript
* const response = await getHARData();
* if (response.status === 'ok' && response.data) {
* console.log('Total requests:', response.data.requests.length);
* }
* ```
*/
export async function getHARData() {
const request = withSession({ type: 'har_data_request' });
return sendRequest(request, 'HAR data', 'har_data_response');
}
/**
* Request daemon to start a new browser session.
* Launches Chrome, establishes CDP connection, and begins telemetry collection.
*
* @param url - Target URL to navigate to
* @param options - Session configuration options
* @returns Start session response with worker and Chrome PIDs
* @throws Error if connection fails, session already running, or Chrome launch fails
*
* @example
* ```typescript
* const response = await startSession('http://localhost:3000', {
* timeout: 30,
* headless: true,
* maxBodySize: 10
* });
* if (response.status === 'ok' && response.data) {
* console.log('Session started, worker PID:', response.data.workerPid);
* }
* ```
*/
export async function startSession(url, options) {
const request = withSession({
type: 'start_session_request',
url,
...(options && {
port: options.port,
timeout: options.timeout,
telemetry: options.telemetry,
includeAll: options.includeAll,
userDataDir: options.userDataDir,
maxBodySize: options.maxBodySize,
headless: options.headless,
chromeWsUrl: options.chromeWsUrl,
}),
});
return sendRequest(request, 'start session', 'start_session_response');
}
/**
* Request session stop from the daemon.
* Stops telemetry collection, closes Chrome, and writes output file.
*
* @returns Stop session response with termination status
* @throws Error if connection fails, times out, or no active session
*
* @example
* ```typescript
* const response = await stopSession();
* if (response.status === 'ok') {
* console.log('Session stopped:', response.message);
* }
* ```
*/
export async function stopSession() {
const request = withSession({ type: 'stop_session_request' });
return sendRequest(request, 'stop session', 'stop_session_response');
}
/**
* Send a command to the worker process.
* Internal helper for worker commands (details, CDP calls).
*
* @param commandName - Name of the command to send
* @param params - Command parameters (without type field)
* @returns Command response from worker
* @throws Error if connection fails or command execution fails
*/
async function sendCommand(commandName, params) {
const request = {
...params,
type: `${commandName}_request`,
sessionId: withSession({ type: '' }).sessionId,
};
return sendRequest(request, commandName, `${commandName}_response`);
}
/**
* Get details for a specific network request or console message.
* Retrieves full data (headers, body, stack trace) for a telemetry item.
*
* @param type - Type of item to retrieve ('network' or 'console')
* @param id - Unique identifier of the item
* @returns Response with full item details
* @throws Error if connection fails or item not found
*
* @example
* ```typescript
* const response = await getDetails('network', 'req-123');
* if (response.status === 'ok' && response.data) {
* console.log('Full request:', response.data.item);
* }
* ```
*/
export async function getDetails(type, id) {
return sendCommand('worker_details', { itemType: type, id });
}
/**
* Get headers for a network request.
* Defaults to main document navigation if no ID specified.
*
* @param options - Optional request ID and header name filter
* @returns Response with request and response headers
* @throws Error if connection fails or request not found
*
* @example
* ```typescript
* const response = await getNetworkHeaders();
* if (response.status === 'ok' && response.data) {
* console.log('Response headers:', response.data.responseHeaders);
* }
* ```
*
* @example
* ```typescript
* const response = await getNetworkHeaders({ id: 'ABC-123' });
* ```
*
* @example
* ```typescript
* const response = await getNetworkHeaders({ headerName: 'content-security-policy' });
* ```
*/
export async function getNetworkHeaders(options) {
return sendCommand('worker_network_headers', {
...(options?.id && { id: options.id }),
...(options?.headerName && { headerName: options.headerName }),
});
}
/**
* Execute arbitrary CDP method via the daemon's worker.
* Forwards CDP commands to the worker's active CDP connection.
*
* @param method - CDP method name (e.g., 'Network.getCookies')
* @param params - Optional method parameters
* @returns Response with CDP method result
* @throws Error if connection fails or CDP method fails
*
* @example
* ```typescript
* const response = await callCDP('Network.getCookies', {});
* if (response.status === 'ok' && response.data) {
* console.log('Cookies:', response.data.result);
* }
* ```
*/
export async function callCDP(method, params) {
return sendCommand('cdp_call', { method, ...(params && { params }) });
}
//# sourceMappingURL=client.js.map