@anantagnanam/lms 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +77 -2
  3. package/astro/client.ts +433 -0
  4. package/astro/components/CertificateCard.astro +83 -0
  5. package/astro/components/CourseCard.astro +61 -0
  6. package/astro/components/CourseCatalog.astro +96 -0
  7. package/astro/components/CourseOverview.astro +286 -0
  8. package/astro/components/LearnerDashboard.astro +121 -0
  9. package/astro/components/LearningShell.astro +28 -0
  10. package/astro/components/LessonPlayer.astro +323 -0
  11. package/astro/components/MediaPlayer.astro +60 -0
  12. package/astro/components/index.ts +7 -0
  13. package/astro/layouts/AcademyLayout.astro +84 -0
  14. package/astro/pages/certificate.astro +57 -0
  15. package/astro/pages/cohort.astro +102 -0
  16. package/astro/pages/course.astro +80 -0
  17. package/astro/pages/dashboard.astro +34 -0
  18. package/astro/pages/index.astro +40 -0
  19. package/astro/pages/lesson.astro +100 -0
  20. package/astro/pages/teach.astro +15 -0
  21. package/astro/styles.css +1288 -0
  22. package/dist/admin.d.ts +32 -0
  23. package/dist/admin.js +2762 -0
  24. package/dist/admin.js.map +1 -0
  25. package/dist/astro.d.ts +11 -0
  26. package/dist/astro.js +49 -0
  27. package/dist/astro.js.map +1 -0
  28. package/dist/commerce.d.ts +72 -0
  29. package/dist/commerce.js +0 -0
  30. package/dist/config-BX3beTpM.js +15 -0
  31. package/dist/config-BX3beTpM.js.map +1 -0
  32. package/dist/constants-C0kT94tc.js +139 -0
  33. package/dist/constants-C0kT94tc.js.map +1 -0
  34. package/dist/csv-DKq_4OWU.js +55 -0
  35. package/dist/csv-DKq_4OWU.js.map +1 -0
  36. package/dist/errors-ChzJS9al.js +16 -0
  37. package/dist/errors-ChzJS9al.js.map +1 -0
  38. package/dist/index.d.ts +13 -0
  39. package/dist/index.js +19 -0
  40. package/dist/index.js.map +1 -0
  41. package/dist/runtime.d.ts +681 -0
  42. package/dist/runtime.js +2060 -0
  43. package/dist/runtime.js.map +1 -0
  44. package/dist/schemas.d.ts +584 -0
  45. package/dist/schemas.js +315 -0
  46. package/dist/schemas.js.map +1 -0
  47. package/dist/server.d.ts +30 -0
  48. package/dist/server.js +54 -0
  49. package/dist/server.js.map +1 -0
  50. package/dist/types.d.ts +284 -0
  51. package/dist/types.js +0 -0
  52. package/package.json +83 -4
@@ -0,0 +1,2060 @@
1
+ import { a as adminPages, i as PLUGIN_VERSION, n as MAX_DOCUMENT_BYTES, o as storage, r as PLUGIN_ID } from "./constants-C0kT94tc.js";
2
+ import { t as normalizeLmsOptions } from "./config-BX3beTpM.js";
3
+ import { assignmentSubmitSchema, catalogSchema, certificateActionSchema, certificateRevokeSchema, cohortSaveSchema, courseIdSchema, courseSaveSchema, discussionSchema, enrollmentAdminSchema, enrollmentRequestSchema, gradeSchema, idSchema, keySchema, lessonIdSchema, moderateSchema, noteSchema, pageSchema, quizSubmitSchema, reviewSchema, settingsSchema } from "./schemas.js";
4
+ import { n as invariant, t as LmsError } from "./errors-ChzJS9al.js";
5
+ import { n as enrollmentCsvLines, t as enrollmentCsvHeader } from "./csv-DKq_4OWU.js";
6
+ import { definePlugin, definePluginRoute, pluginResponse } from "emdash";
7
+ import { z } from "zod";
8
+
9
+ //#region src/store.ts
10
+ function collections(ctx) {
11
+ return ctx.storage;
12
+ }
13
+ function enrollmentKey(courseId, userId) {
14
+ return `${courseId}:${userId}`;
15
+ }
16
+ function assertSize(data) {
17
+ invariant(new TextEncoder().encode(JSON.stringify(data)).byteLength <= MAX_DOCUMENT_BYTES, "DOCUMENT_TOO_LARGE", "This record exceeds the LMS storage limit. Split the course into smaller courses.", 413);
18
+ }
19
+ async function change(store, id, update) {
20
+ for (let attempt = 0; attempt < 8; attempt++) {
21
+ const current = await store.getVersioned(id);
22
+ const { value, result } = await update(current?.value ?? null);
23
+ assertSize(value);
24
+ if ((await store.compareAndSet(id, current?.revision ?? null, value)).applied) return result;
25
+ }
26
+ throw new LmsError("CONFLICT", "Another request changed this record. Please try again.", 409);
27
+ }
28
+ async function queryPage(store, options = {}) {
29
+ const page = await store.query(options);
30
+ return {
31
+ ...page,
32
+ items: page.items.map((item) => item.data)
33
+ };
34
+ }
35
+ async function putOnce(store, id, value) {
36
+ assertSize(value);
37
+ await store.compareAndSet(id, null, value);
38
+ }
39
+
40
+ //#endregion
41
+ //#region src/curriculum.ts
42
+ function lessons(course) {
43
+ return course.modules.flatMap((module) => module.lessons);
44
+ }
45
+ function emptyProgress() {
46
+ return {
47
+ startedAt: null,
48
+ completedAt: null,
49
+ note: "",
50
+ quizAttempts: [],
51
+ assignments: []
52
+ };
53
+ }
54
+ function courseCard(course) {
55
+ const all = lessons(course);
56
+ return {
57
+ id: course.id,
58
+ slug: course.slug,
59
+ title: course.title,
60
+ summary: course.summary,
61
+ category: course.category,
62
+ tags: course.tags,
63
+ level: course.level,
64
+ language: course.language,
65
+ featuredImage: course.featuredImage,
66
+ instructorName: course.instructorName,
67
+ enrollmentMode: course.enrollmentMode,
68
+ lessonCount: all.length,
69
+ durationMinutes: all.reduce((sum, lesson) => sum + lesson.durationMinutes, 0)
70
+ };
71
+ }
72
+ function courseDetail(course) {
73
+ return {
74
+ prerequisites: [],
75
+ ...courseCard(course),
76
+ description: course.description,
77
+ outcomes: course.outcomes,
78
+ requirements: course.requirements,
79
+ sequential: course.sequential,
80
+ prerequisiteCourseIds: course.prerequisiteCourseIds,
81
+ enrollmentClosesAt: course.enrollmentClosesAt,
82
+ accessDays: course.accessDays,
83
+ certificateEnabled: course.certificateEnabled,
84
+ modules: course.modules.map((module) => ({
85
+ id: module.id,
86
+ title: module.title,
87
+ description: module.description,
88
+ releaseDays: module.releaseDays,
89
+ unlockAt: module.unlockAt,
90
+ lessons: module.lessons.map((lesson) => ({
91
+ id: lesson.id,
92
+ title: lesson.title,
93
+ summary: lesson.summary,
94
+ kind: lesson.kind,
95
+ durationMinutes: lesson.durationMinutes,
96
+ preview: lesson.preview,
97
+ required: lesson.required
98
+ }))
99
+ }))
100
+ };
101
+ }
102
+ function publicLesson(lesson) {
103
+ const { quiz, contentSource: _source, ...safe } = lesson;
104
+ return {
105
+ ...safe,
106
+ quiz: quiz ? {
107
+ passingPercent: quiz.passingPercent,
108
+ maxAttempts: quiz.maxAttempts,
109
+ timeLimitMinutes: quiz.timeLimitMinutes,
110
+ randomizeQuestions: quiz.randomizeQuestions,
111
+ randomizeOptions: quiz.randomizeOptions,
112
+ showFeedback: quiz.showFeedback,
113
+ questionCount: quiz.questions.length
114
+ } : null
115
+ };
116
+ }
117
+ function publicAttempt(attempt) {
118
+ const { quiz: _quiz, ...safe } = attempt;
119
+ return safe;
120
+ }
121
+ function effectiveAccess(enrollment, now = /* @__PURE__ */ new Date()) {
122
+ if (enrollment.status === "suspended" || enrollment.accessStatus === "suspended") return "suspended";
123
+ if (["rejected", "cancelled"].includes(enrollment.status) || enrollment.accessStatus === "revoked") return "revoked";
124
+ if (enrollment.status === "pending" || enrollment.accessStatus === "pending") return "pending";
125
+ if (enrollment.accessExpiresAt && now.getTime() >= Date.parse(enrollment.accessExpiresAt)) return "expired";
126
+ if (enrollment.accessStartsAt && now.getTime() < Date.parse(enrollment.accessStartsAt)) return "scheduled";
127
+ const grants = Object.values(enrollment.grants);
128
+ if (grants.some((grant) => grant.status === "granted" && (!grant.startsAt || now.getTime() >= Date.parse(grant.startsAt)) && (!grant.expiresAt || now.getTime() < Date.parse(grant.expiresAt)))) return "granted";
129
+ if (grants.some((grant) => grant.status === "granted" && grant.startsAt && now.getTime() < Date.parse(grant.startsAt) && (!grant.expiresAt || now.getTime() < Date.parse(grant.expiresAt)))) return "scheduled";
130
+ if (grants.some((grant) => grant.status === "suspended")) return "suspended";
131
+ if (grants.some((grant) => grant.status === "granted" && grant.expiresAt && now.getTime() >= Date.parse(grant.expiresAt))) return "expired";
132
+ return "revoked";
133
+ }
134
+ function publicEnrollment(enrollment, now = /* @__PURE__ */ new Date()) {
135
+ const { learnerEmail: _email, progress, ...safe } = enrollment;
136
+ return {
137
+ ...safe,
138
+ effectiveAccess: effectiveAccess(enrollment, now),
139
+ progress: Object.fromEntries(Object.entries(progress).map(([id, item]) => [id, {
140
+ ...item,
141
+ quizAttempts: item.quizAttempts.map(publicAttempt)
142
+ }]))
143
+ };
144
+ }
145
+ function progressSummary(course, enrollment) {
146
+ const required = enrollment?.completedAt ? enrollment.completionLessonIds : lessons(course).filter((lesson) => lesson.required).map((lesson) => lesson.id);
147
+ const completed = required.filter((id) => enrollment?.progress[id]?.completedAt).length;
148
+ return {
149
+ completed,
150
+ total: required.length,
151
+ percent: required.length ? Math.floor(completed / required.length * 100) : 0,
152
+ nextLessonId: lessons(course).find((lesson) => !enrollment?.progress[lesson.id]?.completedAt)?.id ?? null
153
+ };
154
+ }
155
+ function assertEnrollmentAccess(enrollment, now) {
156
+ invariant(enrollment && (enrollment.status === "active" || enrollment.status === "completed"), "ENROLLMENT_REQUIRED", "An active enrollment is required for this lesson.", 403);
157
+ invariant(enrollment.accessStatus === "granted", "ACCESS_RESTRICTED", "Your course access is not currently granted.", 403);
158
+ invariant(Object.values(enrollment.grants).some((grant) => grant.status === "granted" && (!grant.startsAt || now.getTime() >= Date.parse(grant.startsAt)) && (!grant.expiresAt || now.getTime() < Date.parse(grant.expiresAt))), "GRANT_REQUIRED", "Your course access grant has not started, expired, or been revoked.", 403);
159
+ invariant(!enrollment.accessStartsAt || now.getTime() >= Date.parse(enrollment.accessStartsAt), "COURSE_NOT_STARTED", "Your course access has not started yet.", 403);
160
+ invariant(!enrollment.accessExpiresAt || now.getTime() < Date.parse(enrollment.accessExpiresAt), "ACCESS_EXPIRED", "Your course access has expired.", 403);
161
+ }
162
+ function findLesson(course, lessonId) {
163
+ const lesson = lessons(course).find((item) => item.id === lessonId);
164
+ invariant(lesson, "NOT_FOUND", "Lesson not found.", 404);
165
+ return lesson;
166
+ }
167
+ function assertLessonAccess(course, lessonId, enrollment, now, allowPreview = false) {
168
+ const lesson = findLesson(course, lessonId);
169
+ if (allowPreview && lesson.preview && ![
170
+ "quiz",
171
+ "assignment",
172
+ "live"
173
+ ].includes(lesson.kind)) return lesson;
174
+ assertEnrollmentAccess(enrollment, now);
175
+ invariant(course.status !== "draft", "NOT_FOUND", "Course not found.", 404);
176
+ const module = course.modules.find((item) => item.lessons.some((entry) => entry.id === lessonId));
177
+ const releaseAt = Math.max(module.unlockAt ? Date.parse(module.unlockAt) : 0, Date.parse(enrollment.approvedAt ?? enrollment.enrolledAt) + module.releaseDays * 864e5);
178
+ invariant(now.getTime() >= releaseAt, "LESSON_LOCKED", "This module has not been released yet.", 403);
179
+ if (course.sequential) {
180
+ const all = lessons(course);
181
+ const index = all.findIndex((item) => item.id === lessonId);
182
+ invariant(all.slice(0, index).filter((item) => item.required).every((item) => enrollment.progress[item.id]?.completedAt), "PREREQUISITE_REQUIRED", "Complete the earlier required lessons first.", 403);
183
+ }
184
+ return lesson;
185
+ }
186
+ function shuffle(items, random = () => {
187
+ const value = new Uint32Array(1);
188
+ crypto.getRandomValues(value);
189
+ return value[0] / 4294967296;
190
+ }) {
191
+ const output = [...items];
192
+ for (let index = output.length - 1; index > 0; index--) {
193
+ const pick = Math.floor(random() * (index + 1));
194
+ [output[index], output[pick]] = [output[pick], output[index]];
195
+ }
196
+ return output;
197
+ }
198
+ function normalized(value) {
199
+ return value.normalize("NFKC").trim().toLocaleLowerCase("en").replace(/\s+/g, " ");
200
+ }
201
+ function gradeAnswers(questions, answers) {
202
+ const ids = new Set(questions.map((question) => question.id));
203
+ invariant(Object.keys(answers).every((id) => ids.has(id)), "INVALID_ANSWERS", "Answers contain an unknown question.");
204
+ const feedback = questions.map((question) => {
205
+ const response = answers[question.id];
206
+ const selected = Array.isArray(response) ? response : response === void 0 ? [] : [response];
207
+ invariant(new Set(selected).size === selected.length, "INVALID_ANSWERS", "Duplicate answer choices are not accepted.");
208
+ if (question.type !== "multiple") invariant(selected.length <= 1, "INVALID_ANSWERS", "This question accepts one answer.");
209
+ if (question.type !== "short") invariant(selected.every((answer) => question.options.some((option) => option.id === answer)), "INVALID_ANSWERS", "An answer contains an invalid option.");
210
+ const correct = question.type === "short" ? selected.length === 1 && question.correctAnswers.some((answer) => normalized(answer) === normalized(selected[0])) : selected.length === question.correctAnswers.length && selected.every((answer) => question.correctAnswers.includes(answer));
211
+ return {
212
+ questionId: question.id,
213
+ correct,
214
+ points: correct ? question.points : 0,
215
+ maxPoints: question.points,
216
+ explanation: question.explanation
217
+ };
218
+ });
219
+ const score = feedback.reduce((sum, item) => sum + item.points, 0);
220
+ const maxScore = questions.reduce((sum, question) => sum + question.points, 0);
221
+ return {
222
+ score,
223
+ maxScore,
224
+ percent: Math.round(score / maxScore * 1e4) / 100,
225
+ feedback
226
+ };
227
+ }
228
+
229
+ //#endregion
230
+ //#region src/service.ts
231
+ function parse(schema, input) {
232
+ const result = schema.safeParse(input);
233
+ if (!result.success) throw new LmsError("VALIDATION_ERROR", result.error.issues.map((issue) => `${issue.path.join(".") || "Input"}: ${issue.message}`).slice(0, 5).join(" "), 400);
234
+ return result.data;
235
+ }
236
+ function user(actor) {
237
+ invariant(actor, "UNAUTHORIZED", "Sign in to continue.", 401);
238
+ return actor;
239
+ }
240
+ var LmsService = class {
241
+ stores;
242
+ constructor(ctx, now = () => /* @__PURE__ */ new Date()) {
243
+ this.ctx = ctx;
244
+ this.now = now;
245
+ this.stores = collections(ctx);
246
+ }
247
+ time() {
248
+ return this.now().toISOString();
249
+ }
250
+ async settings() {
251
+ return settingsSchema.parse(await this.ctx.settings.get("configuration") ?? {});
252
+ }
253
+ async saveSettings(actor, input) {
254
+ invariant(user(actor).role >= 50, "FORBIDDEN", "Only administrators can change LMS settings.", 403);
255
+ const settings = parse(settingsSchema, input);
256
+ invariant(!settings.emailNotifications || this.ctx.email, "EMAIL_UNAVAILABLE", "Configure an email transport in EmDash before enabling LMS emails.");
257
+ await this.ctx.settings.set("configuration", settings);
258
+ await this.audit(actor, "settings.save", "configuration");
259
+ return settings;
260
+ }
261
+ async audit(actor, action, resourceId, details = {}) {
262
+ const id = crypto.randomUUID();
263
+ await this.stores.audit.put(id, {
264
+ id,
265
+ actorId: actor.id,
266
+ action,
267
+ resourceId,
268
+ createdAt: this.time(),
269
+ details
270
+ });
271
+ }
272
+ async course(id) {
273
+ const course = await this.stores.courses.get(id);
274
+ invariant(course, "NOT_FOUND", "Course not found.", 404);
275
+ return course;
276
+ }
277
+ async accessEnrollment(enrollment) {
278
+ if (!enrollment) return null;
279
+ const grants = Object.values(enrollment.grants).filter((grant) => grant.source === "cohort");
280
+ if (!grants.length) return enrollment;
281
+ const [memberships, cohorts] = await Promise.all([this.stores.cohort_enrollments.getMany(grants.map((grant) => enrollmentKey(grant.referenceId ?? "", enrollment.userId))), this.stores.cohorts.getMany(grants.map((grant) => grant.referenceId ?? ""))]);
282
+ const resolved = structuredClone(enrollment);
283
+ for (const grant of grants) {
284
+ const membership = memberships.get(enrollmentKey(grant.referenceId ?? "", enrollment.userId));
285
+ const cohort = cohorts.get(grant.referenceId ?? "");
286
+ if (membership?.status !== "active" || !cohort?.courseIds.includes(enrollment.courseId)) resolved.grants[grant.id].status = membership?.status === "suspended" ? "suspended" : "revoked";
287
+ else {
288
+ resolved.grants[grant.id].status = "granted";
289
+ resolved.grants[grant.id].startsAt = cohort.startsAt;
290
+ resolved.grants[grant.id].expiresAt = cohort.endsAt;
291
+ }
292
+ }
293
+ return resolved;
294
+ }
295
+ async enrollmentView(enrollment) {
296
+ return publicEnrollment(await this.accessEnrollment(enrollment), this.now());
297
+ }
298
+ async lessonAccess(course, lessonId, enrollment) {
299
+ return assertLessonAccess(course, lessonId, await this.accessEnrollment(enrollment), this.now());
300
+ }
301
+ instructor(course, actor) {
302
+ const current = user(actor);
303
+ invariant(current.role >= 50 || course.createdBy === current.id || course.instructorIds.includes(current.id), "FORBIDDEN", "You are not an instructor for this course.", 403);
304
+ return current;
305
+ }
306
+ async saveCourse(actor, input) {
307
+ const currentActor = user(actor);
308
+ const parsed = parse(courseSaveSchema, input);
309
+ const id = parsed.id ?? crypto.randomUUID();
310
+ const current = await this.stores.courses.getVersioned(id);
311
+ if (current) this.instructor(current.value, currentActor);
312
+ else invariant(currentActor.role >= 20, "FORBIDDEN", "Course authoring requires a contributor account or higher.", 403);
313
+ invariant((current?.revision ?? null) === parsed.expectedRevision, "CONFLICT", "The course changed since you opened it. Reload before saving.", 409);
314
+ if (parsed.data.status === "published") invariant(currentActor.role >= 50 || currentActor.role >= 30, "FORBIDDEN", "Publishing requires an author account or higher.", 403);
315
+ invariant(parsed.data.status !== "published" || parsed.data.commerce.accessModel === "free", "PAID_COURSES_DISABLED", "Payment processing is not enabled in this release. Publish free courses only.", 409);
316
+ invariant(!(await this.stores.courses.query({
317
+ where: { slug: parsed.data.slug },
318
+ limit: 1
319
+ })).items.some((item) => item.id !== id), "SLUG_TAKEN", "A course already uses this URL.", 409);
320
+ await this.assertPrerequisiteGraph(id, parsed.data.prerequisiteCourseIds);
321
+ if (current && await this.stores.enrollments.count({ courseId: id })) {
322
+ const nextIds = new Set(parsed.data.modules.flatMap((module) => module.lessons.map((lesson) => lesson.id)));
323
+ invariant(lessons(current.value).every((lesson) => nextIds.has(lesson.id)), "CURRICULUM_IN_USE", "Enrolled courses must keep existing lesson IDs. Archive the course or create a new edition to remove lessons.", 409);
324
+ }
325
+ const course = {
326
+ ...parsed.data,
327
+ id,
328
+ searchTitle: parsed.data.title.toLocaleLowerCase("en"),
329
+ createdBy: current?.value.createdBy ?? currentActor.id,
330
+ createdAt: current?.value.createdAt ?? this.time(),
331
+ updatedAt: this.time(),
332
+ schemaVersion: 1
333
+ };
334
+ assertSize(course);
335
+ const saved = await this.stores.courses.compareAndSet(id, current?.revision ?? null, course);
336
+ invariant(saved.applied, "CONFLICT", "The course changed while saving. Reload before saving.", 409);
337
+ await this.audit(currentActor, "course.save", id, { status: course.status });
338
+ return {
339
+ course,
340
+ revision: saved.revision
341
+ };
342
+ }
343
+ async assertPrerequisiteGraph(courseId, prerequisites) {
344
+ const visited = /* @__PURE__ */ new Set();
345
+ const visit = async (id) => {
346
+ invariant(id !== courseId, "PREREQUISITE_CYCLE", "Course prerequisites cannot form a cycle.");
347
+ if (visited.has(id)) return;
348
+ invariant(visited.size < 100, "PREREQUISITE_GRAPH_TOO_LARGE", "The prerequisite chain is too long.");
349
+ visited.add(id);
350
+ const course = await this.course(id);
351
+ for (const next of course.prerequisiteCourseIds) await visit(next);
352
+ };
353
+ for (const id of prerequisites) await visit(id);
354
+ }
355
+ async editableCourse(actor, id) {
356
+ const current = await this.stores.courses.getVersioned(id);
357
+ invariant(current, "NOT_FOUND", "Course not found.", 404);
358
+ this.instructor(current.value, actor);
359
+ return {
360
+ course: current.value,
361
+ revision: current.revision
362
+ };
363
+ }
364
+ async adminCourses(actor, options = {}) {
365
+ const current = user(actor);
366
+ const page = await queryPage(this.stores.courses, {
367
+ where: options.status ? { status: options.status } : {},
368
+ orderBy: { updatedAt: "desc" },
369
+ limit: options.limit ?? 24,
370
+ cursor: options.cursor
371
+ });
372
+ return {
373
+ ...page,
374
+ items: page.items.filter((course) => current.role >= 50 || course.createdBy === current.id || course.instructorIds.includes(current.id))
375
+ };
376
+ }
377
+ async catalog(input) {
378
+ const options = parse(catalogSchema, input);
379
+ const where = { status: "published" };
380
+ if (options.q.trim()) where.searchTitle = { startsWith: options.q.trim().toLocaleLowerCase("en") };
381
+ if (options.category) where.category = options.category;
382
+ if (options.language) where.language = options.language;
383
+ if (options.level && options.level !== "all") where.level = { in: [options.level, "all"] };
384
+ const page = await queryPage(this.stores.courses, {
385
+ where,
386
+ orderBy: { title: "asc" },
387
+ limit: options.limit,
388
+ cursor: options.cursor
389
+ });
390
+ return {
391
+ ...page,
392
+ items: page.items.map(courseCard)
393
+ };
394
+ }
395
+ async publicCourse(slug) {
396
+ const page = await this.stores.courses.query({
397
+ where: {
398
+ slug,
399
+ status: "published"
400
+ },
401
+ limit: 1
402
+ });
403
+ invariant(page.items[0], "NOT_FOUND", "Course not found.", 404);
404
+ return this.detail(page.items[0].data);
405
+ }
406
+ async detail(course) {
407
+ const prerequisites = await this.stores.courses.getMany(course.prerequisiteCourseIds);
408
+ return {
409
+ ...courseDetail(course),
410
+ prerequisites: course.prerequisiteCourseIds.map((id) => {
411
+ const value = prerequisites.get(id);
412
+ return {
413
+ id,
414
+ title: value?.title ?? "Prerequisite course",
415
+ slug: value?.status === "published" ? value.slug : null
416
+ };
417
+ })
418
+ };
419
+ }
420
+ async preview(courseId, lessonId) {
421
+ const course = await this.course(courseId);
422
+ invariant(course.status === "published", "NOT_FOUND", "Course not found.", 404);
423
+ const lesson = findLesson(course, lessonId);
424
+ invariant(lesson.preview && ![
425
+ "quiz",
426
+ "assignment",
427
+ "live"
428
+ ].includes(lesson.kind), "PREVIEW_UNAVAILABLE", "This lesson is available to enrolled learners.", 403);
429
+ return {
430
+ course: courseDetail(course),
431
+ lesson: publicLesson(await this.resolveContent(lesson))
432
+ };
433
+ }
434
+ async resolveContent(lesson) {
435
+ if (!lesson.contentSource) return lesson;
436
+ invariant(this.ctx.content, "CONTENT_UNAVAILABLE", "Content integration is unavailable.", 503);
437
+ const entry = await this.ctx.content.get(lesson.contentSource.collection, lesson.contentSource.id);
438
+ invariant(entry?.status === "published", "CONTENT_UNAVAILABLE", "The linked lesson content is not published.", 404);
439
+ const body = entry.data[lesson.contentSource.field];
440
+ invariant(Array.isArray(body) || typeof body === "string", "CONTENT_UNAVAILABLE", "The linked lesson field is unavailable.", 404);
441
+ if (Array.isArray(body)) return {
442
+ ...lesson,
443
+ body: "",
444
+ portableText: body
445
+ };
446
+ return {
447
+ ...lesson,
448
+ body,
449
+ portableText: []
450
+ };
451
+ }
452
+ async assertPrerequisites(course, actorId) {
453
+ for (const id of course.prerequisiteCourseIds) invariant((await this.stores.enrollments.get(enrollmentKey(id, actorId)))?.completedAt, "COURSE_PREREQUISITE_REQUIRED", "Complete the prerequisite courses before enrolling.", 403);
454
+ }
455
+ newEnrollment(course, actor, status) {
456
+ const now = this.time();
457
+ const active = status === "active";
458
+ return {
459
+ id: enrollmentKey(course.id, actor.id),
460
+ courseId: course.id,
461
+ userId: actor.id,
462
+ learnerName: actor.name || actor.email.split("@")[0] || "Learner",
463
+ learnerEmail: actor.email,
464
+ status,
465
+ accessStatus: active ? "granted" : "pending",
466
+ accessSource: "free",
467
+ grants: { free: {
468
+ id: "free",
469
+ source: "free",
470
+ referenceId: null,
471
+ status: active ? "granted" : "pending",
472
+ startsAt: null,
473
+ expiresAt: active && course.accessDays ? new Date(this.now().getTime() + course.accessDays * 864e5).toISOString() : null,
474
+ grantedAt: active ? now : null,
475
+ grantedBy: null
476
+ } },
477
+ cohortIds: [],
478
+ acquisition: {
479
+ orderId: null,
480
+ offerId: course.commerce.offerId,
481
+ paymentStatus: "not_required",
482
+ amountMinor: null,
483
+ currency: null,
484
+ providerId: null,
485
+ providerPaymentId: null
486
+ },
487
+ approvedBy: null,
488
+ decisionAt: active ? now : null,
489
+ decisionReason: null,
490
+ enrolledAt: now,
491
+ approvedAt: active ? now : null,
492
+ completedAt: null,
493
+ accessStartsAt: null,
494
+ accessExpiresAt: null,
495
+ cohortId: null,
496
+ progress: {},
497
+ certificate: null,
498
+ completionLessonIds: [],
499
+ lastActivityAt: now,
500
+ schemaVersion: 1
501
+ };
502
+ }
503
+ async enroll(actor, courseId, options = {}) {
504
+ const current = user(actor);
505
+ const course = await this.course(courseId);
506
+ invariant(course.status === "published", "NOT_FOUND", "Course not found.", 404);
507
+ invariant(course.commerce.accessModel === "free", "PAID_COURSES_DISABLED", "Payment processing is not enabled for this course.", 403);
508
+ const cohort = options.cohortId ? await this.stores.cohorts.get(options.cohortId) : null;
509
+ if (options.cohortId) invariant(cohort && cohort.courseIds.includes(courseId), "NOT_FOUND", "This course is not part of that cohort.", 404);
510
+ if (cohort) invariant((await this.stores.cohort_enrollments.get(enrollmentKey(cohort.id, current.id)))?.status === "active", "COHORT_APPROVAL_REQUIRED", "Request cohort membership and wait for administrator approval.", 403);
511
+ const id = enrollmentKey(courseId, current.id);
512
+ const existing = await this.stores.enrollments.get(id);
513
+ if (!cohort && existing && [
514
+ "active",
515
+ "completed",
516
+ "pending"
517
+ ].includes(existing.status)) return await this.enrollmentView(existing);
518
+ invariant(course.enrollmentMode !== "invite" || cohort, "INVITATION_REQUIRED", "An administrator must enroll you in this course.", 403);
519
+ invariant(!course.enrollmentClosesAt || this.now().getTime() < Date.parse(course.enrollmentClosesAt), "ENROLLMENT_CLOSED", "Enrollment for this course is closed.", 403);
520
+ await this.assertPrerequisites(course, current.id);
521
+ const enrollment = await change(this.stores.enrollments, id, async (stored) => {
522
+ invariant(!stored || ![
523
+ "suspended",
524
+ "cancelled",
525
+ "rejected"
526
+ ].includes(stored.status), "ENROLLMENT_RESTRICTED", "Contact an administrator to restore your enrollment.", 403);
527
+ const next = structuredClone(stored ?? this.newEnrollment(course, current, !cohort && course.enrollmentMode === "approval" ? "pending" : "active"));
528
+ if (cohort) {
529
+ next.cohortId = cohort.id;
530
+ next.cohortIds = [...new Set([...next.cohortIds, cohort.id])];
531
+ if (!stored || stored.accessStatus !== "granted") next.accessSource = "cohort";
532
+ if (!stored) delete next.grants.free;
533
+ next.status = next.completedAt ? "completed" : "active";
534
+ next.accessStatus = "granted";
535
+ next.approvedAt ??= this.time();
536
+ next.grants[`cohort:${cohort.id}`] = {
537
+ id: `cohort:${cohort.id}`,
538
+ source: "cohort",
539
+ referenceId: cohort.id,
540
+ status: "granted",
541
+ startsAt: cohort.startsAt,
542
+ expiresAt: cohort.endsAt,
543
+ grantedAt: this.time(),
544
+ grantedBy: null
545
+ };
546
+ }
547
+ return {
548
+ value: next,
549
+ result: next
550
+ };
551
+ });
552
+ await this.notify(enrollment, "enrolled", enrollment.status === "pending" ? "Enrollment requested" : "You are enrolled", `${course.title}: ${enrollment.status === "pending" ? "an administrator will review your request." : "your learning journey is ready."}`);
553
+ return await this.enrollmentView(enrollment);
554
+ }
555
+ async adminEnrollment(actor, input) {
556
+ const parsed = parse(enrollmentAdminSchema, input);
557
+ const course = await this.course(parsed.courseId);
558
+ const currentActor = this.instructor(course, actor);
559
+ invariant(currentActor.role >= 50, "FORBIDDEN", "Only administrators can make enrollment decisions.", 403);
560
+ invariant(this.ctx.users, "USERS_UNAVAILABLE", "The user directory is unavailable.", 503);
561
+ const target = await this.ctx.users.get(parsed.userId);
562
+ invariant(target, "NOT_FOUND", "Learner account not found.", 404);
563
+ invariant(!parsed.accessStartsAt || !parsed.accessExpiresAt || Date.parse(parsed.accessExpiresAt) > Date.parse(parsed.accessStartsAt), "INVALID_ACCESS_WINDOW", "Access expiry must follow its start.");
564
+ if (parsed.cohortId) {
565
+ const cohort = await this.stores.cohorts.get(parsed.cohortId);
566
+ invariant(cohort && cohort.courseIds.includes(course.id), "INVALID_COHORT", "This course must belong to the selected cohort.");
567
+ }
568
+ if (parsed.status === "active") {
569
+ invariant(course.status !== "draft", "COURSE_NOT_PUBLISHED", "Publish the course before enrolling learners.", 409);
570
+ invariant(course.commerce.accessModel === "free", "PAID_COURSES_DISABLED", "Paid access is not enabled in this release.", 403);
571
+ await this.assertPrerequisites(course, target.id);
572
+ }
573
+ const cohort = parsed.cohortId ? await this.stores.cohorts.get(parsed.cohortId) : null;
574
+ if (cohort && parsed.status === "active") invariant((await this.stores.cohort_enrollments.get(enrollmentKey(cohort.id, target.id)))?.status === "active", "COHORT_APPROVAL_REQUIRED", "Approve cohort membership before granting cohort access.", 403);
575
+ const settings = await this.settings();
576
+ const enrollment = await change(this.stores.enrollments, enrollmentKey(course.id, target.id), async (stored) => {
577
+ const next = structuredClone(stored ?? this.newEnrollment(course, target, parsed.status));
578
+ const firstApproval = parsed.status === "active" && !next.approvedAt;
579
+ next.status = parsed.status === "active" && next.completedAt ? "completed" : parsed.status;
580
+ next.accessStatus = parsed.status === "active" ? "granted" : parsed.status === "suspended" ? "suspended" : "revoked";
581
+ next.approvedBy = parsed.status === "active" ? currentActor.id : next.approvedBy;
582
+ next.decisionAt = this.time();
583
+ next.decisionReason = parsed.reason || null;
584
+ next.accessSource = stored?.approvedAt ? stored.accessSource : cohort ? "cohort" : "manual";
585
+ if (firstApproval) next.approvedAt = this.time();
586
+ if (parsed.cohortId !== void 0) next.cohortId = parsed.cohortId;
587
+ if (!cohort && parsed.accessStartsAt !== void 0) next.accessStartsAt = parsed.accessStartsAt;
588
+ if (!cohort && parsed.accessExpiresAt !== void 0) next.accessExpiresAt = parsed.accessExpiresAt;
589
+ if (parsed.status === "active") {
590
+ if (!stored) delete next.grants.free;
591
+ const grantId = cohort ? `cohort:${cohort.id}` : "manual";
592
+ const previous = next.grants[grantId];
593
+ next.grants[grantId] = {
594
+ id: grantId,
595
+ source: cohort ? "cohort" : "manual",
596
+ referenceId: cohort?.id ?? null,
597
+ status: "granted",
598
+ startsAt: cohort?.startsAt ?? null,
599
+ expiresAt: cohort ? cohort.endsAt : parsed.accessExpiresAt !== void 0 ? parsed.accessExpiresAt : previous && (!previous.expiresAt || Date.parse(previous.expiresAt) > this.now().getTime()) ? previous.expiresAt : course.accessDays ? new Date(this.now().getTime() + course.accessDays * 864e5).toISOString() : null,
600
+ grantedAt: previous?.grantedAt ?? this.time(),
601
+ grantedBy: currentActor.id
602
+ };
603
+ if (cohort) next.cohortIds = [...new Set([...next.cohortIds, cohort.id])];
604
+ }
605
+ invariant(!next.accessStartsAt || !next.accessExpiresAt || Date.parse(next.accessExpiresAt) > Date.parse(next.accessStartsAt), "INVALID_ACCESS_WINDOW", "Access expiry must follow its start.");
606
+ next.lastActivityAt = this.time();
607
+ if (parsed.status === "active") this.finish(course, next, settings);
608
+ return {
609
+ value: next,
610
+ result: next
611
+ };
612
+ });
613
+ await this.audit(currentActor, "enrollment.update", enrollment.id, { status: enrollment.status });
614
+ await this.notify(enrollment, `enrollment-${enrollment.status}-${enrollment.decisionAt}`, "Enrollment updated", `${course.title}: your enrollment is ${enrollment.status}.`);
615
+ await this.projectCompletion(enrollment);
616
+ return this.enrollmentView(enrollment);
617
+ }
618
+ async learnerCourse(actor, courseId) {
619
+ const current = user(actor);
620
+ const course = await this.course(courseId);
621
+ const enrollment = await this.stores.enrollments.get(enrollmentKey(courseId, current.id));
622
+ invariant(course.status === "published" || course.status === "archived" && enrollment, "NOT_FOUND", "Course not found.", 404);
623
+ if (enrollment?.completedAt) await this.projectCompletion(enrollment);
624
+ return {
625
+ course: await this.detail(course),
626
+ enrollment: enrollment ? await this.enrollmentView(enrollment) : null,
627
+ progress: progressSummary(course, enrollment)
628
+ };
629
+ }
630
+ async learnerCourseBySlug(actor, slug) {
631
+ user(actor);
632
+ const page = await this.stores.courses.query({
633
+ where: { slug },
634
+ limit: 1
635
+ });
636
+ invariant(page.items[0], "NOT_FOUND", "Course not found.", 404);
637
+ return this.learnerCourse(actor, page.items[0].id);
638
+ }
639
+ async dashboard(actor, options = {}) {
640
+ const current = user(actor);
641
+ const page = await queryPage(this.stores.enrollments, {
642
+ where: { userId: current.id },
643
+ orderBy: { enrolledAt: "desc" },
644
+ limit: options.limit ?? 24,
645
+ cursor: options.cursor
646
+ });
647
+ const courses = await this.stores.courses.getMany(page.items.map((entry) => entry.courseId));
648
+ const items = (await Promise.all(page.items.map(async (enrollment) => {
649
+ if (enrollment.completedAt) await this.projectCompletion(enrollment);
650
+ const course = courses.get(enrollment.courseId);
651
+ return course ? {
652
+ course: courseCard(course),
653
+ enrollment: await this.enrollmentView(enrollment),
654
+ progress: progressSummary(course, enrollment)
655
+ } : null;
656
+ }))).filter((row) => row !== null);
657
+ return {
658
+ ...page,
659
+ items
660
+ };
661
+ }
662
+ async learnerLesson(actor, courseId, lessonId) {
663
+ const current = user(actor);
664
+ const course = await this.course(courseId);
665
+ const enrollment = await this.stores.enrollments.get(enrollmentKey(courseId, current.id));
666
+ const lesson = await this.lessonAccess(course, lessonId, enrollment);
667
+ return {
668
+ course: courseDetail(course),
669
+ lesson: publicLesson(await this.resolveContent(lesson)),
670
+ enrollment: await this.enrollmentView(enrollment),
671
+ progress: progressSummary(course, enrollment)
672
+ };
673
+ }
674
+ async startLesson(actor, courseId, lessonId) {
675
+ const current = user(actor);
676
+ const course = await this.course(courseId);
677
+ const enrollment = await change(this.stores.enrollments, enrollmentKey(courseId, current.id), async (stored) => {
678
+ await this.lessonAccess(course, lessonId, stored);
679
+ const next = structuredClone(stored);
680
+ const progress = next.progress[lessonId] ?? emptyProgress();
681
+ progress.startedAt ??= this.time();
682
+ next.progress[lessonId] = progress;
683
+ next.lastActivityAt = this.time();
684
+ return {
685
+ value: next,
686
+ result: next
687
+ };
688
+ });
689
+ return await this.enrollmentView(enrollment);
690
+ }
691
+ async completeLesson(actor, courseId, lessonId) {
692
+ const current = user(actor);
693
+ const course = await this.course(courseId);
694
+ const settings = await this.settings();
695
+ const enrollment = await change(this.stores.enrollments, enrollmentKey(courseId, current.id), async (stored) => {
696
+ const lesson = await this.lessonAccess(course, lessonId, stored);
697
+ invariant(!["quiz", "assignment"].includes(lesson.kind), "ASSESSMENT_REQUIRED", "Pass the quiz or assignment to complete this lesson.", 403);
698
+ const next = structuredClone(stored);
699
+ const progress = next.progress[lessonId] ?? emptyProgress();
700
+ invariant(progress.startedAt, "LESSON_NOT_STARTED", "Start the lesson before marking it complete.");
701
+ if (lesson.kind === "live") invariant(lesson.liveStartsAt && this.now().getTime() >= Date.parse(lesson.liveStartsAt), "LIVE_NOT_STARTED", "The live session has not started yet.", 403);
702
+ invariant(this.now().getTime() - Date.parse(progress.startedAt) >= lesson.minStudySeconds * 1e3, "STUDY_TIME_REQUIRED", "Spend the minimum study time on this lesson before completing it.", 403);
703
+ progress.completedAt ??= this.time();
704
+ next.progress[lessonId] = progress;
705
+ this.finish(course, next, settings);
706
+ return {
707
+ value: next,
708
+ result: next
709
+ };
710
+ });
711
+ await this.projectCompletion(enrollment);
712
+ return {
713
+ enrollment: await this.enrollmentView(enrollment),
714
+ progress: progressSummary(course, enrollment)
715
+ };
716
+ }
717
+ finish(course, enrollment, settings) {
718
+ enrollment.lastActivityAt = this.time();
719
+ const required = lessons(course).filter((lesson) => lesson.required);
720
+ if (enrollment.completedAt || !required.length || !required.every((lesson) => enrollment.progress[lesson.id]?.completedAt)) return;
721
+ enrollment.status = "completed";
722
+ enrollment.completedAt = this.time();
723
+ enrollment.completionLessonIds = required.map((lesson) => lesson.id);
724
+ if (course.certificateEnabled) enrollment.certificate = {
725
+ id: crypto.randomUUID(),
726
+ courseId: course.id,
727
+ courseTitle: course.title,
728
+ userId: enrollment.userId,
729
+ learnerName: enrollment.learnerName,
730
+ issuerName: settings.issuerName,
731
+ issuedAt: this.time(),
732
+ shared: false,
733
+ revokedAt: null,
734
+ revocationReason: null
735
+ };
736
+ }
737
+ async projectCompletion(enrollment) {
738
+ if (enrollment.certificate) await putOnce(this.stores.certificates, enrollment.certificate.id, {
739
+ enrollmentId: enrollment.id,
740
+ courseId: enrollment.courseId,
741
+ userId: enrollment.userId
742
+ });
743
+ if (enrollment.completedAt) await this.notify(enrollment, "completed", "Course complete", "You have completed your course. Your achievement is saved in My Learning.");
744
+ }
745
+ async startQuiz(actor, courseId, lessonId) {
746
+ const current = user(actor);
747
+ const course = await this.course(courseId);
748
+ const result = await change(this.stores.enrollments, enrollmentKey(courseId, current.id), async (stored) => {
749
+ const lesson = await this.lessonAccess(course, lessonId, stored);
750
+ invariant(lesson.kind === "quiz" && lesson.quiz, "NOT_A_QUIZ", "This lesson has no quiz.");
751
+ const next = structuredClone(stored);
752
+ const progress = next.progress[lessonId] ?? emptyProgress();
753
+ progress.startedAt ??= this.time();
754
+ const existing = progress.quizAttempts.find((attempt) => attempt.status === "in_progress");
755
+ if (existing && (!existing.expiresAt || this.now().getTime() < Date.parse(existing.expiresAt))) return {
756
+ value: next,
757
+ result: {
758
+ attempt: existing,
759
+ blocked: false
760
+ }
761
+ };
762
+ if (existing) {
763
+ existing.status = "expired";
764
+ existing.quiz = null;
765
+ existing.submittedAt = this.time();
766
+ }
767
+ next.progress[lessonId] = progress;
768
+ if (progress.quizAttempts.length >= lesson.quiz.maxAttempts || progress.completedAt) return {
769
+ value: next,
770
+ result: {
771
+ attempt: null,
772
+ blocked: true
773
+ }
774
+ };
775
+ const quiz = structuredClone(lesson.quiz);
776
+ const questions = (quiz.randomizeQuestions ? shuffle(quiz.questions) : quiz.questions).map(({ correctAnswers: _correct, explanation: _explanation, ...question }) => ({
777
+ ...question,
778
+ options: quiz.randomizeOptions ? shuffle(question.options) : question.options
779
+ }));
780
+ const attempt = {
781
+ id: crypto.randomUUID(),
782
+ startedAt: this.time(),
783
+ expiresAt: quiz.timeLimitMinutes ? new Date(this.now().getTime() + quiz.timeLimitMinutes * 6e4).toISOString() : null,
784
+ status: "in_progress",
785
+ quiz,
786
+ questions,
787
+ submittedAt: null,
788
+ score: null,
789
+ maxScore: null,
790
+ percent: null,
791
+ passed: false,
792
+ feedback: [],
793
+ answers: {}
794
+ };
795
+ progress.quizAttempts.push(attempt);
796
+ next.lastActivityAt = this.time();
797
+ return {
798
+ value: next,
799
+ result: {
800
+ attempt,
801
+ blocked: false
802
+ }
803
+ };
804
+ });
805
+ invariant(result.attempt && !result.blocked, "ATTEMPT_LIMIT", "No further quiz attempts are available. Contact an instructor.", 403);
806
+ return publicAttempt(result.attempt);
807
+ }
808
+ async submitQuiz(actor, input) {
809
+ const current = user(actor);
810
+ const parsed = parse(quizSubmitSchema, input);
811
+ const course = await this.course(parsed.courseId);
812
+ const settings = await this.settings();
813
+ const result = await change(this.stores.enrollments, enrollmentKey(course.id, current.id), async (stored) => {
814
+ await this.lessonAccess(course, parsed.lessonId, stored);
815
+ const next = structuredClone(stored);
816
+ const progress = next.progress[parsed.lessonId];
817
+ const attempt = progress?.quizAttempts.find((item) => item.id === parsed.attemptId);
818
+ invariant(attempt && progress, "NOT_FOUND", "Quiz attempt not found.", 404);
819
+ if (attempt.status !== "in_progress") return {
820
+ value: next,
821
+ result: {
822
+ enrollment: next,
823
+ attempt,
824
+ expired: attempt.status === "expired"
825
+ }
826
+ };
827
+ if (attempt.expiresAt && this.now().getTime() >= Date.parse(attempt.expiresAt)) {
828
+ attempt.status = "expired";
829
+ attempt.quiz = null;
830
+ attempt.submittedAt = this.time();
831
+ return {
832
+ value: next,
833
+ result: {
834
+ enrollment: next,
835
+ attempt,
836
+ expired: true
837
+ }
838
+ };
839
+ }
840
+ invariant(attempt.quiz, "INVALID_ATTEMPT", "This attempt cannot be graded.", 409);
841
+ const graded = gradeAnswers(attempt.quiz.questions, parsed.answers);
842
+ attempt.passed = graded.score * 100 >= graded.maxScore * attempt.quiz.passingPercent;
843
+ attempt.feedback = attempt.quiz.showFeedback === "after_submit" || attempt.quiz.showFeedback === "after_pass" && attempt.passed ? graded.feedback : [];
844
+ attempt.score = graded.score;
845
+ attempt.maxScore = graded.maxScore;
846
+ attempt.percent = graded.percent;
847
+ attempt.answers = parsed.answers;
848
+ attempt.status = "submitted";
849
+ attempt.submittedAt = this.time();
850
+ attempt.quiz = null;
851
+ if (attempt.passed) progress.completedAt ??= this.time();
852
+ this.finish(course, next, settings);
853
+ return {
854
+ value: next,
855
+ result: {
856
+ enrollment: next,
857
+ attempt,
858
+ expired: false
859
+ }
860
+ };
861
+ });
862
+ invariant(!result.expired, "QUIZ_EXPIRED", "The quiz time limit expired. Start a new attempt if one is available.", 409);
863
+ await this.projectCompletion(result.enrollment);
864
+ return {
865
+ attempt: publicAttempt(result.attempt),
866
+ enrollment: await this.enrollmentView(result.enrollment),
867
+ progress: progressSummary(course, result.enrollment)
868
+ };
869
+ }
870
+ async saveQuizDraft(actor, input) {
871
+ const current = user(actor);
872
+ const parsed = parse(quizSubmitSchema, input);
873
+ const course = await this.course(parsed.courseId);
874
+ await change(this.stores.enrollments, enrollmentKey(course.id, current.id), async (stored) => {
875
+ await this.lessonAccess(course, parsed.lessonId, stored);
876
+ const next = structuredClone(stored);
877
+ const attempt = next.progress[parsed.lessonId]?.quizAttempts.find((item) => item.id === parsed.attemptId);
878
+ invariant(attempt?.status === "in_progress" && attempt.quiz, "ATTEMPT_CLOSED", "This quiz attempt is closed.", 409);
879
+ invariant(!attempt.expiresAt || this.now().getTime() < Date.parse(attempt.expiresAt), "QUIZ_EXPIRED", "This quiz attempt has expired.", 409);
880
+ gradeAnswers(attempt.quiz.questions, parsed.answers);
881
+ attempt.answers = parsed.answers;
882
+ return {
883
+ value: next,
884
+ result: true
885
+ };
886
+ });
887
+ return { saved: true };
888
+ }
889
+ async submitAssignment(actor, input) {
890
+ const current = user(actor);
891
+ const parsed = parse(assignmentSubmitSchema, input);
892
+ const course = await this.course(parsed.courseId);
893
+ const enrollment = await change(this.stores.enrollments, enrollmentKey(course.id, current.id), async (stored) => {
894
+ const lesson = await this.lessonAccess(course, parsed.lessonId, stored);
895
+ invariant(lesson.kind === "assignment" && lesson.assignment, "NOT_AN_ASSIGNMENT", "This lesson has no assignment.");
896
+ invariant(!lesson.assignment.dueAt || this.now().getTime() <= Date.parse(lesson.assignment.dueAt), "ASSIGNMENT_CLOSED", "The assignment deadline has passed.", 403);
897
+ const next = structuredClone(stored);
898
+ const progress = next.progress[parsed.lessonId] ?? emptyProgress();
899
+ const last = progress.assignments.at(-1);
900
+ invariant(!progress.completedAt, "ASSIGNMENT_PASSED", "This assignment has already been passed.", 409);
901
+ invariant(!last || last.status === "graded" && lesson.assignment.allowResubmission, "SUBMISSION_PENDING", "Wait for grading before submitting again.", 409);
902
+ invariant(progress.assignments.length < 10, "SUBMISSION_LIMIT", "The assignment submission limit has been reached.", 403);
903
+ progress.startedAt ??= this.time();
904
+ progress.assignments.push({
905
+ id: crypto.randomUUID(),
906
+ body: parsed.body,
907
+ attachmentUrl: parsed.attachmentUrl,
908
+ submittedAt: this.time(),
909
+ status: "submitted",
910
+ maxPoints: lesson.assignment.maxPoints,
911
+ passingPoints: lesson.assignment.passingPoints,
912
+ points: null,
913
+ feedback: "",
914
+ gradedAt: null,
915
+ gradedBy: null
916
+ });
917
+ next.progress[parsed.lessonId] = progress;
918
+ next.lastActivityAt = this.time();
919
+ return {
920
+ value: next,
921
+ result: next
922
+ };
923
+ });
924
+ return await this.enrollmentView(enrollment);
925
+ }
926
+ async gradeAssignment(actor, input) {
927
+ const parsed = parse(gradeSchema, input);
928
+ const course = await this.course(parsed.courseId);
929
+ const current = this.instructor(course, actor);
930
+ const settings = await this.settings();
931
+ const enrollment = await change(this.stores.enrollments, enrollmentKey(course.id, parsed.userId), async (stored) => {
932
+ invariant(stored, "NOT_FOUND", "Enrollment not found.", 404);
933
+ const next = structuredClone(stored);
934
+ const progress = next.progress[parsed.lessonId];
935
+ const submission = progress?.assignments.find((item) => item.id === parsed.submissionId);
936
+ invariant(submission && progress, "NOT_FOUND", "Assignment submission not found.", 404);
937
+ invariant(submission.status === "submitted", "ALREADY_GRADED", "This submission has already been graded.", 409);
938
+ invariant(parsed.points <= submission.maxPoints, "INVALID_GRADE", "The grade cannot exceed the assignment's maximum points.");
939
+ submission.points = parsed.points;
940
+ submission.feedback = parsed.feedback;
941
+ submission.status = "graded";
942
+ submission.gradedAt = this.time();
943
+ submission.gradedBy = current.id;
944
+ if (parsed.points >= submission.passingPoints) progress.completedAt ??= this.time();
945
+ const access = effectiveAccess(await this.accessEnrollment(next), this.now());
946
+ if (["active", "completed"].includes(next.status) && ![
947
+ "suspended",
948
+ "revoked",
949
+ "pending"
950
+ ].includes(access)) this.finish(course, next, settings);
951
+ return {
952
+ value: next,
953
+ result: next
954
+ };
955
+ });
956
+ await this.projectCompletion(enrollment);
957
+ await this.notify(enrollment, `graded-${parsed.submissionId}`, "Assignment graded", "Your assignment feedback is ready in My Learning.");
958
+ await this.audit(current, "assignment.grade", enrollment.id, {
959
+ lessonId: parsed.lessonId,
960
+ points: parsed.points
961
+ });
962
+ return await this.enrollmentView(enrollment);
963
+ }
964
+ async saveNote(actor, input) {
965
+ const current = user(actor);
966
+ const parsed = parse(noteSchema, input);
967
+ const course = await this.course(parsed.courseId);
968
+ return { note: (await change(this.stores.enrollments, enrollmentKey(course.id, current.id), async (stored) => {
969
+ await this.lessonAccess(course, parsed.lessonId, stored);
970
+ const next = structuredClone(stored);
971
+ const progress = next.progress[parsed.lessonId] ?? emptyProgress();
972
+ progress.note = parsed.note;
973
+ next.progress[parsed.lessonId] = progress;
974
+ return {
975
+ value: next,
976
+ result: next
977
+ };
978
+ })).progress[parsed.lessonId].note };
979
+ }
980
+ async certificate(actor, courseId) {
981
+ const current = user(actor);
982
+ const enrollment = await this.stores.enrollments.get(enrollmentKey(courseId, current.id));
983
+ invariant(enrollment?.certificate, "NOT_FOUND", "Certificate not found.", 404);
984
+ await this.projectCompletion(enrollment);
985
+ return enrollment.certificate;
986
+ }
987
+ async ownedCertificate(actor, id) {
988
+ const current = user(actor);
989
+ const index = await this.stores.certificates.get(id);
990
+ invariant(index?.userId === current.id, "NOT_FOUND", "Certificate not found.", 404);
991
+ const enrollment = await this.stores.enrollments.get(index.enrollmentId);
992
+ invariant(enrollment?.certificate?.id === id, "NOT_FOUND", "Certificate not found.", 404);
993
+ return enrollment.certificate;
994
+ }
995
+ async verifyCertificate(id) {
996
+ const index = await this.stores.certificates.get(id);
997
+ invariant(index, "NOT_FOUND", "Certificate not found.", 404);
998
+ const certificate = (await this.stores.enrollments.get(index.enrollmentId))?.certificate;
999
+ invariant(certificate?.id === id, "NOT_FOUND", "Certificate not found.", 404);
1000
+ return {
1001
+ id,
1002
+ courseTitle: certificate.courseTitle,
1003
+ issuerName: certificate.issuerName,
1004
+ issuedAt: certificate.issuedAt,
1005
+ valid: !certificate.revokedAt,
1006
+ shared: certificate.shared,
1007
+ learnerName: certificate.shared ? certificate.learnerName : null
1008
+ };
1009
+ }
1010
+ async shareCertificate(actor, courseId, shared) {
1011
+ const current = user(actor);
1012
+ return await change(this.stores.enrollments, enrollmentKey(courseId, current.id), async (stored) => {
1013
+ invariant(stored?.certificate, "NOT_FOUND", "Certificate not found.", 404);
1014
+ const next = structuredClone(stored);
1015
+ next.certificate.shared = shared;
1016
+ return {
1017
+ value: next,
1018
+ result: next.certificate
1019
+ };
1020
+ });
1021
+ }
1022
+ async revokeCertificate(actor, courseId, userId, reason) {
1023
+ const course = await this.course(courseId);
1024
+ const current = this.instructor(course, actor);
1025
+ const certificate = await change(this.stores.enrollments, enrollmentKey(courseId, userId), async (stored) => {
1026
+ invariant(stored?.certificate, "NOT_FOUND", "Certificate not found.", 404);
1027
+ const next = structuredClone(stored);
1028
+ next.certificate.revokedAt = this.time();
1029
+ next.certificate.revocationReason = reason;
1030
+ return {
1031
+ value: next,
1032
+ result: next.certificate
1033
+ };
1034
+ });
1035
+ await this.audit(current, "certificate.revoke", certificate.id);
1036
+ return certificate;
1037
+ }
1038
+ async cancelEnrollment(actor, courseId) {
1039
+ const current = user(actor);
1040
+ const enrollment = await change(this.stores.enrollments, enrollmentKey(courseId, current.id), async (stored) => {
1041
+ invariant(stored, "NOT_FOUND", "Enrollment not found.", 404);
1042
+ const next = {
1043
+ ...stored,
1044
+ status: "cancelled",
1045
+ accessStatus: "revoked"
1046
+ };
1047
+ return {
1048
+ value: next,
1049
+ result: next
1050
+ };
1051
+ });
1052
+ return await this.enrollmentView(enrollment);
1053
+ }
1054
+ async discussions(actor, courseId, lessonId, cursor) {
1055
+ const current = user(actor);
1056
+ const course = await this.course(courseId);
1057
+ const enrollment = await this.stores.enrollments.get(enrollmentKey(courseId, current.id));
1058
+ await this.lessonAccess(course, lessonId, enrollment);
1059
+ const page = await queryPage(this.stores.discussions, {
1060
+ where: {
1061
+ courseId,
1062
+ lessonId,
1063
+ status: "published"
1064
+ },
1065
+ orderBy: { createdAt: "asc" },
1066
+ cursor,
1067
+ limit: 30
1068
+ });
1069
+ const own = await queryPage(this.stores.discussions, {
1070
+ where: {
1071
+ courseId,
1072
+ lessonId,
1073
+ authorId: current.id,
1074
+ status: "pending"
1075
+ },
1076
+ limit: 30
1077
+ });
1078
+ return {
1079
+ ...page,
1080
+ pending: own.items
1081
+ };
1082
+ }
1083
+ async postDiscussion(actor, input) {
1084
+ const current = user(actor);
1085
+ const parsed = parse(discussionSchema, input);
1086
+ const course = await this.course(parsed.courseId);
1087
+ const enrollment = await this.stores.enrollments.get(enrollmentKey(course.id, current.id));
1088
+ await this.lessonAccess(course, parsed.lessonId, enrollment);
1089
+ if (parsed.parentId) {
1090
+ const parent = await this.stores.discussions.get(parsed.parentId);
1091
+ invariant(parent && parent.courseId === course.id && parent.lessonId === parsed.lessonId && parent.status === "published" && !parent.parentId, "INVALID_PARENT", "Reply to a published discussion in this lesson.");
1092
+ }
1093
+ const settings = await this.settings();
1094
+ const id = crypto.randomUUID();
1095
+ const discussion = {
1096
+ ...parsed,
1097
+ id,
1098
+ authorId: current.id,
1099
+ authorName: current.name || "Learner",
1100
+ status: settings.moderateDiscussions ? "pending" : "published",
1101
+ createdAt: this.time(),
1102
+ updatedAt: this.time()
1103
+ };
1104
+ await this.stores.discussions.put(id, discussion);
1105
+ return discussion;
1106
+ }
1107
+ async publicReviews(courseId, cursor) {
1108
+ invariant((await this.course(courseId)).status === "published", "NOT_FOUND", "Course not found.", 404);
1109
+ return queryPage(this.stores.reviews, {
1110
+ where: {
1111
+ courseId,
1112
+ status: "published"
1113
+ },
1114
+ orderBy: { createdAt: "desc" },
1115
+ limit: 24,
1116
+ cursor
1117
+ });
1118
+ }
1119
+ async postReview(actor, input) {
1120
+ const current = user(actor);
1121
+ const parsed = parse(reviewSchema, input);
1122
+ const course = await this.course(parsed.courseId);
1123
+ const enrollment = await this.accessEnrollment(await this.stores.enrollments.get(enrollmentKey(course.id, current.id)));
1124
+ assertEnrollmentAccess(enrollment, this.now());
1125
+ invariant(Object.values(enrollment.progress).some((progress) => progress.completedAt), "REVIEW_TOO_EARLY", "Complete at least one lesson before reviewing this course.", 403);
1126
+ const settings = await this.settings();
1127
+ const id = enrollmentKey(course.id, current.id);
1128
+ return await change(this.stores.reviews, id, async (stored) => {
1129
+ const next = {
1130
+ ...parsed,
1131
+ id,
1132
+ userId: current.id,
1133
+ authorName: current.name || "Learner",
1134
+ status: settings.moderateReviews ? "pending" : "published",
1135
+ createdAt: stored?.createdAt ?? this.time(),
1136
+ updatedAt: this.time()
1137
+ };
1138
+ return {
1139
+ value: next,
1140
+ result: next
1141
+ };
1142
+ });
1143
+ }
1144
+ async moderate(actor, collection, input) {
1145
+ const parsed = parse(moderateSchema, input);
1146
+ const store = this.stores[collection];
1147
+ const stored = await store.getVersioned(parsed.id);
1148
+ invariant(stored, "NOT_FOUND", "Community item not found.", 404);
1149
+ const course = await this.course(stored.value.courseId);
1150
+ const current = this.instructor(course, actor);
1151
+ invariant(stored.revision === parsed.expectedRevision, "CONFLICT", "This item changed. Reload before moderating.", 409);
1152
+ const next = {
1153
+ ...stored.value,
1154
+ status: parsed.status,
1155
+ updatedAt: this.time()
1156
+ };
1157
+ invariant((await store.compareAndSet(parsed.id, stored.revision, next)).applied, "CONFLICT", "This item changed while moderating.", 409);
1158
+ await this.audit(current, `${collection}.moderate`, parsed.id, { status: parsed.status });
1159
+ return next;
1160
+ }
1161
+ async communityQueue(actor, collection, options = {}) {
1162
+ const current = user(actor);
1163
+ if (options.courseId) this.instructor(await this.course(options.courseId), current);
1164
+ else invariant(current.role >= 50, "FORBIDDEN", "Select a course you teach.", 403);
1165
+ const store = this.stores[collection];
1166
+ const page = await store.query({
1167
+ where: {
1168
+ ...options.courseId ? { courseId: options.courseId } : {},
1169
+ ...options.status ? { status: options.status } : {}
1170
+ },
1171
+ orderBy: { createdAt: "desc" },
1172
+ limit: 30,
1173
+ cursor: options.cursor
1174
+ });
1175
+ const items = (await Promise.all(page.items.map((item) => store.getVersioned(item.id)))).flatMap((item) => item ? [{
1176
+ ...item.value,
1177
+ revision: item.revision
1178
+ }] : []);
1179
+ return {
1180
+ ...page,
1181
+ items
1182
+ };
1183
+ }
1184
+ async enrollments(actor, options = {}) {
1185
+ const current = user(actor);
1186
+ if (options.courseId) this.instructor(await this.course(options.courseId), current);
1187
+ else invariant(current.role >= 50, "FORBIDDEN", "Select a course you teach.", 403);
1188
+ const page = await queryPage(this.stores.enrollments, {
1189
+ where: {
1190
+ ...options.courseId ? { courseId: options.courseId } : {},
1191
+ ...options.status ? { status: options.status } : {}
1192
+ },
1193
+ orderBy: { enrolledAt: "desc" },
1194
+ limit: options.limit ?? 30,
1195
+ cursor: options.cursor
1196
+ });
1197
+ const courses = await this.stores.courses.getMany(page.items.map((item) => item.courseId));
1198
+ return {
1199
+ ...page,
1200
+ items: await Promise.all(page.items.map(async (enrollment) => ({
1201
+ ...await this.enrollmentView(enrollment),
1202
+ learnerEmail: enrollment.learnerEmail,
1203
+ courseTitle: courses.get(enrollment.courseId)?.title ?? "Archived course",
1204
+ lessonTitles: Object.fromEntries((courses.has(enrollment.courseId) ? lessons(courses.get(enrollment.courseId)) : []).map((lesson) => [lesson.id, lesson.title])),
1205
+ progressSummary: courses.has(enrollment.courseId) ? progressSummary(courses.get(enrollment.courseId), enrollment) : null
1206
+ })))
1207
+ };
1208
+ }
1209
+ async report(actor, courseId) {
1210
+ const current = user(actor);
1211
+ if (courseId) this.instructor(await this.course(courseId), current);
1212
+ else invariant(current.role >= 50, "FORBIDDEN", "Select a course you teach.", 403);
1213
+ const filter = courseId ? { courseId } : {};
1214
+ const statuses = [
1215
+ "pending",
1216
+ "active",
1217
+ "completed",
1218
+ "rejected",
1219
+ "suspended",
1220
+ "cancelled"
1221
+ ];
1222
+ const counts = await Promise.all(statuses.map((status) => this.stores.enrollments.count({
1223
+ ...filter,
1224
+ status
1225
+ })));
1226
+ const statusCounts = Object.fromEntries(statuses.map((status, index) => [status, counts[index]]));
1227
+ const total = counts.reduce((sum, count) => sum + count, 0);
1228
+ const completedEver = await this.stores.enrollments.count({
1229
+ ...filter,
1230
+ completedAt: { gte: "0000-01-01T00:00:00.000Z" }
1231
+ });
1232
+ const sourceCounts = Object.fromEntries(await Promise.all([
1233
+ "free",
1234
+ "manual",
1235
+ "cohort",
1236
+ "purchase"
1237
+ ].map(async (accessSource) => [accessSource, await this.stores.enrollments.count({
1238
+ ...filter,
1239
+ accessSource
1240
+ })])));
1241
+ const accessDecisions = Object.fromEntries(await Promise.all([
1242
+ "pending",
1243
+ "granted",
1244
+ "suspended",
1245
+ "revoked"
1246
+ ].map(async (accessStatus) => [accessStatus, await this.stores.enrollments.count({
1247
+ ...filter,
1248
+ accessStatus
1249
+ })])));
1250
+ return {
1251
+ total,
1252
+ completedEver,
1253
+ ...statusCounts,
1254
+ accessSources: sourceCounts,
1255
+ accessDecisions,
1256
+ completionRate: total ? Math.round(completedEver / total * 100) : 0,
1257
+ courseCount: courseId ? 1 : await this.stores.courses.count(),
1258
+ generatedAt: this.time()
1259
+ };
1260
+ }
1261
+ async enrollmentCsv(actor, options = {}) {
1262
+ const lines = [enrollmentCsvHeader];
1263
+ let cursor;
1264
+ let rows = 0;
1265
+ let bytes = new TextEncoder().encode(enrollmentCsvHeader).byteLength + 3;
1266
+ do {
1267
+ const page = await this.enrollments(actor, {
1268
+ ...options,
1269
+ cursor,
1270
+ limit: 100
1271
+ });
1272
+ const next = enrollmentCsvLines(page.items);
1273
+ rows += next.length;
1274
+ bytes += new TextEncoder().encode(next.join("\r\n")).byteLength + next.length * 2;
1275
+ invariant(rows <= 1e4 && bytes <= 6e6, "EXPORT_TOO_LARGE", "Filter by course or enrollment status to export fewer records.", 413);
1276
+ lines.push(...next);
1277
+ cursor = page.hasMore ? page.cursor : void 0;
1278
+ } while (cursor);
1279
+ return "" + lines.join("\r\n");
1280
+ }
1281
+ async cohortList(actor, cursor) {
1282
+ invariant(user(actor).role >= 50, "FORBIDDEN", "Only administrators can manage cohorts.", 403);
1283
+ const page = await this.stores.cohorts.query({
1284
+ orderBy: { createdAt: "desc" },
1285
+ limit: 24,
1286
+ cursor
1287
+ });
1288
+ const items = (await Promise.all(page.items.map((item) => this.stores.cohorts.getVersioned(item.id)))).flatMap((item) => item ? [{
1289
+ ...item.value,
1290
+ revision: item.revision
1291
+ }] : []);
1292
+ return {
1293
+ ...page,
1294
+ items
1295
+ };
1296
+ }
1297
+ async publicCohort(id) {
1298
+ const cohort = await this.stores.cohorts.get(id);
1299
+ invariant(cohort, "NOT_FOUND", "Cohort not found.", 404);
1300
+ const courses = await this.stores.courses.getMany(cohort.courseIds);
1301
+ return {
1302
+ id: cohort.id,
1303
+ title: cohort.title,
1304
+ startsAt: cohort.startsAt,
1305
+ endsAt: cohort.endsAt,
1306
+ courses: [...courses.values()].filter((course) => course.status === "published" && course.commerce.accessModel === "free").map(courseCard)
1307
+ };
1308
+ }
1309
+ async requestCohort(actor, cohortId) {
1310
+ const current = user(actor);
1311
+ const cohort = await this.stores.cohorts.get(cohortId);
1312
+ invariant(cohort, "NOT_FOUND", "Cohort not found.", 404);
1313
+ invariant(!cohort.endsAt || this.now().getTime() < Date.parse(cohort.endsAt), "COHORT_CLOSED", "This cohort has ended.", 403);
1314
+ const id = enrollmentKey(cohortId, current.id);
1315
+ return change(this.stores.cohort_enrollments, id, async (stored) => {
1316
+ invariant(!stored || ![
1317
+ "rejected",
1318
+ "suspended",
1319
+ "cancelled"
1320
+ ].includes(stored.status), "COHORT_RESTRICTED", "Contact an administrator to restore your cohort membership.", 403);
1321
+ const next = stored ?? {
1322
+ id,
1323
+ cohortId,
1324
+ userId: current.id,
1325
+ learnerName: current.name || "Learner",
1326
+ learnerEmail: current.email,
1327
+ status: "pending",
1328
+ requestedAt: this.time(),
1329
+ decidedAt: null,
1330
+ decidedBy: null,
1331
+ reason: null
1332
+ };
1333
+ return {
1334
+ value: next,
1335
+ result: next
1336
+ };
1337
+ });
1338
+ }
1339
+ async cohortMemberships(actor, options = {}) {
1340
+ invariant(user(actor).role >= 50, "FORBIDDEN", "Only administrators can review cohort membership.", 403);
1341
+ return queryPage(this.stores.cohort_enrollments, {
1342
+ where: {
1343
+ ...options.cohortId ? { cohortId: options.cohortId } : {},
1344
+ ...options.status ? { status: options.status } : {}
1345
+ },
1346
+ orderBy: { requestedAt: "desc" },
1347
+ limit: 30,
1348
+ cursor: options.cursor
1349
+ });
1350
+ }
1351
+ async decideCohort(actor, cohortId, userId, status, reason = "") {
1352
+ const current = user(actor);
1353
+ invariant(current.role >= 50, "FORBIDDEN", "Only administrators can make cohort decisions.", 403);
1354
+ const cohort = await this.stores.cohorts.get(cohortId);
1355
+ invariant(cohort && this.ctx.users, "NOT_FOUND", "Cohort not found.", 404);
1356
+ const target = await this.ctx.users.get(userId);
1357
+ invariant(target, "NOT_FOUND", "Learner account not found.", 404);
1358
+ const membership = await change(this.stores.cohort_enrollments, enrollmentKey(cohortId, userId), async (stored) => {
1359
+ const next = {
1360
+ ...stored ?? {
1361
+ id: enrollmentKey(cohortId, userId),
1362
+ cohortId,
1363
+ userId,
1364
+ learnerName: target.name || "Learner",
1365
+ learnerEmail: target.email,
1366
+ requestedAt: this.time()
1367
+ },
1368
+ status,
1369
+ decidedAt: this.time(),
1370
+ decidedBy: current.id,
1371
+ reason: reason || null
1372
+ };
1373
+ return {
1374
+ value: next,
1375
+ result: next
1376
+ };
1377
+ });
1378
+ const results = [];
1379
+ for (const courseId of cohort.courseIds) try {
1380
+ if (status === "active") {
1381
+ const existing = await this.stores.enrollments.get(enrollmentKey(courseId, userId));
1382
+ invariant(!existing || ![
1383
+ "suspended",
1384
+ "cancelled",
1385
+ "rejected"
1386
+ ].includes(existing.status), "ENROLLMENT_RESTRICTED", "Restore this course enrollment separately before granting cohort access.", 403);
1387
+ await this.adminEnrollment(current, {
1388
+ courseId,
1389
+ userId,
1390
+ cohortId,
1391
+ status: "active"
1392
+ });
1393
+ } else {
1394
+ const id = enrollmentKey(courseId, userId);
1395
+ if (await this.stores.enrollments.exists(id)) await change(this.stores.enrollments, id, async (stored) => {
1396
+ invariant(stored, "NOT_FOUND", "Enrollment not found.", 404);
1397
+ const next = structuredClone(stored);
1398
+ const grant = next.grants[`cohort:${cohortId}`];
1399
+ if (grant) grant.status = status === "suspended" ? "suspended" : "revoked";
1400
+ return {
1401
+ value: next,
1402
+ result: true
1403
+ };
1404
+ });
1405
+ }
1406
+ results.push({
1407
+ courseId,
1408
+ success: true
1409
+ });
1410
+ } catch (error) {
1411
+ results.push({
1412
+ courseId,
1413
+ success: false,
1414
+ error: error instanceof LmsError ? error.message : "Access update failed."
1415
+ });
1416
+ }
1417
+ await this.audit(current, "cohort.decision", membership.id, { status });
1418
+ return {
1419
+ membership,
1420
+ results
1421
+ };
1422
+ }
1423
+ async saveCohort(actor, input) {
1424
+ const current = user(actor);
1425
+ invariant(current.role >= 50, "FORBIDDEN", "Only administrators can manage cohorts.", 403);
1426
+ const parsed = parse(cohortSaveSchema, input);
1427
+ for (const id of parsed.data.courseIds) await this.course(id);
1428
+ const id = parsed.id ?? crypto.randomUUID();
1429
+ const existing = await this.stores.cohorts.getVersioned(id);
1430
+ invariant((existing?.revision ?? null) === parsed.expectedRevision, "CONFLICT", "The cohort changed. Reload before saving.", 409);
1431
+ if (existing && await this.stores.cohort_enrollments.count({ cohortId: id })) invariant(existing.value.courseIds.every((courseId) => parsed.data.courseIds.includes(courseId)), "COHORT_IN_USE", "Cohorts with membership records must retain existing courses. Create a new cohort to remove courses.", 409);
1432
+ const cohort = {
1433
+ ...parsed.data,
1434
+ id,
1435
+ createdBy: existing?.value.createdBy ?? current.id,
1436
+ createdAt: existing?.value.createdAt ?? this.time(),
1437
+ updatedAt: this.time()
1438
+ };
1439
+ const saved = await this.stores.cohorts.compareAndSet(id, existing?.revision ?? null, cohort);
1440
+ invariant(saved.applied, "CONFLICT", "The cohort changed while saving.", 409);
1441
+ await this.audit(current, "cohort.save", id);
1442
+ return {
1443
+ cohort,
1444
+ revision: saved.revision
1445
+ };
1446
+ }
1447
+ async applyCohort(actor, id, expectedRevision, offset) {
1448
+ const current = user(actor);
1449
+ invariant(current.role >= 50, "FORBIDDEN", "Only administrators can enroll cohorts.", 403);
1450
+ const stored = await this.stores.cohorts.getVersioned(id);
1451
+ invariant(stored, "NOT_FOUND", "Cohort not found.", 404);
1452
+ invariant(stored.revision === expectedRevision, "CONFLICT", "The cohort changed. Reload before continuing.", 409);
1453
+ const cohort = stored.value;
1454
+ const members = cohort.memberIds.slice(offset, offset + Math.max(1, Math.floor(10 / cohort.courseIds.length)));
1455
+ const results = [];
1456
+ for (const userId of members) try {
1457
+ const decided = await this.decideCohort(current, id, userId, "active");
1458
+ results.push(...decided.results.map((result) => ({
1459
+ userId,
1460
+ ...result
1461
+ })));
1462
+ } catch (error) {
1463
+ results.push({
1464
+ userId,
1465
+ courseId: "",
1466
+ success: false,
1467
+ error: error instanceof LmsError ? error.message : "Enrollment failed."
1468
+ });
1469
+ }
1470
+ const nextOffset = offset + members.length;
1471
+ return {
1472
+ results,
1473
+ nextOffset,
1474
+ hasMore: nextOffset < cohort.memberIds.length
1475
+ };
1476
+ }
1477
+ async notify(enrollment, key, title, message) {
1478
+ const settings = await this.settings();
1479
+ const id = `${enrollment.id}:${key}`;
1480
+ const notification = {
1481
+ id,
1482
+ userId: enrollment.userId,
1483
+ email: enrollment.learnerEmail,
1484
+ title,
1485
+ message,
1486
+ courseId: enrollment.courseId,
1487
+ read: false,
1488
+ createdAt: this.time(),
1489
+ emailStatus: settings.emailNotifications ? "pending" : "disabled",
1490
+ emailAttempts: 0,
1491
+ claimedAt: null
1492
+ };
1493
+ await putOnce(this.stores.notifications, id, notification);
1494
+ }
1495
+ async notifications(actor, cursor) {
1496
+ const current = user(actor);
1497
+ const page = await queryPage(this.stores.notifications, {
1498
+ where: { userId: current.id },
1499
+ orderBy: { createdAt: "desc" },
1500
+ limit: 30,
1501
+ cursor
1502
+ });
1503
+ return {
1504
+ ...page,
1505
+ items: page.items.map(({ email: _email, emailStatus: _status, emailAttempts: _attempts, claimedAt: _claimed, ...item }) => item)
1506
+ };
1507
+ }
1508
+ async readNotification(actor, id) {
1509
+ const current = user(actor);
1510
+ await change(this.stores.notifications, id, async (stored) => {
1511
+ invariant(stored && stored.userId === current.id, "NOT_FOUND", "Notification not found.", 404);
1512
+ return {
1513
+ value: {
1514
+ ...stored,
1515
+ read: true
1516
+ },
1517
+ result: true
1518
+ };
1519
+ });
1520
+ return { read: true };
1521
+ }
1522
+ async deliverNotifications() {
1523
+ if (!(await this.settings()).emailNotifications || !this.ctx.email) return {
1524
+ sent: 0,
1525
+ failed: 0
1526
+ };
1527
+ const cutoff = (/* @__PURE__ */ new Date(this.now().getTime() - 15 * 6e4)).toISOString();
1528
+ const abandoned = await this.stores.notifications.query({
1529
+ where: {
1530
+ emailStatus: "sending",
1531
+ claimedAt: { lte: cutoff }
1532
+ },
1533
+ limit: 20
1534
+ });
1535
+ let failed = 0;
1536
+ for (const item of abandoned.items) if ((await this.stores.notifications.updateIf(item.id, {
1537
+ where: {
1538
+ emailStatus: "sending",
1539
+ claimedAt: { lte: cutoff }
1540
+ },
1541
+ set: { emailStatus: "failed" }
1542
+ })).applied) failed++;
1543
+ const page = await this.stores.notifications.query({
1544
+ where: { emailStatus: "pending" },
1545
+ limit: 20
1546
+ });
1547
+ let sent = 0;
1548
+ for (const item of page.items) {
1549
+ if (item.data.emailAttempts >= 3) continue;
1550
+ const claimedAt = this.time();
1551
+ const emailAttempts = item.data.emailAttempts + 1;
1552
+ if (!(await this.stores.notifications.updateIf(item.id, {
1553
+ where: {
1554
+ emailStatus: "pending",
1555
+ emailAttempts: item.data.emailAttempts
1556
+ },
1557
+ set: {
1558
+ emailStatus: "sending",
1559
+ claimedAt
1560
+ },
1561
+ delta: { emailAttempts: { inc: 1 } }
1562
+ })).applied) continue;
1563
+ try {
1564
+ await this.ctx.email.send({
1565
+ to: item.data.email,
1566
+ subject: item.data.title,
1567
+ text: item.data.message
1568
+ });
1569
+ await this.stores.notifications.updateIf(item.id, {
1570
+ where: {
1571
+ emailStatus: "sending",
1572
+ emailAttempts,
1573
+ claimedAt
1574
+ },
1575
+ set: { emailStatus: "sent" }
1576
+ });
1577
+ sent++;
1578
+ } catch {
1579
+ await this.stores.notifications.updateIf(item.id, {
1580
+ where: {
1581
+ emailStatus: "sending",
1582
+ emailAttempts,
1583
+ claimedAt
1584
+ },
1585
+ set: { emailStatus: "failed" }
1586
+ });
1587
+ failed++;
1588
+ }
1589
+ }
1590
+ return {
1591
+ sent,
1592
+ failed
1593
+ };
1594
+ }
1595
+ async assignments(actor, courseId, cursor) {
1596
+ const page = await this.enrollments(actor, {
1597
+ courseId,
1598
+ cursor,
1599
+ limit: 30
1600
+ });
1601
+ return {
1602
+ ...page,
1603
+ items: page.items.flatMap((enrollment) => Object.entries(enrollment.progress).flatMap(([lessonId, progress]) => progress.assignments.map((submission) => ({
1604
+ ...submission,
1605
+ userId: enrollment.userId,
1606
+ learnerName: enrollment.learnerName,
1607
+ courseId,
1608
+ lessonId
1609
+ }))))
1610
+ };
1611
+ }
1612
+ async exportCourse(actor, id) {
1613
+ const { course } = await this.editableCourse(actor, id);
1614
+ const { id: _id, searchTitle: _search, createdBy: _creator, createdAt: _created, updatedAt: _updated, schemaVersion: _version, ...data } = course;
1615
+ return {
1616
+ format: "anantagnanam-lms-course",
1617
+ version: 1,
1618
+ course: data
1619
+ };
1620
+ }
1621
+ async importCourse(actor, input) {
1622
+ const parsed = parse(z.object({
1623
+ format: z.literal("anantagnanam-lms-course"),
1624
+ version: z.literal(1),
1625
+ course: courseSaveSchema.shape.data
1626
+ }), input);
1627
+ return this.saveCourse(actor, {
1628
+ data: {
1629
+ ...parsed.course,
1630
+ status: "draft"
1631
+ },
1632
+ expectedRevision: null
1633
+ });
1634
+ }
1635
+ async deleteCourse(actor, id, expectedRevision) {
1636
+ const stored = await this.stores.courses.getVersioned(id);
1637
+ invariant(stored, "NOT_FOUND", "Course not found.", 404);
1638
+ const current = this.instructor(stored.value, actor);
1639
+ invariant(stored.value.status === "draft" && await this.stores.enrollments.count({ courseId: id }) === 0, "COURSE_IN_USE", "Only drafts without enrollments can be deleted. Archive other courses.", 409);
1640
+ invariant((await this.stores.courses.compareAndDelete(id, expectedRevision)).applied, "CONFLICT", "The course changed. Reload before deleting.", 409);
1641
+ await this.audit(current, "course.delete", id);
1642
+ return { deleted: true };
1643
+ }
1644
+ async retryNotification(actor, id) {
1645
+ invariant(user(actor).role >= 50, "FORBIDDEN", "Only administrators can retry email delivery.", 403);
1646
+ invariant((await this.stores.notifications.updateIf(id, {
1647
+ where: {
1648
+ emailStatus: "failed",
1649
+ emailAttempts: { lt: 3 }
1650
+ },
1651
+ set: {
1652
+ emailStatus: "pending",
1653
+ claimedAt: null
1654
+ }
1655
+ })).applied, "RETRY_UNAVAILABLE", "This notification cannot be retried.", 409);
1656
+ await this.audit(actor, "notification.retry", id);
1657
+ return { queued: true };
1658
+ }
1659
+ async notificationQueue(actor, options = {}) {
1660
+ invariant(user(actor).role >= 50, "FORBIDDEN", "Administrator access required.", 403);
1661
+ return queryPage(this.stores.notifications, {
1662
+ where: options.status ? { emailStatus: options.status } : {},
1663
+ orderBy: { createdAt: "desc" },
1664
+ limit: options.limit ?? 30,
1665
+ cursor: options.cursor
1666
+ });
1667
+ }
1668
+ async auditList(actor, options = {}) {
1669
+ invariant(user(actor).role >= 50, "FORBIDDEN", "Administrator access required.", 403);
1670
+ return queryPage(this.stores.audit, {
1671
+ orderBy: { createdAt: "desc" },
1672
+ limit: options.limit ?? 30,
1673
+ cursor: options.cursor
1674
+ });
1675
+ }
1676
+ async reminders() {
1677
+ const settings = await this.settings();
1678
+ if (!settings.reminderDays) return 0;
1679
+ const cutoff = (/* @__PURE__ */ new Date(this.now().getTime() - settings.reminderDays * 864e5)).toISOString();
1680
+ const cursor = await this.ctx.kv.get("reminders:cursor");
1681
+ const page = await this.stores.enrollments.query({
1682
+ where: { status: "active" },
1683
+ limit: 30,
1684
+ cursor: cursor ?? void 0
1685
+ });
1686
+ const week = Math.floor(this.now().getTime() / (7 * 864e5));
1687
+ let queued = 0;
1688
+ for (const item of page.items) {
1689
+ if (item.data.lastActivityAt > cutoff || effectiveAccess(await this.accessEnrollment(item.data), this.now()) !== "granted") continue;
1690
+ await this.notify(item.data, `reminder-${week}`, "Continue your learning", "Your next lesson is waiting in My Learning.");
1691
+ queued++;
1692
+ }
1693
+ if (page.hasMore && page.cursor) await this.ctx.kv.set("reminders:cursor", page.cursor);
1694
+ else await this.ctx.kv.delete("reminders:cursor");
1695
+ return queued;
1696
+ }
1697
+ };
1698
+
1699
+ //#endregion
1700
+ //#region src/runtime.ts
1701
+ const listSchema = pageSchema.extend({
1702
+ courseId: idSchema.optional(),
1703
+ status: z.enum([
1704
+ "pending",
1705
+ "active",
1706
+ "completed",
1707
+ "rejected",
1708
+ "suspended",
1709
+ "cancelled"
1710
+ ]).optional()
1711
+ });
1712
+ const communityListSchema = pageSchema.extend({
1713
+ courseId: idSchema.optional(),
1714
+ status: z.enum([
1715
+ "pending",
1716
+ "published",
1717
+ "hidden"
1718
+ ]).optional()
1719
+ });
1720
+ const slugSchema = z.object({ slug: z.string().min(1).max(100) });
1721
+ const keyInput = z.object({ id: keySchema });
1722
+ function get(handler, publicRoute = false, permission = "content:read") {
1723
+ return definePluginRoute({
1724
+ methods: ["GET"],
1725
+ public: publicRoute,
1726
+ permission,
1727
+ request: { body: "none" },
1728
+ handler: async (ctx) => handler(ctx, new LmsService(ctx))
1729
+ });
1730
+ }
1731
+ function post(handler, permission = "content:read") {
1732
+ return definePluginRoute({
1733
+ methods: ["POST"],
1734
+ permission,
1735
+ request: {
1736
+ body: "json",
1737
+ maxBytes: 1e6
1738
+ },
1739
+ handler: async (ctx) => handler(ctx, new LmsService(ctx))
1740
+ });
1741
+ }
1742
+ function createPlugin(_options = {}) {
1743
+ const options = normalizeLmsOptions(_options);
1744
+ return definePlugin({
1745
+ id: PLUGIN_ID,
1746
+ version: PLUGIN_VERSION,
1747
+ capabilities: [
1748
+ "schema:read",
1749
+ "content:read",
1750
+ "users:read",
1751
+ "email:send"
1752
+ ],
1753
+ storage,
1754
+ admin: {
1755
+ entry: "@anantagnanam/lms/admin",
1756
+ pages: adminPages,
1757
+ widgets: [{
1758
+ id: "learning",
1759
+ title: "Learning",
1760
+ size: "half"
1761
+ }]
1762
+ },
1763
+ hooks: {
1764
+ "plugin:install": async (_event, ctx) => {
1765
+ await ctx.kv.set("schemaVersion", 1);
1766
+ },
1767
+ "plugin:activate": async (_event, ctx) => {
1768
+ await ctx.cron?.schedule("maintenance", { schedule: "*/15 * * * *" });
1769
+ },
1770
+ "plugin:deactivate": async (_event, ctx) => {
1771
+ await ctx.cron?.cancel("maintenance");
1772
+ },
1773
+ cron: async (event, ctx) => {
1774
+ if (event.name === "maintenance") {
1775
+ const service = new LmsService(ctx);
1776
+ await service.reminders();
1777
+ await service.deliverNotifications();
1778
+ }
1779
+ }
1780
+ },
1781
+ routes: {
1782
+ academy: get(async (_ctx, service) => {
1783
+ const settings = await service.settings();
1784
+ return {
1785
+ title: settings.academyTitle,
1786
+ description: settings.academyDescription,
1787
+ basePath: options.basePath
1788
+ };
1789
+ }, true),
1790
+ catalog: get(async (ctx, service) => service.catalog(ctx.input), true),
1791
+ course: get(async (ctx, service) => service.publicCourse(parse(slugSchema, ctx.input).slug), true),
1792
+ cohort: get(async (ctx, service) => service.publicCohort(parse(z.object({ id: idSchema }), ctx.input).id), true),
1793
+ preview: get(async (ctx, service) => {
1794
+ const input = parse(lessonIdSchema, ctx.input);
1795
+ return service.preview(input.courseId, input.lessonId);
1796
+ }, true),
1797
+ reviews: get(async (ctx, service) => {
1798
+ const input = parse(courseIdSchema.extend({ cursor: z.string().optional() }), ctx.input);
1799
+ return service.publicReviews(input.courseId, input.cursor);
1800
+ }, true),
1801
+ "certificates/verify": get(async (ctx, service) => service.verifyCertificate(parse(z.object({ id: idSchema }), ctx.input).id), true),
1802
+ "learner/dashboard": get(async (ctx, service) => service.dashboard(ctx.user, parse(pageSchema, ctx.input))),
1803
+ "learner/course": get(async (ctx, service) => service.learnerCourse(ctx.user, parse(courseIdSchema, ctx.input).courseId)),
1804
+ "learner/course-by-slug": get(async (ctx, service) => service.learnerCourseBySlug(ctx.user, parse(slugSchema, ctx.input).slug)),
1805
+ "learner/lesson": get(async (ctx, service) => {
1806
+ const input = parse(lessonIdSchema, ctx.input);
1807
+ return service.learnerLesson(ctx.user, input.courseId, input.lessonId);
1808
+ }),
1809
+ "learner/enroll": post(async (ctx, service) => {
1810
+ const input = parse(enrollmentRequestSchema, ctx.input);
1811
+ return service.enroll(ctx.user, input.courseId, { cohortId: input.cohortId });
1812
+ }),
1813
+ "learner/cohort/request": post(async (ctx, service) => service.requestCohort(ctx.user, parse(z.object({ cohortId: idSchema }), ctx.input).cohortId)),
1814
+ "learner/cancel": post(async (ctx, service) => service.cancelEnrollment(ctx.user, parse(courseIdSchema, ctx.input).courseId)),
1815
+ "learner/start": post(async (ctx, service) => {
1816
+ const input = parse(lessonIdSchema, ctx.input);
1817
+ return service.startLesson(ctx.user, input.courseId, input.lessonId);
1818
+ }),
1819
+ "learner/complete": post(async (ctx, service) => {
1820
+ const input = parse(lessonIdSchema, ctx.input);
1821
+ return service.completeLesson(ctx.user, input.courseId, input.lessonId);
1822
+ }),
1823
+ "learner/quiz/start": post(async (ctx, service) => {
1824
+ const input = parse(lessonIdSchema, ctx.input);
1825
+ return service.startQuiz(ctx.user, input.courseId, input.lessonId);
1826
+ }),
1827
+ "learner/quiz/submit": post(async (ctx, service) => service.submitQuiz(ctx.user, ctx.input)),
1828
+ "learner/quiz/draft": post(async (ctx, service) => service.saveQuizDraft(ctx.user, ctx.input)),
1829
+ "learner/assignment": post(async (ctx, service) => service.submitAssignment(ctx.user, ctx.input)),
1830
+ "learner/note": post(async (ctx, service) => service.saveNote(ctx.user, ctx.input)),
1831
+ "learner/discussions": get(async (ctx, service) => {
1832
+ const input = parse(lessonIdSchema.extend({ cursor: z.string().optional() }), ctx.input);
1833
+ return service.discussions(ctx.user, input.courseId, input.lessonId, input.cursor);
1834
+ }),
1835
+ "learner/discussion": post(async (ctx, service) => service.postDiscussion(ctx.user, ctx.input)),
1836
+ "learner/review": post(async (ctx, service) => service.postReview(ctx.user, ctx.input)),
1837
+ "learner/certificate": get(async (ctx, service) => service.certificate(ctx.user, parse(courseIdSchema, ctx.input).courseId)),
1838
+ "learner/certificate-by-id": get(async (ctx, service) => service.ownedCertificate(ctx.user, parse(z.object({ id: idSchema }), ctx.input).id)),
1839
+ "learner/cohort": get(async (ctx, service) => {
1840
+ const input = parse(z.object({ cohortId: idSchema }), ctx.input);
1841
+ invariant(ctx.user, "UNAUTHORIZED", "Sign in to continue.", 401);
1842
+ return service.stores.cohort_enrollments.get(`${input.cohortId}:${ctx.user.id}`);
1843
+ }),
1844
+ "learner/certificate/share": post(async (ctx, service) => {
1845
+ const input = parse(certificateActionSchema, ctx.input);
1846
+ return service.shareCertificate(ctx.user, input.courseId, input.shared);
1847
+ }),
1848
+ "learner/notifications": get(async (ctx, service) => service.notifications(ctx.user, parse(pageSchema, ctx.input).cursor)),
1849
+ "learner/notification/read": post(async (ctx, service) => service.readNotification(ctx.user, parse(keyInput, ctx.input).id)),
1850
+ "admin/courses": get(async (ctx, service) => service.adminCourses(ctx.user, parse(pageSchema.extend({ status: z.enum([
1851
+ "draft",
1852
+ "published",
1853
+ "archived"
1854
+ ]).optional() }), ctx.input))),
1855
+ "admin/course": get(async (ctx, service) => service.editableCourse(ctx.user, parse(z.object({ id: idSchema }), ctx.input).id)),
1856
+ "admin/course/save": post(async (ctx, service) => service.saveCourse(ctx.user, ctx.input)),
1857
+ "admin/course/delete": post(async (ctx, service) => {
1858
+ const input = parse(z.object({
1859
+ id: idSchema,
1860
+ expectedRevision: z.string().min(1).max(128)
1861
+ }), ctx.input);
1862
+ return service.deleteCourse(ctx.user, input.id, input.expectedRevision);
1863
+ }),
1864
+ "admin/course/export": get(async (ctx, service) => service.exportCourse(ctx.user, parse(z.object({ id: idSchema }), ctx.input).id)),
1865
+ "admin/course/import": post(async (ctx, service) => service.importCourse(ctx.user, ctx.input)),
1866
+ "admin/enrollments": get(async (ctx, service) => service.enrollments(ctx.user, parse(listSchema, ctx.input))),
1867
+ "admin/enrollment/save": post(async (ctx, service) => service.adminEnrollment(ctx.user, ctx.input), "plugins:manage"),
1868
+ "admin/assignments": get(async (ctx, service) => {
1869
+ const input = parse(courseIdSchema.extend({ cursor: z.string().optional() }), ctx.input);
1870
+ return service.assignments(ctx.user, input.courseId, input.cursor);
1871
+ }),
1872
+ "admin/assignment/grade": post(async (ctx, service) => service.gradeAssignment(ctx.user, ctx.input)),
1873
+ "admin/discussions": get(async (ctx, service) => service.communityQueue(ctx.user, "discussions", parse(communityListSchema, ctx.input))),
1874
+ "admin/reviews": get(async (ctx, service) => service.communityQueue(ctx.user, "reviews", parse(communityListSchema, ctx.input))),
1875
+ "admin/discussion/moderate": post(async (ctx, service) => service.moderate(ctx.user, "discussions", ctx.input)),
1876
+ "admin/review/moderate": post(async (ctx, service) => service.moderate(ctx.user, "reviews", ctx.input)),
1877
+ "admin/certificate/revoke": post(async (ctx, service) => {
1878
+ const input = parse(certificateRevokeSchema, ctx.input);
1879
+ return service.revokeCertificate(ctx.user, input.courseId, input.userId, input.reason);
1880
+ }),
1881
+ "admin/report": get(async (ctx, service) => service.report(ctx.user, parse(z.object({ courseId: idSchema.optional() }), ctx.input).courseId)),
1882
+ "admin/cohorts": get(async (ctx, service) => service.cohortList(ctx.user, parse(pageSchema, ctx.input).cursor), false, "plugins:manage"),
1883
+ "admin/cohort/save": post(async (ctx, service) => service.saveCohort(ctx.user, ctx.input), "plugins:manage"),
1884
+ "admin/cohort/enroll": post(async (ctx, service) => {
1885
+ const input = parse(z.object({
1886
+ id: idSchema,
1887
+ expectedRevision: z.string().min(1).max(128),
1888
+ offset: z.number().int().min(0).max(1e3).default(0)
1889
+ }), ctx.input);
1890
+ return service.applyCohort(ctx.user, input.id, input.expectedRevision, input.offset);
1891
+ }, "plugins:manage"),
1892
+ "admin/cohort/memberships": get(async (ctx, service) => service.cohortMemberships(ctx.user, parse(pageSchema.extend({
1893
+ cohortId: idSchema.optional(),
1894
+ status: z.enum([
1895
+ "pending",
1896
+ "active",
1897
+ "rejected",
1898
+ "suspended",
1899
+ "cancelled"
1900
+ ]).optional()
1901
+ }), ctx.input)), false, "plugins:manage"),
1902
+ "admin/cohort/decision": post(async (ctx, service) => {
1903
+ const input = parse(z.object({
1904
+ cohortId: idSchema,
1905
+ userId: idSchema,
1906
+ status: z.enum([
1907
+ "active",
1908
+ "rejected",
1909
+ "suspended",
1910
+ "cancelled"
1911
+ ]),
1912
+ reason: z.string().max(1e3).default("")
1913
+ }), ctx.input);
1914
+ return service.decideCohort(ctx.user, input.cohortId, input.userId, input.status, input.reason);
1915
+ }, "plugins:manage"),
1916
+ "admin/settings": get(async (_ctx, service) => service.settings(), false, "plugins:manage"),
1917
+ "admin/settings/save": post(async (ctx, service) => service.saveSettings(ctx.user, ctx.input), "plugins:manage"),
1918
+ "admin/notification/retry": post(async (ctx, service) => service.retryNotification(ctx.user, parse(keyInput, ctx.input).id), "plugins:manage"),
1919
+ "admin/notifications": get(async (ctx, service) => service.notificationQueue(ctx.user, parse(pageSchema.extend({ status: z.enum([
1920
+ "pending",
1921
+ "sending",
1922
+ "sent",
1923
+ "disabled",
1924
+ "failed"
1925
+ ]).optional() }), ctx.input)), false, "plugins:manage"),
1926
+ "admin/audit": get(async (ctx, service) => service.auditList(ctx.user, parse(pageSchema, ctx.input)), false, "plugins:manage"),
1927
+ "admin/users": get(async (ctx) => {
1928
+ invariant(ctx.users, "USERS_UNAVAILABLE", "The user directory is unavailable.", 503);
1929
+ const input = parse(pageSchema, ctx.input);
1930
+ const page = await ctx.users.list({
1931
+ limit: input.limit,
1932
+ cursor: input.cursor
1933
+ });
1934
+ return {
1935
+ ...page,
1936
+ items: page.items.map((entry) => ({
1937
+ id: entry.id,
1938
+ name: entry.name,
1939
+ email: entry.email,
1940
+ role: entry.role
1941
+ }))
1942
+ };
1943
+ }, false, "users:read"),
1944
+ "admin/instructors": get(async (ctx) => {
1945
+ invariant(ctx.user && ctx.user.role >= 20, "FORBIDDEN", "Course authoring access required.", 403);
1946
+ invariant(ctx.users, "USERS_UNAVAILABLE", "The user directory is unavailable.", 503);
1947
+ const input = parse(pageSchema, ctx.input);
1948
+ const page = await ctx.users.list({
1949
+ limit: input.limit,
1950
+ cursor: input.cursor
1951
+ });
1952
+ return {
1953
+ ...page,
1954
+ items: page.items.filter((entry) => entry.role >= 20).map((entry) => ({
1955
+ id: entry.id,
1956
+ name: entry.name,
1957
+ email: entry.email
1958
+ }))
1959
+ };
1960
+ }),
1961
+ "admin/content/collections": get(async (ctx) => {
1962
+ invariant(ctx.user && ctx.user.role >= 20, "FORBIDDEN", "Course authoring access required.", 403);
1963
+ invariant(ctx.schema, "SCHEMA_UNAVAILABLE", "The content schema is unavailable.", 503);
1964
+ return (await ctx.schema.listCollections()).map((collection) => ({
1965
+ slug: collection.slug,
1966
+ label: collection.label,
1967
+ fields: collection.fields.filter((field) => [
1968
+ "portableText",
1969
+ "text",
1970
+ "string"
1971
+ ].includes(field.type)).map((field) => ({
1972
+ slug: field.slug,
1973
+ label: field.label,
1974
+ type: field.type
1975
+ }))
1976
+ })).filter((collection) => collection.fields.length);
1977
+ }),
1978
+ "admin/content/entries": get(async (ctx) => {
1979
+ invariant(ctx.user && ctx.user.role >= 20, "FORBIDDEN", "Course authoring access required.", 403);
1980
+ invariant(ctx.schema && ctx.content, "CONTENT_UNAVAILABLE", "Content integration is unavailable.", 503);
1981
+ const input = parse(pageSchema.extend({ collection: idSchema }), ctx.input);
1982
+ const collection = await ctx.schema.getCollection(input.collection);
1983
+ invariant(collection, "NOT_FOUND", "Content collection not found.", 404);
1984
+ const page = await ctx.content.list(input.collection, {
1985
+ limit: input.limit,
1986
+ cursor: input.cursor,
1987
+ where: { status: "published" }
1988
+ });
1989
+ return {
1990
+ ...page,
1991
+ items: page.items.map((entry) => ({
1992
+ id: entry.id,
1993
+ title: String(entry.data[collection.titleField ?? "title"] ?? entry.slug ?? "Published entry")
1994
+ }))
1995
+ };
1996
+ }),
1997
+ "admin/learner/find": post(async (ctx, service) => {
1998
+ const input = parse(courseIdSchema.extend({ email: z.email().max(254) }), ctx.input);
1999
+ service.instructor(await service.course(input.courseId), ctx.user);
2000
+ invariant(ctx.users, "USERS_UNAVAILABLE", "The user directory is unavailable.", 503);
2001
+ const target = await ctx.users.getByEmail(input.email);
2002
+ invariant(target, "NOT_FOUND", "No account uses this email address. Invite the learner through EmDash first.", 404);
2003
+ return {
2004
+ id: target.id,
2005
+ name: target.name,
2006
+ email: target.email
2007
+ };
2008
+ }, "plugins:manage"),
2009
+ "admin/report/csv": definePluginRoute({
2010
+ methods: ["GET"],
2011
+ permission: "content:read",
2012
+ request: { body: "none" },
2013
+ response: "raw",
2014
+ handler: async (ctx) => {
2015
+ const input = parse(listSchema, ctx.input);
2016
+ return pluginResponse({
2017
+ body: {
2018
+ kind: "text",
2019
+ value: await new LmsService(ctx).enrollmentCsv(ctx.user, input)
2020
+ },
2021
+ headers: {
2022
+ "Content-Type": "text/csv; charset=utf-8",
2023
+ "Content-Disposition": "attachment; filename=\"lms-enrollments.csv\""
2024
+ }
2025
+ });
2026
+ }
2027
+ }),
2028
+ "mcp/courses": post(async (ctx, service) => service.adminCourses(ctx.user, parse(pageSchema, ctx.input)))
2029
+ },
2030
+ mcp: { tools: {
2031
+ list_courses: {
2032
+ route: "mcp/courses",
2033
+ description: "List courses available to this instructor or administrator.",
2034
+ input: pageSchema
2035
+ },
2036
+ save_course: {
2037
+ route: "admin/course/save",
2038
+ description: "Create or update a course using its current storage revision. Can publish course content.",
2039
+ input: courseSaveSchema,
2040
+ destructive: true
2041
+ },
2042
+ enroll_learner: {
2043
+ route: "admin/enrollment/save",
2044
+ description: "Approve, reject, suspend, or manually enroll a learner. Requires an administrator account.",
2045
+ input: enrollmentAdminSchema,
2046
+ destructive: true
2047
+ },
2048
+ grade_assignment: {
2049
+ route: "admin/assignment/grade",
2050
+ description: "Grade a pending assignment submission in a course you teach.",
2051
+ input: gradeSchema,
2052
+ destructive: true
2053
+ }
2054
+ } }
2055
+ });
2056
+ }
2057
+
2058
+ //#endregion
2059
+ export { LmsService, createPlugin };
2060
+ //# sourceMappingURL=runtime.js.map