|
| 1 | +import { randomBytes } from 'crypto' |
| 2 | +import * as child_process from 'child_process' |
| 3 | +import { RemoteRepo } from './remote' |
| 4 | + |
| 5 | +export class BundleServer { |
| 6 | + private bundleServerCmd: string |
| 7 | + private bundleWebServerCmd: string |
| 8 | + |
| 9 | + // Web server |
| 10 | + private webServerProcess: child_process.ChildProcess | undefined |
| 11 | + private bundleUriBase: string | undefined |
| 12 | + |
| 13 | + // Remote repo info (for now, only support one per test) |
| 14 | + private route: string | undefined |
| 15 | + |
| 16 | + constructor(bundleServerCmd: string, bundleWebServerCmd: string) { |
| 17 | + this.bundleServerCmd = bundleServerCmd |
| 18 | + this.bundleWebServerCmd = bundleWebServerCmd |
| 19 | + } |
| 20 | + |
| 21 | + startWebServer(port: number): void { |
| 22 | + if (this.webServerProcess) { |
| 23 | + throw new Error("Tried to start web server, but web server is already running") |
| 24 | + } |
| 25 | + this.webServerProcess = child_process.spawn(this.bundleWebServerCmd, ["--port", String(port)]) |
| 26 | + this.bundleUriBase = `http://localhost:${port}/` |
| 27 | + } |
| 28 | + |
| 29 | + init(remote: RemoteRepo): child_process.SpawnSyncReturns<Buffer> { |
| 30 | + this.route = `e2e/${randomBytes(8).toString('hex')}` |
| 31 | + return child_process.spawnSync(this.bundleServerCmd, ["init", remote.remoteUri, this.route]) |
| 32 | + } |
| 33 | + |
| 34 | + update(): child_process.SpawnSyncReturns<Buffer> { |
| 35 | + if (!this.route) { |
| 36 | + throw new Error("Tried to update server before running 'init'") |
| 37 | + } |
| 38 | + return child_process.spawnSync(this.bundleServerCmd, ["update", this.route]) |
| 39 | + } |
| 40 | + |
| 41 | + bundleUri(): string { |
| 42 | + if (!this.webServerProcess) { |
| 43 | + throw new Error("Tried to get bundle URI before starting the web server") |
| 44 | + } |
| 45 | + if (!this.route) { |
| 46 | + throw new Error("Tried to get bundle URI before running 'init'") |
| 47 | + } |
| 48 | + |
| 49 | + return this.bundleUriBase + this.route |
| 50 | + } |
| 51 | + |
| 52 | + cleanup(): void { |
| 53 | + if (this.webServerProcess) { |
| 54 | + const killed = this.webServerProcess.kill('SIGINT') |
| 55 | + if (!killed) { |
| 56 | + console.warn("Web server process was not successfully stopped") |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + // Delete the added route |
| 61 | + if (this.route) { |
| 62 | + child_process.spawnSync(this.bundleServerCmd, ["delete", this.route]) |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments