|
| 1 | +import { Injectable, signal } from '@angular/core'; |
| 2 | +import type { WebContainer, WebContainerProcess } from '@webcontainer/api'; |
| 3 | +import { ChallengeStarter } from '../../doc.model'; |
| 4 | +import { buildProjectTree } from './starter-project'; |
| 5 | + |
| 6 | +export type RunnerPhase = |
| 7 | + 'idle' | 'booting' | 'installing' | 'starting' | 'running' | 'testing' | 'error'; |
| 8 | + |
| 9 | +// eslint-disable-next-line no-control-regex |
| 10 | +const ANSI_ESCAPES = /\x1b\[[0-9;?]*[A-Za-z]|\x1b\][^\x07]*(?:\x07|\x1b\\)|\x1b[=>]|\r/g; |
| 11 | + |
| 12 | +/** |
| 13 | + * Runs a challenge's synthesized project inside a WebContainer: one container |
| 14 | + * per page load, `npm install` once, then `ng serve` and/or the test runner. |
| 15 | + * Requires cross-origin isolation (COOP/COEP headers on the editor route). |
| 16 | + */ |
| 17 | +@Injectable() |
| 18 | +export class ChallengeRunner { |
| 19 | + readonly phase = signal<RunnerPhase>('idle'); |
| 20 | + readonly output = signal(''); |
| 21 | + readonly previewUrl = signal<string | null>(null); |
| 22 | + |
| 23 | + private container?: Promise<WebContainer>; |
| 24 | + private installed?: Promise<boolean>; |
| 25 | + private serveProcess?: WebContainerProcess; |
| 26 | + private testProcess?: WebContainerProcess; |
| 27 | + |
| 28 | + get supported(): boolean { |
| 29 | + return typeof window !== 'undefined' && window.crossOriginIsolated === true; |
| 30 | + } |
| 31 | + |
| 32 | + async serve(starter: ChallengeStarter, contents: ReadonlyMap<string, string>): Promise<void> { |
| 33 | + try { |
| 34 | + const container = await this.prepare(starter, contents); |
| 35 | + if (!(await this.installed!)) { |
| 36 | + return; |
| 37 | + } |
| 38 | + this.serveProcess?.kill(); |
| 39 | + this.phase.set('starting'); |
| 40 | + this.append('\n$ npm start\n'); |
| 41 | + container.on('server-ready', (_port, url) => { |
| 42 | + this.previewUrl.set(url); |
| 43 | + this.phase.set('running'); |
| 44 | + }); |
| 45 | + this.serveProcess = await container.spawn('npm', ['start']); |
| 46 | + this.pipe(this.serveProcess); |
| 47 | + } catch (error) { |
| 48 | + this.fail(error); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + async runTests(starter: ChallengeStarter, contents: ReadonlyMap<string, string>): Promise<void> { |
| 53 | + try { |
| 54 | + const container = await this.prepare(starter, contents); |
| 55 | + if (!(await this.installed!)) { |
| 56 | + return; |
| 57 | + } |
| 58 | + this.testProcess?.kill(); |
| 59 | + const wasRunning = this.phase() === 'running'; |
| 60 | + this.phase.set('testing'); |
| 61 | + this.append('\n$ npm test\n'); |
| 62 | + this.testProcess = await container.spawn('npm', ['test']); |
| 63 | + this.pipe(this.testProcess); |
| 64 | + const code = await this.testProcess.exit; |
| 65 | + this.append(code === 0 ? '\n✓ Tests passed\n' : `\n✗ Tests failed (exit code ${code})\n`); |
| 66 | + this.phase.set(wasRunning ? 'running' : 'idle'); |
| 67 | + } catch (error) { |
| 68 | + this.fail(error); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + /** Push edited sources into the running container (dev server rebuilds). */ |
| 73 | + async syncFile(path: string, content: string): Promise<void> { |
| 74 | + if (!this.container) { |
| 75 | + return; |
| 76 | + } |
| 77 | + const container = await this.container; |
| 78 | + await container.fs.writeFile(`/${path}`, content).catch(() => undefined); |
| 79 | + } |
| 80 | + |
| 81 | + async destroy(): Promise<void> { |
| 82 | + this.serveProcess?.kill(); |
| 83 | + this.testProcess?.kill(); |
| 84 | + (await this.container)?.teardown(); |
| 85 | + } |
| 86 | + |
| 87 | + private async prepare( |
| 88 | + starter: ChallengeStarter, |
| 89 | + contents: ReadonlyMap<string, string>, |
| 90 | + ): Promise<WebContainer> { |
| 91 | + if (!this.container) { |
| 92 | + this.phase.set('booting'); |
| 93 | + this.append('Booting WebContainer…\n'); |
| 94 | + this.container = import('@webcontainer/api').then(({ WebContainer }) => |
| 95 | + WebContainer.boot({ coep: 'credentialless' }), |
| 96 | + ); |
| 97 | + } |
| 98 | + const container = await this.container; |
| 99 | + await container.mount(buildProjectTree(starter, contents)); |
| 100 | + if (!this.installed) { |
| 101 | + this.installed = this.install(container); |
| 102 | + } |
| 103 | + return container; |
| 104 | + } |
| 105 | + |
| 106 | + private async install(container: WebContainer): Promise<boolean> { |
| 107 | + this.phase.set('installing'); |
| 108 | + this.append('$ npm install (this can take a minute or two)\n'); |
| 109 | + const process = await container.spawn('npm', [ |
| 110 | + 'install', |
| 111 | + '--no-audit', |
| 112 | + '--no-fund', |
| 113 | + '--loglevel=error', |
| 114 | + ]); |
| 115 | + this.pipe(process); |
| 116 | + const code = await process.exit; |
| 117 | + if (code !== 0) { |
| 118 | + this.append(`\n✗ npm install failed (exit code ${code})\n`); |
| 119 | + this.phase.set('error'); |
| 120 | + return false; |
| 121 | + } |
| 122 | + this.append('\n✓ Dependencies installed\n'); |
| 123 | + return true; |
| 124 | + } |
| 125 | + |
| 126 | + private pipe(process: WebContainerProcess): void { |
| 127 | + void process.output.pipeTo( |
| 128 | + new WritableStream({ |
| 129 | + write: (chunk) => this.append(chunk.replace(ANSI_ESCAPES, '')), |
| 130 | + }), |
| 131 | + ); |
| 132 | + } |
| 133 | + |
| 134 | + private append(text: string): void { |
| 135 | + if (text) { |
| 136 | + // Keep the log bounded so a chatty dev server can't grow memory forever. |
| 137 | + this.output.update((current) => (current + text).slice(-100_000)); |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + private fail(error: unknown): void { |
| 142 | + this.append(`\n✗ ${error instanceof Error ? error.message : String(error)}\n`); |
| 143 | + this.phase.set('error'); |
| 144 | + } |
| 145 | +} |
0 commit comments