Files
STCourses/apps/server/test/e2e.test.ts
T
Lucas WintherandClaude Opus 5.5 777ae2cc37 feat: resolve Phase 1 contract requests and compose every feature
Contracts and core:
- Feature gains auth and stop; FeatureFactory; core composeServer builds the
  context, runs the factories, then the job queue from the union of their jobs
  (R8/R14). startServer uses it; main.ts composes learner, import, studio, AI.
- AppConfig/loadConfig own the layout and settings: courseDirs include
  <dataDir>/courses and <dataDir>/worktrees, studioReposDir, cacheDir,
  importRoots, uploadMaxMb, aiAllowedBaseUrls, transcribeUrl, python.
  resolveConfig derives the same for tests; cachePaths shares the importer's
  cache layout.
- canView: the global author role views every course (R14); the learner,
  studio and AI packages all call it.
- migrate(db, packages): core first, then packages in name order.
- Media: nosniff on every response, a sandbox CSP on svg/html/js; a Range on
  an empty file is 416.
- courseUrl/lessonUrl and the lesson route patterns live in @stc/contracts.

Packages:
- import, studio and AI read AppConfig instead of process.env; the importer
  refuses ids used by studio/repos.
- learner migrations run through core migrate; library covers fall back to
  the importer's cached candidate behind a canView-checked route.
- studio preview renders through the learner LessonView (anchors honoured,
  draft URLs); AI drafts go to the studio draft branch for studio courses (as
  the requesting user) and to <dataDir>/drafts otherwise, and the generator
  page says which.

Web: tsconfig paths for @stc/<feature>/web browser entries; features.ts
imports them by package name; nav.roles hides links by role.

Tests: compose, config, canView, media headers, migrations order, covers,
preview, nav, SPA bundle without server code, and an end-to-end flow on
SQLite and Postgres.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 15:02:46 +01:00

118 lines
7.0 KiB
TypeScript

// End-to-end (plan Task I3): the real server with every feature, against the fixtures, on SQLite and Postgres.
import { describe, expect, test } from "bun:test";
import { mkdtempSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { loadConfig } from "@stc/core";
import { studioFeature } from "@stc/feature-studio";
import { createBrowserRunner } from "../../../packages/feature-learner/src/web/runner/runner";
import { aiDraftSink, packageMigrations, productFeatures } from "../src/features";
import { startServer } from "../src/main";
import { PG, pgSchema } from "./pg";
const FIXTURES = resolve(import.meta.dir, "../../../fixtures/courses");
const ORIGIN = "http://localhost:3000";
const cookieFrom = (r: Response) => r.headers.getSetCookie().map((c) => c.split(";")[0]).filter((c) => !c.endsWith("=")).join("; ");
async function run(databaseUrl: string) {
const dataDir = mkdtempSync(join(tmpdir(), "stc-e2e-"));
const config = loadConfig({
STC_PORT: "0", STC_DATABASE_URL: databaseUrl, STC_SECRET: "e2e-secret-0123456789abcdef0123456789",
STC_DATA_DIR: dataDir, STC_COURSE_DIRS: FIXTURES, STC_PUBLIC_URL: ORIGIN,
});
const s = await startServer(config, productFeatures({ studioWatch: false }), { migrations: packageMigrations });
const base = s.server.url.toString().replace(/\/$/, "");
const call = async (method: string, path: string, opts: { cookie?: string; body?: unknown } = {}) => {
const headers: Record<string, string> = { origin: ORIGIN };
if (opts.cookie) headers.cookie = opts.cookie;
if (opts.body !== undefined) headers["content-type"] = "application/json";
return fetch(base + path, { method, headers, body: opts.body === undefined ? undefined : JSON.stringify(opts.body) });
};
const signUp = async (email: string, name: string) => {
const r = await call("POST", "/api/auth/sign-up/email", { body: { email, name, password: "correct horse battery" } });
expect(r.status).toBe(200);
return cookieFrom(r);
};
try {
// 1. the server is up with every feature and the fixture course
expect(await (await call("GET", "/api/health")).json()).toEqual({ ok: true, courses: 1, db: databaseUrl.startsWith("postgres") ? "postgres" : "sqlite" });
expect((await call("GET", "/c/sample")).headers.get("content-type")).toContain("text/html");
// 2. sign up: the first account is the owner
const owner = await signUp("[email protected]", "Ada Lovelace");
const me = (await (await call("GET", "/api/me", { cookie: owner })).json()) as { user: { id: string; roles: string[] } };
expect(me.user.roles).toContain("owner");
// 3. mark a lesson done
expect((await call("PUT", "/api/courses/sample/progress/m1-intro", { cookie: owner, body: { state: "done" } })).status).toBe(200);
// 4. a slide note on the video lesson's deck
const note = await call("POST", "/api/courses/sample/notes", { cookie: owner, body: { lessonId: "m1-video", anchorKind: "slide", anchorValue: 2, deckId: "d1", body: "Slide two matters" } });
expect(note.status).toBe(201);
// 5. run the sample exercise with the learner's runner, then save the passing attempt
const lesson = (await (await call("GET", "/api/courses/sample/lessons/m2-ex-add", { cookie: owner })).json()) as { browser: { starter: string; tests: string } };
const runner = createBrowserRunner("js");
const failing = await runner.run(lesson.browser.starter, lesson.browser.tests, 5000);
expect(failing.some((t) => !t.passed)).toBe(true);
const code = lesson.browser.starter.replace("a - b", "a + b");
const results = await runner.run(code, lesson.browser.tests, 5000);
expect(results.length).toBeGreaterThan(0);
expect(results.every((t) => t.passed)).toBe(true);
expect((await call("PUT", "/api/courses/sample/lessons/m2-ex-add/attempt", { cookie: owner, body: { code, passed: true, result: results, track: "js" } })).status).toBe(200);
// 6. read progress and notes back
const progress = (await (await call("GET", "/api/courses/sample/progress", { cookie: owner })).json()) as Record<string, { state: string }>;
expect(progress["m1-intro"]?.state).toBe("done");
expect(progress["m2-ex-add"]?.state).toBe("done");
const notes = (await (await call("GET", "/api/courses/sample/notes", { cookie: owner })).json()) as { body: string; anchorKind: string; deckId: string }[];
expect(notes.map((n) => [n.body, n.anchorKind, n.deckId])).toEqual([["Slide two matters", "slide", "d1"]]);
// 7. a second account is a plain learner: own data only, and the owner/author features refuse it
const lea = await signUp("[email protected]", "Lea");
expect(await (await call("GET", "/api/courses/sample/progress", { cookie: lea })).json()).toEqual({});
expect((await call("GET", "/api/import/info", { cookie: lea })).status).toBe(403);
expect((await call("GET", "/api/studio/courses", { cookie: lea })).status).toBe(403);
expect((await call("GET", "/api/ai/admin/config", { cookie: lea })).status).toBe(403);
expect((await call("GET", "/api/import/info", { cookie: owner })).status).toBe(200);
expect((await call("GET", "/api/studio/courses", { cookie: owner })).status).toBe(200);
expect((await call("GET", "/api/ai/status", { cookie: owner })).status).toBe(200);
// 8. media: Range, nosniff
const clip = await call("GET", "/api/media/sample/media/clip.mp4", { cookie: lea });
expect(clip.headers.get("x-content-type-options")).toBe("nosniff");
// 9. the AI draft sink: studio-managed course -> the author's draft branch, as that user; other courses -> files
const studio = studioFeature(s.ctx, { watch: false });
try {
await studio.store.createCourse({ id: "gen-target", title: "Generated" }, { name: "Ada Lovelace", email: "[email protected]" });
const sink = aiDraftSink(s.ctx, studio);
const onStudio = await sink.writeDraftFiles("gen-target", me.user.id, [{ path: "lessons/q.md", content: "# Q\n" }], "AI draft");
expect(onStudio.branch).toMatch(/^draft\//);
const repo = join(config.studioReposDir, "gen-target.git");
const author = (await Bun.$`git --git-dir=${repo} log -1 ${"--format=%an <%ae>"} ${onStudio.branch!}`.text()).trim();
expect(author).toBe("Ada Lovelace <[email protected]>");
const onFiles = await sink.writeDraftFiles("sample", me.user.id, [{ path: "q.md", content: "# Q\n" }], "AI draft");
expect(onFiles.branch).toBeUndefined();
expect(onFiles.location!.startsWith(resolve(dataDir, "drafts", "sample"))).toBe(true);
expect(readFileSync(join(onFiles.location!, "q.md"), "utf8")).toBe("# Q\n");
} finally {
studio.stop();
}
} finally {
await s.stop();
}
}
describe("end to end", () => {
test("sign up, mark done, slide note, exercise, progress [sqlite]", () => run("sqlite://:memory:"), 60_000);
const pg = PG;
if (pg) {
test("sign up, mark done, slide note, exercise, progress [postgres]", async () => {
const { url, drop } = await pgSchema(pg);
try { await run(url); } finally { await drop(); }
}, 60_000);
}
});