( sessionName: string, headed = false, )
| 81 | } |
| 82 | |
| 83 | export async function getOrLaunchSession( |
| 84 | sessionName: string, |
| 85 | headed = false, |
| 86 | ): Promise<{session: BrowserSession; error?: string}> { |
| 87 | // Return existing session if alive |
| 88 | const existing = sessionMap.get(sessionName); |
| 89 | if (existing) { |
| 90 | if (existing.page.isClosed()) { |
| 91 | existing.page = await existing.context.newPage(); |
| 92 | } |
| 93 | return {session: existing}; |
| 94 | } |
| 95 | |
| 96 | // Look up profile from session config |
| 97 | const sessionConfig = getSessionConfig(sessionName); |
| 98 | if (!sessionConfig) { |
| 99 | return { |
| 100 | session: undefined as unknown as BrowserSession, |
| 101 | error: `Session "${sessionName}" is not configured. Run: corebrain browser create-session ${sessionName} --profile <profile>`, |
| 102 | }; |
| 103 | } |
| 104 | |
| 105 | try { |
| 106 | const {chromium} = await import('playwright'); |
| 107 | |
| 108 | const profileDir = getProfileDir(sessionConfig.profile); |
| 109 | fs.mkdirSync(profileDir, {recursive: true}); |
| 110 | |
| 111 | const browserConfig = getBrowserExecutable(); |
| 112 | const launchOptions: import('playwright').LaunchOptions = { |
| 113 | headless: !headed, |
| 114 | args: ['--remote-debugging-port=0'], |
| 115 | }; |
| 116 | if (browserConfig.type !== 'default' && browserConfig.path) { |
| 117 | launchOptions.executablePath = browserConfig.path; |
| 118 | } |
| 119 | |
| 120 | const context = await chromium.launchPersistentContext(profileDir, launchOptions); |
| 121 | |
| 122 | context.on('close', () => { |
| 123 | sessionMap.delete(sessionName); |
| 124 | }); |
| 125 | |
| 126 | const page = context.pages()[0] ?? (await context.newPage()); |
| 127 | |
| 128 | const cdp = await captureCdpEndpoint(profileDir); |
| 129 | |
| 130 | const session: BrowserSession = { |
| 131 | context, |
| 132 | page, |
| 133 | sessionName, |
| 134 | profile: sessionConfig.profile, |
| 135 | profileDir, |
| 136 | headed: false, |
| 137 | createdAt: Date.now(), |
| 138 | cdpPort: cdp?.port, |
| 139 | cdpWsEndpoint: cdp?.wsEndpoint, |
| 140 | cdpHttpEndpoint: cdp?.httpEndpoint, |
no test coverage detected