(options: ServerOptions)
| 31 | * Spawns `python -m deepnote_toolkit server` and waits for it to be ready. |
| 32 | */ |
| 33 | export async function startServer(options: ServerOptions): Promise<ServerInfo> { |
| 34 | const { pythonEnv, workingDirectory, port, startupTimeoutMs = SERVER_STARTUP_TIMEOUT_MS } = options |
| 35 | |
| 36 | // Resolve the Python executable from the venv path |
| 37 | const pythonPath = await resolvePythonExecutable(pythonEnv) |
| 38 | |
| 39 | // Find available consecutive ports (Jupyter + LSP) |
| 40 | const jupyterPort = await findConsecutiveAvailablePorts(port ?? DEFAULT_PORT) |
| 41 | const lspPort = jupyterPort + 1 |
| 42 | |
| 43 | // Set up environment with correct Python paths (PATH, VIRTUAL_ENV) |
| 44 | const baseEnv: Record<string, string | undefined> = { ...process.env, ...options.env } |
| 45 | const env = await buildPythonEnv(pythonPath, baseEnv) |
| 46 | env.DEEPNOTE_RUNTIME__RUNNING_IN_DETACHED_MODE = 'true' |
| 47 | env.DEEPNOTE_ENFORCE_PIP_CONSTRAINTS = 'true' |
| 48 | |
| 49 | // Spawn deepnote-toolkit server |
| 50 | const serverProcess = spawn( |
| 51 | pythonPath, |
| 52 | ['-m', 'deepnote_toolkit', 'server', '--jupyter-port', String(jupyterPort), '--ls-port', String(lspPort)], |
| 53 | { |
| 54 | cwd: workingDirectory, |
| 55 | env, |
| 56 | stdio: ['ignore', 'pipe', 'pipe'], |
| 57 | } |
| 58 | ) |
| 59 | |
| 60 | const serverInfo: ServerInfo = { |
| 61 | url: `http://localhost:${jupyterPort}`, |
| 62 | jupyterPort, |
| 63 | lspPort, |
| 64 | process: serverProcess, |
| 65 | } |
| 66 | |
| 67 | // Collect output for error reporting |
| 68 | let stdout = '' |
| 69 | let stderr = '' |
| 70 | |
| 71 | serverProcess.stdout?.on('data', (data: Buffer) => { |
| 72 | stdout += data.toString() |
| 73 | // Keep last 5000 chars |
| 74 | if (stdout.length > 5000) stdout = stdout.slice(-5000) |
| 75 | }) |
| 76 | |
| 77 | serverProcess.stderr?.on('data', (data: Buffer) => { |
| 78 | stderr += data.toString() |
| 79 | if (stderr.length > 5000) stderr = stderr.slice(-5000) |
| 80 | }) |
| 81 | |
| 82 | // Handle early process exit |
| 83 | const exitPromise = new Promise<never>((_, reject) => { |
| 84 | serverProcess.on('exit', (code, signal) => { |
| 85 | reject(new Error(`Server process exited unexpectedly (code=${code}, signal=${signal}).\nstderr: ${stderr}`)) |
| 86 | }) |
| 87 | }) |
| 88 | |
| 89 | // Wait for server to be ready |
| 90 | try { |
no test coverage detected