Skip to content

Commit 1efb219

Browse files
tomalaforgeclaude
andcommitted
feat(website): run challenges in a WebContainer and submit answers as PRs
The editor page can now serve a challenge's app (synthesized standalone Angular project, npm install + ng serve in a WebContainer with live preview iframe), run its jest/vitest tests with streamed output, and open an Answer:<n> pull request from the signed-in user's fork via a new /api/challenges/:number/submit endpoint. The generator bundles dependency versions, test-runner metadata and base64 assets per challenge; the editor route gets COOP/COEP headers for cross-origin isolation. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
1 parent 5ff16d3 commit 1efb219

12 files changed

Lines changed: 1053 additions & 63 deletions

File tree

‎website/angular.json‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,7 @@
2424
"input": "public"
2525
}
2626
],
27-
"styles": [
28-
"src/styles.css"
29-
],
27+
"styles": ["src/styles.css"],
3028
"server": "src/main.server.ts",
3129
"outputMode": "server",
3230
"security": {
@@ -62,6 +60,12 @@
6260
},
6361
"serve": {
6462
"builder": "@angular/build:dev-server",
63+
"options": {
64+
"headers": {
65+
"Cross-Origin-Opener-Policy": "same-origin",
66+
"Cross-Origin-Embedder-Policy": "credentialless"
67+
}
68+
},
6569
"configurations": {
6670
"production": {
6771
"buildTarget": "angular-challenges-website:build:production"

‎website/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
"@shikijs/langs": "4.4.3",
2626
"@shikijs/themes": "4.4.3",
2727
"@tailwindcss/postcss": "^4.3.3",
28+
"@webcontainer/api": "^1.6.4",
2829
"express": "^5.1.0",
2930
"postcss": "^8.5.26",
3031
"rxjs": "~7.8.0",

‎website/pnpm-lock.yaml‎

Lines changed: 8 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎website/src/app/doc.model.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,26 @@ export interface Doc {
4545
export interface StarterFile {
4646
path: string;
4747
content: string;
48+
/** Binary asset (base64-encoded): mounted for the preview, hidden from the editor. */
49+
base64?: boolean;
50+
}
51+
52+
/**
53+
* A challenge's starter app bundled for the in-browser editor, with the
54+
* metadata needed to synthesize a standalone runnable project (WebContainer)
55+
* and to submit edits back as a pull request.
56+
*/
57+
export interface ChallengeStarter {
58+
/** Repo-relative app directory, e.g. `apps/angular/1-projection`. */
59+
appPath: string;
60+
/** Whether the app can be served standalone (all imports resolvable + has main.ts). */
61+
runnable: boolean;
62+
hasTests: boolean;
63+
runner: 'jest' | 'vitest' | null;
64+
/** Exact versions from the workspace root package.json. */
65+
dependencies: Record<string, string>;
66+
devDependencies: Record<string, string>;
67+
files: StarterFile[];
4868
}
4969

5070
export interface NavItem {

‎website/src/app/pages/docs/doc-page.html‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,9 @@ <h1 class="text-3xl font-bold tracking-tight text-neutral-900 sm:text-4xl dark:t
5252
Browse solutions
5353
</a>
5454
@if (doc().hasStarter) {
55+
<!-- Hard navigation: the editor route needs COOP/COEP headers on its document. -->
5556
<a
56-
[routerLink]="doc().url + '/editor'"
57+
[href]="doc().url + '/editor'"
5758
class="inline-flex items-center gap-2 rounded-lg border border-neutral-300 bg-black/[0.02] px-4 py-2 text-sm font-medium text-neutral-700 transition hover:border-neutral-400 hover:text-neutral-900 dark:border-neutral-700/80 dark:bg-white/[0.03] dark:text-neutral-300 dark:hover:border-neutral-500 dark:hover:text-white"
5859
>
5960
<svg
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
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

Comments
 (0)