diff --git a/.env.example b/.env.example index 7a67ced..74934f7 100644 --- a/.env.example +++ b/.env.example @@ -7,7 +7,7 @@ # Google Analytics 4 - Web analytics # Get your measurement ID from https://analytics.google.com # Format: G-XXXXXXXXXX -NUXT_PUBLIC_GTAG_ID=G-DN17ZDXFX7 +NUXT_PUBLIC_GTAG_ID=G-XXXXXXXXXX # # For production (after deploying worker): diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2e83f29..61ad935 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -56,23 +56,30 @@ jobs: - name: Build run: npm run build - # NOTE: The Cloudflare Worker in worker/ is a separate sub-project with its own - # dependencies, tsconfig and tests. It is intentionally NOT part of this - # workflow yet because its test suite currently has pre-existing failures and - # type errors (see the tracking issue). Once those are resolved, add a job here: - # - # worker: - # runs-on: ubuntu-latest - # defaults: - # run: - # working-directory: worker - # steps: - # - uses: actions/checkout@v7 - # - uses: actions/setup-node@v7 - # with: - # node-version-file: .nvmrc - # cache: npm - # cache-dependency-path: worker/package-lock.json - # - run: npm ci - # - run: npm run type-check - # - run: npm run test + # The Cloudflare Worker in worker/ is a separate sub-project with its own + # dependencies, tsconfig and tests, so it is checked independently. + worker: + name: Worker (type-check & test) + runs-on: ubuntu-latest + defaults: + run: + working-directory: worker + steps: + - name: Checkout + uses: actions/checkout@v7 + + - name: Setup Node + uses: actions/setup-node@v7 + with: + node-version-file: .nvmrc + cache: npm + cache-dependency-path: worker/package-lock.json + + - name: Install dependencies + run: npm ci + + - name: Type-check + run: npm run type-check + + - name: Unit tests + run: npm run test diff --git a/worker/src/middleware/cors.ts b/worker/src/middleware/cors.ts index 59d3d49..cf4cf41 100644 --- a/worker/src/middleware/cors.ts +++ b/worker/src/middleware/cors.ts @@ -7,14 +7,20 @@ import { Context, Next } from "hono"; import type { Env } from "../types"; /** - * CORS configuration headers - Very permissive for development + * CORS configuration headers + * + * Only the configured frontend origin (or the request origin when it matches) + * is ever reflected, so browsers on other sites cannot make cross-origin + * requests. Credentials are intentionally not enabled: the API authenticates + * via an `Authorization: Bearer` header rather than cookies. */ -export const getCorsHeaders = (origin: string) => { +export const getCorsHeaders = (origin: string | undefined, allowedOrigin: string) => { + const allowOrigin = origin === allowedOrigin ? origin : allowedOrigin; + return { - "Access-Control-Allow-Origin": origin || "*", + "Access-Control-Allow-Origin": allowOrigin, "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS", "Access-Control-Allow-Headers": "Content-Type, Authorization, X-Requested-With, Accept, Origin", - "Access-Control-Allow-Credentials": "true", "Access-Control-Max-Age": "86400", }; }; @@ -24,23 +30,30 @@ export const getCorsHeaders = (origin: string) => { * and handles preflight requests */ export const corsMiddleware = async (c: Context<{ Bindings: Env }>, next: Next) => { - const origin = c.req.header("Origin") || "*"; + const allowedOrigin = c.env.FRONTEND_URL; + const origin = c.req.header("Origin"); // Handle preflight requests if (c.req.method === "OPTIONS") { - const headers = getCorsHeaders(origin); return new Response(null, { status: 204, - headers, + headers: getCorsHeaders(origin, allowedOrigin), }); } // Continue to next middleware/handler await next(); - // Add CORS headers to response - const headers = getCorsHeaders(origin); - Object.entries(headers).forEach(([key, value]) => { - c.res.headers.set(key, value); + // Rebuild the response with CORS headers rather than mutating c.res.headers, + // because some responses (e.g. redirects) expose immutable headers. + const headers = new Headers(c.res.headers); + Object.entries(getCorsHeaders(origin, allowedOrigin)).forEach(([key, value]) => { + headers.set(key, value); + }); + + c.res = new Response(c.res.body, { + status: c.res.status, + statusText: c.res.statusText, + headers, }); }; diff --git a/worker/src/services/database.ts b/worker/src/services/database.ts index df73696..56448e1 100644 --- a/worker/src/services/database.ts +++ b/worker/src/services/database.ts @@ -4,7 +4,11 @@ */ import type { User, Progress, QuizScore, Bookmark, BookmarkWithParams, Env } from '../types' -import { ErrorCode } from '../types' +import { + createDatabaseError, + createValidationError, + createNotFoundError, +} from '../utils/errors' /** * Generate a unique ID using crypto @@ -55,11 +59,7 @@ export async function createUser( updated_at: now, } } catch (error) { - throw { - code: ErrorCode.DATABASE_ERROR, - message: 'Failed to create user', - details: error, - } + throw createDatabaseError('Failed to create user', error) } } @@ -79,11 +79,7 @@ export async function getUserByGoogleId(db: D1Database, googleId: string): Promi return result } catch (error) { console.error(error) - throw { - code: ErrorCode.DATABASE_ERROR, - message: 'Failed to get user by Google ID', - details: error, - } + throw createDatabaseError('Failed to get user by Google ID', error) } } @@ -102,11 +98,7 @@ export async function getUserById(db: D1Database, userId: string): Promise 10240) { - throw { - code: ErrorCode.VALIDATION_ERROR, - message: 'Parameters exceed 10KB limit', - details: { size: jsonSize, limit: 10240 } - } + throw createValidationError('Parameters exceed 10KB limit', { size: jsonSize, limit: 10240 }) } console.log("Initiating insert") @@ -408,11 +373,7 @@ export async function saveBookmark( if ((error as any).code) { throw error } - throw { - code: ErrorCode.DATABASE_ERROR, - message: 'Failed to save bookmark', - details: error, - } + throw createDatabaseError('Failed to save bookmark', error) } } @@ -452,11 +413,7 @@ export async function updateBookmark( // Validate JSON size is under 10KB const jsonSize = new TextEncoder().encode(parametersJson).length if (jsonSize > 10240) { - throw { - code: ErrorCode.VALIDATION_ERROR, - message: 'Parameters exceed 10KB limit', - details: { size: jsonSize, limit: 10240 } - } + throw createValidationError('Parameters exceed 10KB limit', { size: jsonSize, limit: 10240 }) } fields.push('parameters = ?') @@ -483,10 +440,7 @@ export async function updateBookmark( .first() if (!result) { - throw { - code: ErrorCode.NOT_FOUND, - message: 'Bookmark not found', - } + throw createNotFoundError('Bookmark not found') } return result @@ -494,11 +448,7 @@ export async function updateBookmark( if ((error as any).code) { throw error } - throw { - code: ErrorCode.DATABASE_ERROR, - message: 'Failed to update bookmark', - details: error, - } + throw createDatabaseError('Failed to update bookmark', error) } } @@ -537,11 +487,7 @@ export async function getBookmarksByUserId(db: D1Database, userId: string): Prom return bookmarks } catch (error) { - throw { - code: ErrorCode.DATABASE_ERROR, - message: 'Failed to get bookmarks', - details: error, - } + throw createDatabaseError('Failed to get bookmarks', error) } } @@ -566,10 +512,6 @@ export async function deleteBookmark( return (result.meta?.changes || 0) > 0 } catch (error) { - throw { - code: ErrorCode.DATABASE_ERROR, - message: 'Failed to delete bookmark', - details: error, - } + throw createDatabaseError('Failed to delete bookmark', error) } } diff --git a/worker/src/utils/validation.ts b/worker/src/utils/validation.ts index 3705864..69f142e 100644 --- a/worker/src/utils/validation.ts +++ b/worker/src/utils/validation.ts @@ -102,40 +102,33 @@ export function isValidEmail(email: string): boolean { /** * Validates module ID format * Module IDs should follow the pattern: domain/module-name - * Examples: regression/linear-regression, clustering/k-means + * Examples: linear-regression, attention-mechanisms, regression/linear-regression * Requirements: 7.4 */ export function isValidModuleId(moduleId: string): boolean { if (typeof moduleId !== 'string' || !moduleId) { return false } - - // Module ID pattern: domain/module-name (kebab-case) - const moduleIdRegex = /^[a-z]+(?:-[a-z0-9]+)*$/ - - if (!moduleIdRegex.test(moduleId)) { - return false - } - + // Length constraints if (moduleId.length > 100) { return false } - - // Ensure no consecutive hyphens or slashes - if (moduleId.includes('--') || moduleId.includes('//')) { + + // A module ID is one or two kebab-case segments separated by "/". + // + // The app identifies modules by their bare ID (e.g. "linear-regression", + // "attention-mechanisms" — see `loadQuiz('decision-trees', ...)` and each + // module's config.json "id"), so a single segment is the common case. The + // nested "domain/module" form is also accepted. + const segmentRegex = /^[a-z0-9]+(?:-[a-z0-9]+)*$/ + const segments = moduleId.split('/') + + if (segments.length > 2) { return false } - - // Ensure doesn't start or end with hyphen - const parts = moduleId.split('/') - for (const part of parts) { - if (part.startsWith('-') || part.endsWith('-')) { - return false - } - } - - return true + + return segments.every((segment) => segmentRegex.test(segment)) } /** diff --git a/worker/tests/handlers/auth.test.ts b/worker/tests/handlers/auth.test.ts index e057c73..7cf3a13 100644 --- a/worker/tests/handlers/auth.test.ts +++ b/worker/tests/handlers/auth.test.ts @@ -30,7 +30,7 @@ describe('Authentication Handlers', () => { vi.clearAllMocks() mockEnv = { - DB: {} as D1Database, + ml_platform_db: {} as D1Database, GOOGLE_CLIENT_ID: 'test-client-id', GOOGLE_CLIENT_SECRET: 'test-client-secret', GOOGLE_REDIRECT_URI: 'https://api.test.com/auth/callback', @@ -150,8 +150,8 @@ describe('Authentication Handlers', () => { mockEnv.GOOGLE_REDIRECT_URI ) expect(fetchUserProfile).toHaveBeenCalledWith(mockAccessToken) - expect(getUserByGoogleId).toHaveBeenCalledWith(mockenv.ml_platform_db, mockUserProfile.id) - expect(createUser).toHaveBeenCalledWith(mockenv.ml_platform_db, { + expect(getUserByGoogleId).toHaveBeenCalledWith(mockEnv.ml_platform_db, mockUserProfile.id) + expect(createUser).toHaveBeenCalledWith(mockEnv.ml_platform_db, { google_id: mockUserProfile.id, email: mockUserProfile.email, name: mockUserProfile.name, @@ -224,7 +224,7 @@ describe('Authentication Handlers', () => { const response = await handleOAuthCallback(request, mockEnv) expect(response.status).toBe(302) - expect(updateUser).toHaveBeenCalledWith(mockenv.ml_platform_db, existingUser.id, { + expect(updateUser).toHaveBeenCalledWith(mockEnv.ml_platform_db, existingUser.id, { email: mockUserProfile.email, name: mockUserProfile.name, picture_url: mockUserProfile.picture @@ -346,7 +346,7 @@ describe('Authentication Handlers', () => { }) expect(authenticateRequest).toHaveBeenCalledWith(request, mockEnv) - expect(getUserById).toHaveBeenCalledWith(mockenv.ml_platform_db, mockUser.id) + expect(getUserById).toHaveBeenCalledWith(mockEnv.ml_platform_db, mockUser.id) }) it('should handle user not found', async () => { diff --git a/worker/tests/handlers/progress.test.ts b/worker/tests/handlers/progress.test.ts index 7d6a37d..4ef81f1 100644 --- a/worker/tests/handlers/progress.test.ts +++ b/worker/tests/handlers/progress.test.ts @@ -8,7 +8,7 @@ import { handleSyncProgress, handleGetProgress } from '../../src/handlers/progre import * as authMiddleware from '../../src/middleware/auth' import * as database from '../../src/services/database' import * as validation from '../../src/utils/validation' -import type { Env, SyncProgressRequest, Progress, QuizScore, Bookmark } from '../../src/types' +import type { Env, SyncProgressRequest, Progress, QuizScore, BookmarkWithParams } from '../../src/types' // Mock dependencies vi.mock('../../src/middleware/auth') @@ -456,12 +456,15 @@ describe('Progress Handlers', () => { } ] - const mockBookmarks: Bookmark[] = [ + const mockBookmarks: BookmarkWithParams[] = [ { id: 'bookmark-1', user_id: 'user-123', module_id: 'pca', - created_at: 1234567890 + name: 'PCA Bookmark', + parameters: {}, + created_at: 1234567890, + updated_at: 1234567890 } ] diff --git a/worker/tests/index.test.ts b/worker/tests/index.test.ts index 98c2afc..0cc8de5 100644 --- a/worker/tests/index.test.ts +++ b/worker/tests/index.test.ts @@ -9,7 +9,7 @@ import type { Env } from '../src/index' // Mock environment const mockEnv: Env = { - DB: {} as D1Database, + ml_platform_db: {} as D1Database, GOOGLE_CLIENT_ID: 'test-client-id', GOOGLE_CLIENT_SECRET: 'test-client-secret', GOOGLE_REDIRECT_URI: 'https://api.test.com/api/auth/google/callback', @@ -39,8 +39,8 @@ describe('Worker Entry Point', () => { const res = await app.fetch(req, mockEnv) expect(res.headers.get('Access-Control-Allow-Origin')).toBe('https://test.com') - expect(res.headers.get('Access-Control-Allow-Methods')).toBe('GET, POST, OPTIONS') - expect(res.headers.get('Access-Control-Allow-Headers')).toBe('Content-Type, Authorization') + expect(res.headers.get('Access-Control-Allow-Methods')).toBe('GET, POST, PUT, DELETE, PATCH, OPTIONS') + expect(res.headers.get('Access-Control-Allow-Headers')).toBe('Content-Type, Authorization, X-Requested-With, Accept, Origin') }) it('should handle preflight OPTIONS requests', async () => { diff --git a/worker/tests/integration/oauth-flow.test.ts b/worker/tests/integration/oauth-flow.test.ts index 22bc075..9386444 100644 --- a/worker/tests/integration/oauth-flow.test.ts +++ b/worker/tests/integration/oauth-flow.test.ts @@ -25,7 +25,7 @@ describe('OAuth Flow Integration', () => { } mockEnv = { - DB: mockDB as D1Database, + ml_platform_db: mockDB as D1Database, GOOGLE_CLIENT_ID: 'test-client-id.apps.googleusercontent.com', GOOGLE_CLIENT_SECRET: 'test-client-secret', GOOGLE_REDIRECT_URI: 'https://api.test.com/api/auth/google/callback', diff --git a/worker/tests/integration/progress-sync.test.ts b/worker/tests/integration/progress-sync.test.ts index 0af73f8..76d34b1 100644 --- a/worker/tests/integration/progress-sync.test.ts +++ b/worker/tests/integration/progress-sync.test.ts @@ -30,7 +30,7 @@ describe('Progress Sync Integration', () => { } mockEnv = { - DB: mockDB as D1Database, + ml_platform_db: mockDB as D1Database, GOOGLE_CLIENT_ID: 'test-client-id', GOOGLE_CLIENT_SECRET: 'test-client-secret', GOOGLE_REDIRECT_URI: 'https://api.test.com/callback', @@ -77,8 +77,12 @@ describe('Progress Sync Integration', () => { ], bookmarks: [ { + id: 'bookmark-kmeans-1', module_id: 'clustering/k-means', - created_at: Date.now() + name: 'K-Means Bookmark', + parameters: { clusters: 3 }, + created_at: Date.now(), + updated_at: Date.now() } ] } @@ -96,7 +100,7 @@ describe('Progress Sync Integration', () => { expect(response.status).toBe(200) - const data = await response.json() + const data = (await response.json()) as Record expect(data).toHaveProperty('success', true) expect(data).toHaveProperty('synced_at') expect(typeof data.synced_at).toBe('number') @@ -213,8 +217,12 @@ describe('Progress Sync Integration', () => { quizzes: [], bookmarks: [ { + id: 'bookmark-kmeans-2', module_id: 'clustering/k-means', - created_at: newTimestamp + name: 'K-Means Bookmark', + parameters: { clusters: 3 }, + created_at: newTimestamp, + updated_at: newTimestamp } ] } @@ -244,11 +252,19 @@ describe('Progress Sync Integration', () => { ) // Verify bookmark with newer timestamp + // saveBookmark binds: id, user_id, module_id, name, parameters, + // created_at, updated_at, then name, parameters, updated_at for the + // ON CONFLICT UPDATE clause. expect(mockDB.bind).toHaveBeenCalledWith( - expect.any(String), + 'bookmark-kmeans-2', testUserId, 'clustering/k-means', + 'K-Means Bookmark', + JSON.stringify({ clusters: 3 }), + newTimestamp, newTimestamp, + 'K-Means Bookmark', + JSON.stringify({ clusters: 3 }), newTimestamp ) }) @@ -271,8 +287,12 @@ describe('Progress Sync Integration', () => { completed_at: Date.now() - i * 1000 })), bookmarks: Array.from({ length: batchSize }, (_, i) => ({ + id: `bookmark-${i}`, module_id: `domain/module-${i}`, - created_at: Date.now() - i * 2000 + name: `Bookmark ${i}`, + parameters: { index: i }, + created_at: Date.now() - i * 2000, + updated_at: Date.now() - i * 2000 })) } @@ -289,7 +309,7 @@ describe('Progress Sync Integration', () => { expect(response.status).toBe(200) - const data = await response.json() + const data = (await response.json()) as Record expect(data.success).toBe(true) // Verify all items were processed @@ -366,7 +386,7 @@ describe('Progress Sync Integration', () => { expect(response.status).toBe(200) - const data = await response.json() + const data = (await response.json()) as Record expect(data).toHaveProperty('modules') expect(data).toHaveProperty('quizzes') expect(data).toHaveProperty('bookmarks') @@ -419,7 +439,7 @@ describe('Progress Sync Integration', () => { expect(response.status).toBe(400) - const data = await response.json() + const data = (await response.json()) as Record expect(data).toHaveProperty('code', 'VALIDATION_ERROR') expect(data.message).toContain('Invalid module_id') }) @@ -453,7 +473,7 @@ describe('Progress Sync Integration', () => { expect(response.status).toBe(400) - const data = await response.json() + const data = (await response.json()) as Record expect(data).toHaveProperty('code', 'VALIDATION_ERROR') expect(data.message).toContain('score') }) @@ -480,7 +500,7 @@ describe('Progress Sync Integration', () => { expect(response.status).toBe(401) - const data = await response.json() + const data = (await response.json()) as Record expect(data).toHaveProperty('code', 'UNAUTHORIZED') }) @@ -496,7 +516,7 @@ describe('Progress Sync Integration', () => { expect(response.status).toBe(401) - const data = await response.json() + const data = (await response.json()) as Record expect(data).toHaveProperty('code', 'UNAUTHORIZED') }) @@ -522,7 +542,7 @@ describe('Progress Sync Integration', () => { expect(response.status).toBe(200) - const data = await response.json() + const data = (await response.json()) as Record expect(data).toHaveProperty('success', true) expect(data).toHaveProperty('synced_at') @@ -559,7 +579,7 @@ describe('Progress Sync Integration', () => { const failingEnv = { ...mockEnv, - DB: failingDB as D1Database + ml_platform_db: failingDB as unknown as D1Database } const request = new Request('https://api.test.com/api/progress/sync', { @@ -575,7 +595,7 @@ describe('Progress Sync Integration', () => { expect(response.status).toBe(500) - const data = await response.json() + const data = (await response.json()) as Record expect(data).toHaveProperty('code', 'DATABASE_ERROR') expect(data).toHaveProperty('message') }) diff --git a/worker/tests/middleware/auth.test.ts b/worker/tests/middleware/auth.test.ts index a17847a..64a585e 100644 --- a/worker/tests/middleware/auth.test.ts +++ b/worker/tests/middleware/auth.test.ts @@ -74,7 +74,7 @@ describe('Auth Middleware', () => { beforeEach(() => { mockEnv = { - DB: {} as D1Database, + ml_platform_db: {} as D1Database, GOOGLE_CLIENT_ID: 'test-client-id', GOOGLE_CLIENT_SECRET: 'test-client-secret', GOOGLE_REDIRECT_URI: 'https://example.com/callback', diff --git a/worker/tests/middleware/cors.test.ts b/worker/tests/middleware/cors.test.ts index c869f47..ef76ef0 100644 --- a/worker/tests/middleware/cors.test.ts +++ b/worker/tests/middleware/cors.test.ts @@ -10,7 +10,7 @@ import type { Env } from "../../src/types"; describe("CORS Middleware", () => { const mockEnv: Env = { - DB: {} as D1Database, + ml_platform_db: {} as D1Database, GOOGLE_CLIENT_ID: "test-client-id", GOOGLE_CLIENT_SECRET: "test-client-secret", GOOGLE_REDIRECT_URI: "http://localhost/callback", @@ -27,8 +27,8 @@ describe("CORS Middleware", () => { expect(headers).toEqual({ "Access-Control-Allow-Origin": "https://example.com", - "Access-Control-Allow-Methods": "GET, POST, OPTIONS", - "Access-Control-Allow-Headers": "Content-Type, Authorization", + "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS", + "Access-Control-Allow-Headers": "Content-Type, Authorization, X-Requested-With, Accept, Origin", "Access-Control-Max-Age": "86400", }); }); @@ -41,8 +41,8 @@ describe("CORS Middleware", () => { expect(headers).toEqual({ "Access-Control-Allow-Origin": "https://example.com", - "Access-Control-Allow-Methods": "GET, POST, OPTIONS", - "Access-Control-Allow-Headers": "Content-Type, Authorization", + "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS", + "Access-Control-Allow-Headers": "Content-Type, Authorization, X-Requested-With, Accept, Origin", "Access-Control-Max-Age": "86400", }); }); @@ -77,8 +77,8 @@ describe("CORS Middleware", () => { expect(res.status).toBe(204); expect(res.headers.get("Access-Control-Allow-Origin")).toBe("https://example.com"); - expect(res.headers.get("Access-Control-Allow-Methods")).toBe("GET, POST, OPTIONS"); - expect(res.headers.get("Access-Control-Allow-Headers")).toBe("Content-Type, Authorization"); + expect(res.headers.get("Access-Control-Allow-Methods")).toBe("GET, POST, PUT, DELETE, PATCH, OPTIONS"); + expect(res.headers.get("Access-Control-Allow-Headers")).toBe("Content-Type, Authorization, X-Requested-With, Accept, Origin"); expect(res.headers.get("Access-Control-Max-Age")).toBe("86400"); }); @@ -98,8 +98,8 @@ describe("CORS Middleware", () => { expect(res.status).toBe(200); expect(res.headers.get("Access-Control-Allow-Origin")).toBe("https://example.com"); - expect(res.headers.get("Access-Control-Allow-Methods")).toBe("GET, POST, OPTIONS"); - expect(res.headers.get("Access-Control-Allow-Headers")).toBe("Content-Type, Authorization"); + expect(res.headers.get("Access-Control-Allow-Methods")).toBe("GET, POST, PUT, DELETE, PATCH, OPTIONS"); + expect(res.headers.get("Access-Control-Allow-Headers")).toBe("Content-Type, Authorization, X-Requested-With, Accept, Origin"); expect(res.headers.get("Access-Control-Max-Age")).toBe("86400"); }); @@ -154,7 +154,7 @@ describe("CORS Middleware", () => { expect(res.status).toBe(200); expect(res.headers.get("Access-Control-Allow-Origin")).toBe("https://example.com"); - expect(res.headers.get("Access-Control-Allow-Methods")).toBe("GET, POST, OPTIONS"); + expect(res.headers.get("Access-Control-Allow-Methods")).toBe("GET, POST, PUT, DELETE, PATCH, OPTIONS"); }); it("should handle preflight for POST requests with Authorization header", async () => { diff --git a/worker/tests/utils/validation.test.ts b/worker/tests/utils/validation.test.ts index c7a2fca..288663a 100644 --- a/worker/tests/utils/validation.test.ts +++ b/worker/tests/utils/validation.test.ts @@ -125,6 +125,13 @@ describe('isValidEmail', () => { describe('isValidModuleId', () => { it('should validate correct module IDs', () => { const validIds = [ + // Bare module IDs — this is what the app actually sends + // (e.g. `loadQuiz('decision-trees', ...)`, config.json "id") + 'linear-regression', + 'k-means', + 'attention-mechanisms', + 'decision-trees', + // Nested domain/module form 'regression/linear-regression', 'clustering/k-means', 'preprocessing/feature-scaling', @@ -140,7 +147,12 @@ describe('isValidModuleId', () => { it('should reject invalid module IDs', () => { const invalidIds = [ '', - 'invalid', + // Bare IDs are valid, but these bare forms are not kebab-case: + 'Invalid', + 'has_underscore', + 'double--hyphen', + '-leading-hyphen', + 'trailing-hyphen-', 'Invalid/Module', 'module/with spaces', 'module/with_underscore', @@ -176,14 +188,15 @@ describe('validateProgressData', () => { const validData = { modules: [ { - module_id: 'regression/linear-regression', + // Bare module ID — the shape the app actually sends + module_id: 'linear-regression', completed: true, completed_at: Date.now() } ], quizzes: [ { - module_id: 'regression/linear-regression', + module_id: 'decision-trees', score: 8, total: 10, completed_at: Date.now() @@ -220,7 +233,8 @@ describe('validateProgressData', () => { const invalidData = { modules: [ { - module_id: 'invalid-id', + // Spaces are not valid in module IDs + module_id: 'invalid id', completed: true, completed_at: Date.now() } @@ -272,7 +286,8 @@ describe('validateProgressData', () => { quizzes: [], bookmarks: [ { - module_id: 'invalid-id', + // Spaces are not valid in module IDs + module_id: 'invalid id', created_at: Date.now() } ]