chromancer
Version:
A powerful command-line interface for automating Chrome browser using Playwright. Perfect for web scraping, automation, testing, and browser workflows.
106 lines (105 loc) • 3.32 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SessionManager = void 0;
const tslib_1 = require("tslib");
const fs = tslib_1.__importStar(require("fs"));
const path = tslib_1.__importStar(require("path"));
const os = tslib_1.__importStar(require("os"));
class SessionManager {
static instance;
static sessionFile = path.join(os.tmpdir(), 'chromancer-session.json');
static activeProcess = null;
browserInstance = null;
contextInstance = null;
pageInstance = null;
static getInstance() {
if (!this.instance) {
this.instance = new SessionManager();
}
return this.instance;
}
setBrowserInstance(browser, context, page) {
this.browserInstance = browser;
this.contextInstance = context;
this.pageInstance = page;
}
getBrowserInstance() {
if (this.browserInstance) {
return {
browser: this.browserInstance,
context: this.contextInstance,
page: this.pageInstance
};
}
return null;
}
static setActiveProcess(process) {
this.activeProcess = process;
}
static getActiveProcess() {
return this.activeProcess;
}
static saveSession(session) {
fs.writeFileSync(this.sessionFile, JSON.stringify(session, null, 2));
}
static loadSession() {
try {
if (fs.existsSync(this.sessionFile)) {
const data = fs.readFileSync(this.sessionFile, 'utf8');
return JSON.parse(data);
}
}
catch (error) {
// Session file might be corrupted
}
return null;
}
static clearSession() {
try {
if (fs.existsSync(this.sessionFile)) {
fs.unlinkSync(this.sessionFile);
}
}
catch (error) {
// Ignore errors when clearing
}
this.activeProcess = null;
}
static async isSessionValid(session) {
try {
// Check if the process is still running
if (process.platform === 'win32') {
// On Windows, use tasklist to check if process exists
const { execSync } = require('child_process');
try {
const output = execSync(`tasklist /FI "PID eq ${session.pid}"`, { encoding: 'utf8' });
if (!output.includes(session.pid.toString())) {
return false;
}
}
catch {
return false;
}
}
else {
// On Unix-like systems, use kill -0
process.kill(session.pid, 0);
}
// Also check if Chrome is responding
const response = await fetch(`http://localhost:${session.port}/json/version`);
return response.ok;
}
catch {
return false;
}
}
static async getValidSession() {
const session = this.loadSession();
if (session && await this.isSessionValid(session)) {
return session;
}
this.clearSession();
return null;
}
}
exports.SessionManager = SessionManager;