@vue-skuilder/db 0.2.36 → 0.3.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 (59) hide show
  1. package/dist/{contentSource-D_E7JaxR.d.ts → contentSource-2zVmcjKA.d.ts} +6 -1
  2. package/dist/core/index.cjs +203 -148
  3. package/dist/core/index.cjs.map +1 -1
  4. package/dist/core/index.d.ts +5 -5
  5. package/dist/core/navigators/Pipeline.mjs +8 -0
  6. package/dist/core/navigators/Pipeline.mjs.map +1 -1
  7. package/dist/core/navigators/generators/prescribed.mjs +29 -11
  8. package/dist/core/navigators/generators/prescribed.mjs.map +1 -1
  9. package/dist/core/versionStamps.mjs +1 -1
  10. package/dist/{dataLayerProvider-BDshhSp_.d.ts → dataLayerProvider-rGyLQ93v.d.ts} +1 -1
  11. package/dist/diagnostics/index.d.ts +3 -3
  12. package/dist/impl/common/BaseUserDB.mjs +32 -15
  13. package/dist/impl/common/BaseUserDB.mjs.map +1 -1
  14. package/dist/impl/couch/CourseSyncService.mjs +111 -11
  15. package/dist/impl/couch/CourseSyncService.mjs.map +1 -1
  16. package/dist/impl/couch/PouchDataLayerProvider.mjs +16 -1
  17. package/dist/impl/couch/PouchDataLayerProvider.mjs.map +1 -1
  18. package/dist/impl/couch/courseAPI.mjs +24 -10
  19. package/dist/impl/couch/courseAPI.mjs.map +1 -1
  20. package/dist/impl/couch/courseDB.mjs +19 -9
  21. package/dist/impl/couch/courseDB.mjs.map +1 -1
  22. package/dist/impl/couch/index.cjs +297 -141
  23. package/dist/impl/couch/index.cjs.map +1 -1
  24. package/dist/impl/couch/index.d.ts +27 -4
  25. package/dist/impl/couch/index.mjs +20 -3
  26. package/dist/impl/couch/index.mjs.map +1 -1
  27. package/dist/impl/couch/updateQueue.mjs +69 -46
  28. package/dist/impl/couch/updateQueue.mjs.map +1 -1
  29. package/dist/impl/static/index.cjs +147 -93
  30. package/dist/impl/static/index.cjs.map +1 -1
  31. package/dist/impl/static/index.d.ts +4 -4
  32. package/dist/{index-BLDpFYG3.d.ts → index-C745YB_6.d.ts} +1 -1
  33. package/dist/index.cjs +345 -171
  34. package/dist/index.cjs.map +1 -1
  35. package/dist/index.d.ts +23 -10
  36. package/dist/index.mjs +2 -1
  37. package/dist/study/SessionController.mjs +4 -0
  38. package/dist/study/SessionController.mjs.map +1 -1
  39. package/dist/{types-DChCz22D.d.ts → types-DF0JuPbs.d.ts} +1 -1
  40. package/dist/{types-legacy-fT5Y1Wuy.d.ts → types-legacy-DdVjg81H.d.ts} +1 -1
  41. package/dist/util/packer/index.d.ts +3 -3
  42. package/dist/util/perfMarks.mjs +30 -0
  43. package/dist/util/perfMarks.mjs.map +1 -0
  44. package/package.json +3 -3
  45. package/src/core/interfaces/courseDB.ts +6 -0
  46. package/src/core/navigators/Pipeline.ts +8 -0
  47. package/src/core/navigators/generators/prescribed.ts +42 -16
  48. package/src/impl/common/BaseUserDB.ts +42 -23
  49. package/src/impl/couch/CourseSyncService.ts +149 -22
  50. package/src/impl/couch/PouchDataLayerProvider.ts +14 -1
  51. package/src/impl/couch/courseAPI.ts +26 -12
  52. package/src/impl/couch/courseDB.ts +25 -12
  53. package/src/impl/couch/index.ts +16 -5
  54. package/src/impl/couch/updateQueue.ts +86 -82
  55. package/src/study/SessionController.ts +4 -0
  56. package/src/util/index.ts +1 -0
  57. package/src/util/perfMarks.ts +35 -0
  58. package/tests/impl/courseSync.test.ts +139 -0
  59. package/tests/impl/updateQueue.test.ts +57 -0
@@ -1 +1 @@
1
- {"version":3,"file":"BaseUserDB.mjs","names":[],"sources":["../../../src/impl/common/BaseUserDB.ts"],"sourcesContent":["import {\n DocType,\n DocTypePrefixes,\n StrategyStateDoc,\n buildStrategyStateId,\n HYDRATION_MARKER_ID,\n type HydrationMarker,\n type UserHydrationStatus,\n} from '@db/core';\nimport { areQuestionRecords, getCardHistoryID } from '@db/core/util';\nimport { CourseElo, Status } from '@vue-skuilder/common';\nimport moment, { Moment } from 'moment';\nimport { GuestUsername } from '../../core/types/types-legacy';\nimport { logger } from '../../util/logger';\n\nimport {\n ClassroomRegistrationDoc,\n UserCourseSetting,\n UserDBInterface,\n UsrCrsDataInterface,\n} from '@db/core';\nimport {\n ActivityRecord,\n CourseRegistration,\n CourseRegistrationDoc,\n ScheduledCard,\n UserConfig,\n} from '@db/core/types/user';\nimport { DocumentUpdater, getLapses, getStreak } from '@db/study';\nimport { CardHistory, CardRecord } from '../../core/types/types-legacy';\nimport { UserOutcomeRecord } from '../../core/types/userOutcome';\nimport { StudySessionDoc } from '../../core/types/studySession';\nimport type { SyncStrategy } from './SyncStrategy';\nimport { filterAllDocsByPrefix, getStartAndEndKeys, REVIEW_TIME_FORMAT } from './userDBKeys';\nimport {\n getLocalUserDB,\n scheduleCardReviewLocal,\n removeScheduledCardReviewLocal,\n} from './userDBHelpers';\nimport { PouchError } from '../couch/types';\nimport type { AdoptSessionResult } from './types';\nimport UpdateQueue, { Update } from '../couch/updateQueue';\nimport { UsrCrsData } from '../couch/user-course-relDB';\nimport { getCredentialledCourseConfig } from '../couch/index';\n\nconst log = (s: any) => {\n logger.info(s);\n};\n\n// logger.log(`Connecting to remote: ${remoteStr}`);\n\ninterface DesignDoc {\n _id: string;\n views: {\n [viewName: string]: {\n map: string; // String representation of the map function\n };\n };\n}\n\n/**\n * Ceiling on the initial pull of a user's data before we give up and report\n * `failed`. Generous relative to the expected payload (a user database is a\n * config doc, registrations, strategy state, and per-card history), so hitting\n * it indicates a genuinely unusable connection rather than a large account.\n */\nconst HYDRATION_TIMEOUT_MS = 15_000;\n\n/**\n * Reject if `p` has not settled within `ms`.\n *\n * Note the underlying work is not cancelled by this — callers that need the\n * operation stopped must do so themselves.\n */\nfunction withTimeout<T>(p: Promise<T>, ms: number, label: string): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n return Promise.race([\n p,\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);\n }),\n ]).finally(() => {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n }) as Promise<T>;\n}\n\n/**\n * Base user database implementation that uses a pluggable sync strategy.\n * Handles local storage operations and delegates sync/remote operations to the strategy.\n */\nexport class BaseUser implements UserDBInterface, DocumentUpdater {\n private static _instance: BaseUser;\n private static _initialized: boolean = false;\n\n public static Dummy(syncStrategy: SyncStrategy): BaseUser {\n return new BaseUser('Me', syncStrategy);\n }\n\n static readonly DOC_IDS = {\n CONFIG: 'CONFIG',\n COURSE_REGISTRATIONS: 'CourseRegistrations',\n CLASSROOM_REGISTRATIONS: 'ClassroomRegistrations',\n };\n\n // private email: string;\n private _username: string;\n private syncStrategy: SyncStrategy;\n\n public getUsername(): string {\n return this._username;\n }\n\n public isLoggedIn(): boolean {\n return !this._username.startsWith(GuestUsername);\n }\n\n public remote(): PouchDB.Database {\n return this.remoteDB;\n }\n\n private localDB!: PouchDB.Database;\n private remoteDB!: PouchDB.Database;\n private writeDB!: PouchDB.Database; // Database to use for write operations (local-first approach)\n private updateQueue!: UpdateQueue;\n\n private _hydration: UserHydrationStatus = { state: 'not-required' };\n /** In-flight hydration, so concurrent callers can wait for a real answer. */\n private _hydrationPromise: Promise<void> | null = null;\n /**\n * Sequence the local mirror was filled to by a hydration that succeeded in\n * THIS init(), handed to startSync() so the live pull can skip history it\n * would otherwise re-walk. Undefined whenever there is no such guarantee —\n * hydration skipped, not required, or failed. Never persisted; see the\n * `since` note in CouchDBSyncStrategy.startSync().\n */\n private _hydratedSeq?: string | number;\n\n /**\n * How far the local mirror can be trusted, RIGHT NOW. See\n * {@link UserHydrationStatus}.\n *\n * This is a snapshot, and during login it can legitimately read\n * `hydrating` — prefer awaitHydration() anywhere a decision hangs on the\n * answer.\n */\n public hydrationStatus(): UserHydrationStatus {\n return { ...this._hydration };\n }\n\n /**\n * The hydration status once it has settled — never `hydrating`.\n *\n * Resolves immediately unless a pull is in flight. Exists for callers that\n * must decide something (a route guard, a first-run branch) and would\n * otherwise sample `hydrating` and guess. Since init() is awaited by both\n * app startup and login(), that only happens when something navigates\n * concurrently with a login still in progress — a window that stretches to\n * HYDRATION_TIMEOUT_MS on a slow connection.\n */\n public async awaitHydration(): Promise<UserHydrationStatus> {\n // hydrateLocalMirror() records failures rather than throwing, so this\n // cannot reject — but a stray rejection must not become the caller's\n // problem when a status is available either way.\n try {\n await this._hydrationPromise;\n } catch {\n // fall through to the recorded status\n }\n return this.hydrationStatus();\n }\n\n /**\n * Whether a missing document may be treated as genuinely absent, allowing\n * callers to create it with defaults.\n *\n * False only when hydration failed or is still running: a 404 then may just\n * mean \"not pulled down yet\", and materializing a default would both lie to\n * the user and, once live sync starts, push a rev-1 document that loses to\n * the real one — silently discarding it.\n */\n private canMaterializeDefaults(): boolean {\n return this._hydration.state !== 'failed' && this._hydration.state !== 'hydrating';\n }\n\n public async createAccount(\n username: string,\n password: string\n ): Promise<{\n status: Status;\n error: string;\n }> {\n if (!this.syncStrategy.canCreateAccount()) {\n throw new Error('Account creation not supported by current sync strategy');\n }\n\n if (!this._username.startsWith(GuestUsername)) {\n throw new Error(\n `Cannot create a new account while logged in:\nCurrently logged-in as ${this._username}.`\n );\n }\n\n const result = await this.syncStrategy.createAccount!(username, password);\n\n // If account creation was successful, update the username and reinitialize\n if (result.status === Status.ok) {\n log(`Account created successfully, updating username to ${username}`);\n this._username = username;\n try {\n localStorage.removeItem('sk-guest-uuid');\n } catch (e) {\n logger.warn('localStorage not available (Node.js environment):', e);\n }\n await this.init();\n }\n\n return {\n status: result.status,\n error: result.error || '',\n };\n }\n public async login(username: string, password: string) {\n if (!this.syncStrategy.canAuthenticate()) {\n throw new Error('Authentication not supported by current sync strategy');\n }\n\n if (!this._username.startsWith(GuestUsername) && this._username != username) {\n if (this._username != username) {\n throw new Error(`Cannot change accounts while logged in.\n Log out of account ${this.getUsername()} before logging in as ${username}.`);\n }\n logger.warn(`User ${this._username} is already logged in, but executing login again.`);\n }\n\n const loginResult = await this.syncStrategy.authenticate!(username, password);\n if (loginResult.ok) {\n log(`Logged in as ${username}`);\n this._username = username;\n try {\n localStorage.removeItem('sk-guest-uuid');\n } catch (e) {\n logger.warn('localStorage not available (Node.js environment):', e);\n }\n await this.init();\n }\n return loginResult;\n }\n\n /**\n * Adopt a remote session that was established outside this client — e.g. a\n * backend verified a third-party sign-in (Google) and set the session cookie\n * on its response. Afterwards the user is logged in exactly as after\n * login(): username switched, guest pointer cleared, init() re-run.\n *\n * @param opts.migrateGuestData Carry the current guest account's local data\n * into the adopted account. Pass true for a freshly created account (as\n * createAccount() does), false for an existing one (as login() does).\n */\n public async adoptSession(opts: { migrateGuestData: boolean }): Promise<AdoptSessionResult> {\n if (!this.syncStrategy.canAuthenticate() || !this.syncStrategy.adoptSession) {\n throw new Error('Session adoption not supported by current sync strategy');\n }\n\n // Captured from memory, not the remote: the remote session already\n // belongs to the adopted user.\n const guestUsername = this._username.startsWith(GuestUsername) ? this._username : undefined;\n if (!guestUsername) {\n throw new Error(`Cannot adopt a session while logged in.\n Log out of account ${this.getUsername()} first.`);\n }\n\n const result = await this.syncStrategy.adoptSession(\n opts.migrateGuestData ? guestUsername : undefined\n );\n if (result.ok && result.username) {\n log(`Adopted session for ${result.username}`);\n this._username = result.username;\n try {\n localStorage.removeItem('sk-guest-uuid');\n } catch (e) {\n logger.warn('localStorage not available (Node.js environment):', e);\n }\n await this.init();\n }\n return result;\n }\n\n public async resetUserData(): Promise<{ status: Status; error?: string }> {\n // Only allow reset for local-only sync strategies\n if (this.syncStrategy.canAuthenticate()) {\n return {\n status: Status.error,\n error:\n 'Reset user data is only available for local-only mode. Use logout instead for remote sync.',\n };\n }\n\n try {\n const localDB = getLocalUserDB(this._username);\n\n // Get all documents to identify user data to clear\n const allDocs = await localDB.allDocs({ include_docs: false });\n\n // Identify documents to delete (preserve authentication and user identity)\n const docsToDelete = allDocs.rows\n .filter((row) => {\n const id = row.id;\n // Delete user progress data but preserve authentication and user identity\n return (\n id.startsWith(DocTypePrefixes[DocType.CARDRECORD]) || // Card interaction history\n id.startsWith(DocTypePrefixes[DocType.SCHEDULED_CARD]) || // Scheduled reviews\n id.startsWith(DocTypePrefixes[DocType.STRATEGY_STATE]) || // Strategy state (user prefs, progression)\n id.startsWith(DocTypePrefixes[DocType.USER_OUTCOME]) || // Evolutionary orchestration outcomes\n id.startsWith(DocTypePrefixes[DocType.STRATEGY_LEARNING_STATE]) || // Strategy learning state\n id === BaseUser.DOC_IDS.COURSE_REGISTRATIONS || // Course registrations\n id === BaseUser.DOC_IDS.CLASSROOM_REGISTRATIONS || // Classroom registrations\n id === BaseUser.DOC_IDS.CONFIG // User config\n );\n })\n .map((row) => ({ _id: row.id, _rev: row.value.rev, _deleted: true }));\n\n if (docsToDelete.length > 0) {\n await localDB.bulkDocs(docsToDelete);\n }\n\n // Reinitialize to create fresh default documents\n await this.init();\n\n return { status: Status.ok };\n } catch (error) {\n logger.error('Failed to reset user data:', error);\n return {\n status: Status.error,\n error: error instanceof Error ? error.message : 'Unknown error during reset',\n };\n }\n }\n\n public async logout() {\n if (!this.syncStrategy.canAuthenticate()) {\n // For strategies that don't support authentication, just switch to guest\n this._username = await this.syncStrategy.getCurrentUsername();\n await this.init();\n return { ok: true };\n }\n\n const ret = await this.syncStrategy.logout!();\n\n // Mint a FRESH guest identity on logout rather than re-adopting whatever\n // sk-guest-uuid happens to survive in localStorage. A stale UUID can point\n // at an already-consumed guest DB (one previously migrated into a real\n // account); re-adopting it would resurface that account's progress and, on\n // the next signup, migrate it into the new account. Clearing the pointer\n // forces accomodateGuest() to generate a new UUID + empty guest DB.\n try {\n localStorage.removeItem('sk-guest-uuid');\n } catch (e) {\n logger.warn('localStorage not available (Node.js environment):', e);\n }\n\n // return to 'guest' mode\n this._username = await this.syncStrategy.getCurrentUsername();\n await this.init();\n\n return ret;\n }\n\n public async get<T>(id: string): Promise<T & PouchDB.Core.RevisionIdMeta> {\n return this.localDB.get<T>(id);\n }\n\n public update<T extends PouchDB.Core.Document<object>>(id: string, update: Update<T>) {\n return this.updateQueue.update(id, update);\n }\n\n public async getCourseRegistrationsDoc(): Promise<\n CourseRegistrationDoc & PouchDB.Core.IdMeta & PouchDB.Core.GetMeta\n > {\n logger.debug(`Fetching courseRegistrations for ${this.getUsername()}`);\n\n let ret;\n\n try {\n const regDoc = await this.localDB.get<CourseRegistrationDoc>(\n BaseUser.DOC_IDS.COURSE_REGISTRATIONS\n );\n return regDoc;\n } catch (e) {\n const err = e as PouchError;\n if (err.status === 404) {\n if (!this.canMaterializeDefaults()) {\n throw new Error(\n `Cannot read course registrations for ${this._username}: the local mirror is ` +\n `unavailable (hydration state '${this._hydration.state}'). Refusing to create an ` +\n `empty registration doc — that would report an existing user as unregistered, and ` +\n `then lose to their real document once sync resumes.`\n );\n }\n await this.localDB.put<CourseRegistrationDoc>({\n _id: BaseUser.DOC_IDS.COURSE_REGISTRATIONS,\n courses: [],\n studyWeight: {},\n });\n ret = await this.getCourseRegistrationsDoc();\n } else {\n throw new Error(\n `Unexpected error ${JSON.stringify(e)} in getOrCreateCourseRegistrationDoc...`\n );\n }\n }\n\n return ret;\n }\n\n public async getActiveCourses() {\n const reg = await this.getCourseRegistrationsDoc();\n return reg.courses.filter((c) => {\n return c.status === undefined || c.status === 'active';\n });\n }\n\n /**\n * Returns a promise of the card IDs that the user has\n * a scheduled review for.\n *\n */\n public async getActiveCards() {\n const keys = getStartAndEndKeys(DocTypePrefixes[DocType.SCHEDULED_CARD]);\n\n const reviews = await this.remoteDB.allDocs<ScheduledCard>({\n startkey: keys.startkey,\n endkey: keys.endkey,\n include_docs: true,\n });\n\n return reviews.rows.map((r) => {\n return {\n courseID: r.doc!.courseId,\n cardID: r.doc!.cardId,\n };\n });\n }\n\n public async getActivityRecords(): Promise<ActivityRecord[]> {\n try {\n const hist = await this.getHistory();\n\n const allRecords: ActivityRecord[] = [];\n if (!Array.isArray(hist)) {\n logger.error('getHistory did not return an array:', hist);\n return allRecords;\n }\n\n // Sample the first few records to understand structure\n let sampleCount = 0;\n\n for (let i = 0; i < hist.length; i++) {\n try {\n if (hist[i] && Array.isArray(hist[i]!.records)) {\n hist[i]!.records.forEach((record: CardRecord) => {\n try {\n // Skip this record if timeStamp is missing\n if (!record.timeStamp) {\n return;\n }\n\n let timeStamp;\n\n // Handle different timestamp formats\n if (typeof record.timeStamp === 'object') {\n // It's likely a Moment object\n if (typeof record.timeStamp.toDate === 'function') {\n // It's definitely a Moment object\n timeStamp = record.timeStamp.toISOString();\n } else if (record.timeStamp instanceof Date) {\n // It's a Date object\n timeStamp = record.timeStamp.toISOString();\n } else {\n // Log a sample of unknown object types, but don't flood logger\n if (sampleCount < 3) {\n logger.warn('Unknown timestamp object type:', record.timeStamp);\n sampleCount++;\n }\n return;\n }\n } else if (typeof record.timeStamp === 'string') {\n // It's already a string, but make sure it's a valid date\n const date = new Date(record.timeStamp);\n if (isNaN(date.getTime())) {\n return; // Invalid date string\n }\n timeStamp = record.timeStamp;\n } else if (typeof record.timeStamp === 'number') {\n // Assume it's a Unix timestamp (milliseconds since epoch)\n timeStamp = new Date(record.timeStamp).toISOString();\n } else {\n // Unknown type, skip\n return;\n }\n\n allRecords.push({\n timeStamp,\n courseID: record.courseID || 'unknown',\n cardID: record.cardID || 'unknown',\n timeSpent: record.timeSpent || 0,\n type: 'card_view',\n });\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (err) {\n // Silently skip problematic records to avoid flooding logs\n }\n });\n }\n } catch (err) {\n logger.error('Error processing history item:', err);\n }\n }\n\n logger.debug(`Found ${allRecords.length} activity records`);\n return allRecords;\n } catch (err) {\n logger.error('Error in getActivityRecords:', err);\n return [];\n }\n }\n\n private async getReviewstoDate(targetDate: Moment, course_id?: string) {\n const keys = getStartAndEndKeys(DocTypePrefixes[DocType.SCHEDULED_CARD]);\n\n const reviews = await this.remoteDB.allDocs<ScheduledCard>({\n startkey: keys.startkey,\n endkey: keys.endkey,\n include_docs: true,\n });\n\n log(\n `Fetching ${this._username}'s scheduled reviews${\n course_id ? ` for course ${course_id}` : ''\n }.`\n );\n return reviews.rows\n .filter((r) => {\n if (r.id.startsWith(DocTypePrefixes[DocType.SCHEDULED_CARD])) {\n const date = moment.utc(\n r.id.substr(DocTypePrefixes[DocType.SCHEDULED_CARD].length),\n REVIEW_TIME_FORMAT\n );\n if (targetDate.isAfter(date)) {\n if (course_id === undefined || r.doc!.courseId === course_id) {\n return true;\n }\n }\n }\n })\n .map((r) => r.doc!);\n }\n\n public async getReviewsForcast(daysCount: number, course_id?: string) {\n const time = moment.utc().add(daysCount, 'days');\n return this.getReviewstoDate(time, course_id);\n }\n\n public async getPendingReviews(course_id?: string) {\n const now = moment.utc();\n return this.getReviewstoDate(now, course_id);\n }\n\n public async getScheduledReviewCount(course_id: string): Promise<number> {\n return (await this.getPendingReviews(course_id)).length;\n }\n\n public async getRegisteredCourses() {\n const regDoc = await this.getCourseRegistrationsDoc();\n return regDoc.courses.filter((c) => {\n return !c.status || c.status === 'active' || c.status === 'maintenance-mode';\n });\n }\n\n public async getCourseRegDoc(courseID: string) {\n const regDocs = await this.getCourseRegistrationsDoc();\n const ret = regDocs.courses.find((c) => c.courseID === courseID);\n if (ret) {\n return ret;\n } else {\n throw new Error(`Course registration not found for course ID: ${courseID}`);\n }\n }\n\n public async registerForCourse(course_id: string, previewMode: boolean = false) {\n return this.getCourseRegistrationsDoc()\n .then((doc: CourseRegistrationDoc) => {\n const status = previewMode ? 'preview' : 'active';\n logger.debug(`Registering for ${course_id} with status: ${status}`);\n\n const regItem: CourseRegistration = {\n status: status,\n courseID: course_id,\n user: true,\n admin: false,\n moderator: false,\n elo: {\n global: {\n score: 1000,\n count: 0,\n },\n tags: {},\n misc: {},\n },\n };\n\n if (\n doc.courses.filter((course) => {\n return course.courseID === regItem.courseID;\n }).length === 0\n ) {\n log(`It's a new course registration!`);\n doc.courses.push(regItem);\n doc.studyWeight[course_id] = 1;\n } else {\n doc.courses.forEach((c) => {\n log(`Found the previously registered course!`);\n if (c.courseID === course_id) {\n c.status = status;\n }\n });\n }\n\n return this.localDB.put<CourseRegistrationDoc>(doc);\n })\n .catch((e) => {\n log(`Registration failed because of: ${JSON.stringify(e)}`);\n throw e;\n });\n }\n public async dropCourse(course_id: string, dropStatus: CourseRegistration['status'] = 'dropped') {\n return this.getCourseRegistrationsDoc().then((doc) => {\n let index: number = -1;\n for (let i = 0; i < doc.courses.length; i++) {\n if (doc.courses[i].courseID === course_id) {\n index = i;\n }\n }\n\n if (index !== -1) {\n // remove from the relative-weighting of course study\n delete doc.studyWeight[course_id];\n // set drop status\n doc.courses[index].status = dropStatus;\n } else {\n throw new Error(\n `User ${this.getUsername()} is not currently registered for course ${course_id}`\n );\n }\n\n return this.localDB.put<CourseRegistrationDoc>(doc);\n });\n }\n\n public async getCourseInterface(courseId: string): Promise<UsrCrsDataInterface> {\n return new UsrCrsData(this, courseId);\n }\n\n public async getUserEditableCourses() {\n let courseIDs: string[] = [];\n\n const registeredCourses = await this.getCourseRegistrationsDoc();\n\n courseIDs = courseIDs.concat(\n registeredCourses.courses.map((course) => {\n return course.courseID;\n })\n );\n\n const cfgs = await Promise.all(\n courseIDs.map(async (id) => {\n return await getCredentialledCourseConfig(id);\n })\n );\n return cfgs;\n }\n\n public async getConfig(): Promise<UserConfig & PouchDB.Core.IdMeta & PouchDB.Core.GetMeta> {\n const defaultConfig: PouchDB.Core.Document<UserConfig> = {\n _id: BaseUser.DOC_IDS.CONFIG,\n darkMode: false,\n likesConfetti: false,\n sessionTimeLimit: 5,\n };\n\n try {\n const cfg = await this.localDB.get<UserConfig>(BaseUser.DOC_IDS.CONFIG);\n logger.debug('Raw config from DB:', cfg);\n\n return cfg;\n } catch (e) {\n const err = e as PouchError;\n if (err.name && err.name === 'not_found') {\n if (!this.canMaterializeDefaults()) {\n throw new Error(\n `Cannot read config for ${this._username}: the local mirror is unavailable ` +\n `(hydration state '${this._hydration.state}'). Refusing to write a default config ` +\n `over what may be an existing one.`\n );\n }\n await this.localDB.put<UserConfig>(defaultConfig);\n return this.getConfig();\n } else {\n logger.error(`Error setting user default config:`, e);\n throw new Error(`Error returning the user's configuration: ${JSON.stringify(e)}`);\n }\n }\n }\n\n public async setConfig(items: Partial<UserConfig>) {\n logger.debug(`Setting Config items ${JSON.stringify(items)}`);\n\n const c = await this.getConfig();\n const put = await this.localDB.put<UserConfig>({\n ...c,\n ...items,\n });\n\n if (put.ok) {\n logger.debug(`Config items set: ${JSON.stringify(items)}`);\n } else {\n logger.error(`Error setting config items: ${JSON.stringify(put)}`);\n }\n }\n\n /**\n *\n * This function should be called *only* by the pouchdb datalayer provider\n * auth store.\n *\n *\n * Anyone else seeking the current user should use the auth store's\n * exported `getCurrentUser` method.\n *\n */\n public static async instance(syncStrategy: SyncStrategy, username?: string): Promise<BaseUser> {\n if (username) {\n BaseUser._instance = new BaseUser(username, syncStrategy);\n await BaseUser._instance.init();\n return BaseUser._instance;\n } else if (BaseUser._instance && BaseUser._initialized) {\n // log(`USER.instance() returning user ${BaseUser._instance._username}`);\n return BaseUser._instance;\n } else if (BaseUser._instance) {\n return new Promise((resolve) => {\n (function waitForUser() {\n if (BaseUser._initialized) {\n return resolve(BaseUser._instance);\n } else {\n setTimeout(waitForUser, 50);\n }\n })();\n });\n } else {\n const guestUsername = await syncStrategy.getCurrentUsername();\n BaseUser._instance = new BaseUser(guestUsername, syncStrategy);\n await BaseUser._instance.init();\n return BaseUser._instance;\n }\n }\n\n private constructor(username: string, syncStrategy: SyncStrategy) {\n BaseUser._initialized = false;\n this._username = username;\n this.syncStrategy = syncStrategy;\n this.setDBandQ();\n }\n\n private setDBandQ() {\n this.localDB = getLocalUserDB(this._username);\n this.remoteDB = this.syncStrategy.setupRemoteDB(this._username);\n // writeDB follows local-first pattern: static mode writes to local, CouchDB writes to remote/local as appropriate\n this.writeDB = this.syncStrategy.getWriteDB\n ? this.syncStrategy.getWriteDB(this._username)\n : this.localDB;\n this.updateQueue = new UpdateQueue(this.localDB, this.writeDB);\n }\n\n private async init() {\n BaseUser._initialized = false;\n\n // Skip admin user\n if (this._username === 'admin') {\n BaseUser._initialized = true;\n return;\n }\n\n // Cancel replication left over from the previous identity BEFORE rebinding\n // the DB handles below. init() runs on every identity change (login,\n // logout, account creation, data reset), and each one points localDB /\n // remoteDB somewhere new — so without this, the prior sync keeps running\n // against handles nobody holds a reference to anymore.\n //\n // Logout is the case that bites: the guest branch of startSync() never\n // replaces the handle (it only ever assigns when a sync is actually\n // started), so the departing user's live sync survived indefinitely. Its\n // session cookie is gone by then, leaving it to 401-and-retry forever.\n this.syncStrategy.stopSync?.();\n\n this.setDBandQ();\n\n // Populate the local mirror BEFORE anything can read it, and before live\n // sync can push local state upward. See hydrateLocalMirror().\n //\n // Retained (not just awaited) so awaitHydration() can hand the same\n // promise to anything that asks mid-flight. Assigned synchronously with\n // respect to init()'s entry, so no caller can observe a previous\n // identity's promise here.\n this._hydrationPromise = this.hydrateLocalMirror();\n await this._hydrationPromise;\n\n // _hydratedSeq is set only by a hydration that just succeeded above, for\n // this identity — see hydrateLocalMirror(). Anything else leaves it\n // undefined and the live sync resumes from its own checkpoint.\n this.syncStrategy.startSync(this.localDB, this.remoteDB, this._hydratedSeq);\n this.applyDesignDocs().catch((error) => {\n log(`Error in applyDesignDocs background task: ${error}`);\n if (error && typeof error === 'object') {\n log(`Full error details in applyDesignDocs: ${JSON.stringify(error)}`);\n }\n });\n this.deduplicateReviews().catch((error) => {\n log(`Error in deduplicateReviews background task: ${error}`);\n if (error && typeof error === 'object') {\n log(`Full error details in background task: ${JSON.stringify(error)}`);\n }\n });\n BaseUser._initialized = true;\n }\n\n /**\n * Pull this account's documents into the local mirror, if that hasn't\n * happened on this device before.\n *\n * Runs between setDBandQ() and startSync() — after the handles exist, before\n * anything can observe an empty local DB or replicate one upward.\n *\n * Never throws: a failure is recorded as `failed` state and reported through\n * hydrationStatus(), because throwing here would abort init() and leave\n * BaseUser._initialized false forever (BaseUser.instance() polls it with no\n * ceiling). Callers decide what a failure means for them.\n */\n private async hydrateLocalMirror(): Promise<void> {\n // Clear first: init() reruns on every identity change, and a sequence from\n // the departing account would be meaningless against the incoming one's\n // database. Every path below either sets it or leaves it unset.\n this._hydratedSeq = undefined;\n\n // Guests and static-mode users have no remote — setupRemoteDB() hands back\n // the local database itself, so there is nothing to pull from.\n if (this.localDB.name === this.remoteDB.name || !this.syncStrategy.hydrate) {\n this._hydration = { state: 'not-required' };\n return;\n }\n\n if (await this.hasHydrationMarker()) {\n // A full pull already completed on this device, so local reads return\n // real data and live sync will close any gap. Blocking here would break\n // offline startup to re-fetch what we already have.\n this._hydration = { state: 'stale' };\n return;\n }\n\n this._hydration = { state: 'hydrating' };\n const start = Date.now();\n\n try {\n const { docsWritten, lastSeq } = await withTimeout(\n this.syncStrategy.hydrate(this.localDB, this.remoteDB),\n HYDRATION_TIMEOUT_MS,\n `Hydration of local mirror for ${this._username}`\n );\n this._hydratedSeq = lastSeq;\n await this.writeHydrationMarker();\n this._hydration = {\n state: 'hydrated',\n docsWritten,\n durationMs: Date.now() - start,\n };\n log(\n `Hydrated local mirror for ${this._username}: ` +\n `${docsWritten} docs in ${this._hydration.durationMs}ms`\n );\n } catch (e) {\n // Cancel the pull if it is merely slow rather than dead — otherwise it\n // races the live sync we are about to start over the same documents.\n this.syncStrategy.stopSync?.();\n this._hydration = {\n state: 'failed',\n durationMs: Date.now() - start,\n error: e instanceof Error ? e.message : String(e),\n };\n logger.error(`Failed to hydrate local mirror for ${this._username}:`, e);\n }\n }\n\n /**\n * Has a full pull completed on this device for the CURRENT account?\n *\n * The marker is a `_local/` document, which never replicates — so its\n * presence describes this device's mirror and cannot arrive from elsewhere.\n */\n private async hasHydrationMarker(): Promise<boolean> {\n try {\n const marker = await this.localDB.get<HydrationMarker>(HYDRATION_MARKER_ID);\n return marker.username === this._username;\n } catch {\n // Absent, or unreadable — either way, treat as never hydrated. The cost\n // of a false negative is one redundant pull.\n return false;\n }\n }\n\n private async writeHydrationMarker(): Promise<void> {\n try {\n let existingRev: string | undefined;\n try {\n existingRev = (await this.localDB.get<HydrationMarker>(HYDRATION_MARKER_ID))._rev;\n } catch {\n // First hydration on this device.\n }\n\n await this.localDB.put<HydrationMarker>({\n _id: HYDRATION_MARKER_ID,\n _rev: existingRev,\n username: this._username,\n hydratedAt: new Date().toISOString(),\n });\n } catch (e) {\n // Costs a redundant pull on next startup, not correctness.\n logger.warn(`Could not write hydration marker for ${this._username}: ${e}`);\n }\n }\n\n private static designDocs: DesignDoc[] = [\n {\n _id: '_design/reviewCards',\n views: {\n reviewCards: {\n map: `function (doc) {\n if (doc._id && doc._id.indexOf('card_review') === 0 && doc.courseId && doc.cardId) {\n emit(doc._id, doc.courseId + '-' + doc.cardId);\n }\n }`,\n },\n },\n },\n ];\n\n private async applyDesignDocs() {\n log(`Starting applyDesignDocs for user: ${this._username}`);\n log(`Remote DB name: ${this.remoteDB.name || 'unknown'}`);\n\n if (this._username === 'admin') {\n // Skip admin user\n log('Skipping design docs for admin user');\n return;\n }\n\n log(`Applying ${BaseUser.designDocs.length} design docs`);\n for (const doc of BaseUser.designDocs) {\n log(`Applying design doc: ${doc._id}`);\n try {\n // Try to get existing doc\n try {\n const existingDoc = await this.remoteDB.get(doc._id);\n // Update existing doc\n await this.remoteDB.put({\n ...doc,\n _rev: existingDoc._rev,\n });\n } catch (e: unknown) {\n // NB: PouchDB errors are plain objects ({error, reason, status, name,\n // message, ...}), not Error instances — `e instanceof Error` is false\n // for them. Check `.name` directly. The outer catch at line ~697\n // already does this correctly; mirror that style here so the\n // not_found → \"create new doc\" path actually fires for fresh user DBs.\n if ((e as { name?: string })?.name === 'not_found') {\n // Create new doc\n await this.remoteDB.put(doc);\n } else {\n throw e; // Re-throw unexpected errors\n }\n }\n } catch (error: unknown) {\n if ((error as any).name && (error as any).name === 'conflict') {\n logger.warn(`Design doc ${doc._id} update conflict - will retry`);\n // Wait a bit and try again\n await new Promise((resolve) => setTimeout(resolve, 1000));\n await this.applyDesignDoc(doc); // Recursive retry\n } else {\n logger.error(`Failed to apply design doc ${doc._id}:`, error);\n throw error;\n }\n }\n }\n }\n\n // Helper method for single doc update with retry\n private async applyDesignDoc(doc: DesignDoc, retries = 3): Promise<void> {\n try {\n const existingDoc = await this.remoteDB.get(doc._id);\n await this.remoteDB.put({\n ...doc,\n _rev: existingDoc._rev,\n });\n } catch (e: unknown) {\n // NB: PouchDB errors are plain objects, not Error instances — see\n // applyDesignDocs() above. Check `.name` directly so the conflict-retry\n // path actually fires.\n if ((e as { name?: string })?.name === 'conflict' && retries > 0) {\n await new Promise((resolve) => setTimeout(resolve, 1000));\n return this.applyDesignDoc(doc, retries - 1);\n }\n throw e;\n }\n }\n\n /**\n * Logs a record of the user's interaction with the card and returns the card's\n * up-to-date history.\n *\n * **Automatic Initialization:**\n * If this is the user's first interaction with the card (CardHistory doesn't exist),\n * this method automatically creates the CardHistory document with initial values\n * (lapses: 0, streak: 0, bestInterval: 0).\n *\n * **Error Handling:**\n * - Handles 404 errors by creating initial CardHistory document\n * - Re-throws all other errors from UpdateQueue\n *\n * // [ ] #db-refactor extract to a smaller scope - eg, UserStudySession\n *\n * @param record - The recent recorded interaction between user and card\n * @returns The updated state of the card's CardHistory data\n * @throws Error if document creation fails or non-404 database error occurs\n */\n\n public async putCardRecord<T extends CardRecord>(\n record: T\n ): Promise<CardHistory<CardRecord> & PouchDB.Core.RevisionIdMeta> {\n const cardHistoryID = getCardHistoryID(record.courseID, record.cardID);\n // stringify the current record to make it writable to couchdb\n record.timeStamp = moment.utc(record.timeStamp).toString() as unknown as Moment;\n\n try {\n const cardHistory = await this.update<CardHistory<T>>(\n cardHistoryID,\n function (h: CardHistory<T>) {\n h.records.push(record);\n h.bestInterval = h.bestInterval || 0;\n // Scheduling (SpacedRepetition.newQuestionInterval) re-derives\n // lapses/streak from `records` on every call, so these persisted\n // fields are informational — kept current so the stored doc reads\n // truthfully when inspected outside a session.\n if (areQuestionRecords(h)) {\n h.lapses = getLapses(h.records);\n h.streak = getStreak(h.records);\n } else {\n h.lapses = h.lapses || 0;\n h.streak = h.streak || 0;\n }\n return h;\n }\n );\n\n // Convert timestamps to moment objects\n cardHistory.records = cardHistory.records.map<T>((record) => {\n const ret: T = {\n ...(record as object),\n } as T;\n ret.timeStamp = moment.utc(record.timeStamp);\n return ret;\n });\n return cardHistory;\n } catch (e) {\n const reason = e as PouchError;\n if (reason.status === 404) {\n try {\n const initCardHistory: CardHistory<T> = {\n _id: cardHistoryID,\n cardID: record.cardID,\n courseID: record.courseID,\n records: [record],\n lapses: 0,\n streak: 0,\n bestInterval: 0,\n };\n const putResult = await this.writeDB.put<CardHistory<T>>(initCardHistory);\n return { ...initCardHistory, _rev: putResult.rev };\n } catch (creationError) {\n throw new Error(\n `Failed to create CardHistory for ${cardHistoryID}. Reason: ${creationError}`\n );\n }\n } else {\n throw new Error(`putCardRecord failed because of:\n name:${reason.name}\n error: ${reason.error}\n message: ${reason.message}`);\n }\n }\n }\n\n private async deduplicateReviews() {\n try {\n log('Starting deduplication of scheduled reviews...');\n log(`Remote DB name: ${this.remoteDB.name || 'unknown'}`);\n log(`Write DB name: ${this.writeDB.name || 'unknown'}`);\n /**\n * Maps the qualified-id of a scheduled review card to\n * the docId of the same scheduled review.\n *\n * EG: {\n * courseId-cardId: 'card_review_2021-06--17:12:165'\n * }\n */\n const reviewsMap: { [index: string]: string } = {};\n const duplicateDocIds: string[] = [];\n\n log(\n `Attempting to query remoteDB for reviewCards/reviewCards. Database: ${this.remoteDB.name || 'unknown'}`\n );\n const scheduledReviews = await this.remoteDB.query<{\n id: string;\n value: string;\n }>('reviewCards/reviewCards');\n\n log(`Found ${scheduledReviews.rows.length} scheduled reviews to process`);\n\n // First pass: identify duplicates\n scheduledReviews.rows.forEach((r) => {\n const qualifiedCardId = r.value; // courseId-cardId\n const docId = r.key; // card_review_2021-06--17:12:165\n\n if (reviewsMap[qualifiedCardId]) {\n // this card is scheduled more than once! mark the earlier one for deletion\n log(`Found duplicate scheduled review for card: ${qualifiedCardId}`);\n log(\n `Marking earlier review ${reviewsMap[qualifiedCardId]} for deletion, keeping ${docId}`\n );\n duplicateDocIds.push(reviewsMap[qualifiedCardId]);\n // replace with the later-dated scheduled review\n reviewsMap[qualifiedCardId] = docId;\n } else {\n // note that this card is scheduled for review\n reviewsMap[qualifiedCardId] = docId;\n }\n });\n\n // Second pass: remove duplicates\n if (duplicateDocIds.length > 0) {\n log(`Removing ${duplicateDocIds.length} duplicate reviews...`);\n const deletePromises = duplicateDocIds.map(async (docId) => {\n try {\n const doc = await this.remoteDB.get(docId);\n await this.writeDB.remove(doc);\n log(`Successfully removed duplicate review: ${docId}`);\n } catch (error) {\n log(`Failed to remove duplicate review ${docId}: ${error}`);\n }\n });\n\n await Promise.all(deletePromises);\n log(`Deduplication complete. Processed ${duplicateDocIds.length} duplicates`);\n } else {\n log('No duplicate reviews found');\n }\n } catch (error) {\n log(`Error during review deduplication: ${error}`);\n if (error && typeof error === 'object' && 'status' in error && error.status === 404) {\n log(\n `Database not found (404) during review deduplication. Database: ${this.remoteDB.name || 'unknown'}`\n );\n log(\n `This might indicate the user database doesn't exist or the reviewCards view isn't available`\n );\n }\n // Log full error details for debugging\n if (error && typeof error === 'object') {\n log(`Full error details: ${JSON.stringify(error)}`);\n }\n }\n }\n\n /**\n * Returns a promise of the card IDs that the user has\n * encountered in the past.\n *\n * @param course_id optional specification of individual course\n */\n async getSeenCards(course_id?: string) {\n // Doc IDs follow the pattern: cardH-{courseId}-{cardId}\n // (see getCardHistoryID in core/util)\n const basePrefix = DocTypePrefixes[DocType.CARDRECORD];\n let filterPrefix = basePrefix;\n if (course_id) {\n filterPrefix += `-${course_id}-`;\n }\n const docs = await filterAllDocsByPrefix(this.localDB, filterPrefix, {\n include_docs: false,\n });\n const ret: PouchDB.Core.DocumentId[] = [];\n docs.rows.forEach((row) => {\n if (row.id.startsWith(filterPrefix)) {\n // Strip the full prefix to return bare cardId\n ret.push(row.id.substr(filterPrefix.length));\n }\n });\n return ret;\n }\n\n /**\n *\n * @returns A promise of the cards that the user has seen in the past.\n */\n async getHistory() {\n const cards = await filterAllDocsByPrefix<CardHistory<CardRecord>>(\n this.remoteDB,\n DocTypePrefixes[DocType.CARDRECORD],\n {\n include_docs: true,\n attachments: false,\n }\n );\n return cards.rows.map((r) => r.doc);\n }\n\n async updateCourseSettings(course_id: string, settings: UserCourseSetting[]) {\n void this.getCourseRegistrationsDoc().then((doc) => {\n const crs = doc.courses.find((c) => c.courseID === course_id);\n if (crs) {\n if (crs.settings === null || crs.settings === undefined) {\n crs.settings = {};\n }\n settings.forEach((setting) => {\n crs!.settings![setting.key] = setting.value;\n });\n }\n\n return this.localDB.put(doc);\n });\n }\n async getCourseSettings(course_id: string) {\n const regDoc = await this.getCourseRegistrationsDoc();\n const crsDoc = regDoc.courses.find((c) => c.courseID === course_id);\n\n if (crsDoc) {\n return crsDoc.settings;\n } else {\n throw new Error(`getCourseSettings Failed:\n User is not registered for course ${course_id}`);\n }\n }\n\n private async getOrCreateClassroomRegistrationsDoc(): Promise<\n ClassroomRegistrationDoc & PouchDB.Core.IdMeta & PouchDB.Core.GetMeta\n > {\n let ret;\n\n try {\n ret = await this.remoteDB.get<ClassroomRegistrationDoc>(\n BaseUser.DOC_IDS.CLASSROOM_REGISTRATIONS\n );\n } catch (e) {\n const err = e as PouchError;\n\n if (err.status === 404) {\n // doc does not exist. Create it and then run this fcn again.\n await this.writeDB.put<ClassroomRegistrationDoc>({\n _id: BaseUser.DOC_IDS.CLASSROOM_REGISTRATIONS,\n registrations: [],\n });\n ret = await this.getOrCreateClassroomRegistrationsDoc();\n } else {\n // Properly serialize error information\n const errorDetails = {\n name: err.name,\n status: err.status,\n message: err.message,\n reason: err.reason,\n error: err.error,\n };\n\n logger.error(\n 'Database error in getOrCreateClassroomRegistrationsDoc (private method):',\n errorDetails\n );\n\n throw new Error(\n `Database error accessing classroom registrations: ${err.message || err.name || 'Unknown error'} (status: ${err.status})`\n );\n }\n }\n\n logger.debug(`Returning classroom registrations doc: ${JSON.stringify(ret)}`);\n return ret;\n }\n\n /**\n * Retrieves the list of active classroom IDs where the user is registered as a student.\n *\n * @returns Promise<string[]> - Array of classroom IDs, or empty array if classroom\n * registration document is unavailable due to database errors\n *\n * @description This method gracefully handles database connectivity issues by returning\n * an empty array when the classroom registrations document cannot be accessed.\n * This ensures that users can still access other application features even\n * when classroom functionality is temporarily unavailable.\n */\n public async getActiveClasses(): Promise<string[]> {\n try {\n return (await this.getOrCreateClassroomRegistrationsDoc()).registrations\n .filter((c) => c.registeredAs === 'student')\n .map((c) => c.classID);\n } catch (error) {\n logger.warn(\n 'Failed to load classroom registrations, continuing without classroom data:',\n error\n );\n // Return empty array so user can still access other features\n return [];\n }\n }\n\n public async scheduleCardReview(review: {\n user: string;\n course_id: string;\n card_id: PouchDB.Core.DocumentId;\n time: Moment;\n scheduledFor: ScheduledCard['scheduledFor'];\n schedulingAgentId: ScheduledCard['schedulingAgentId'];\n }) {\n return scheduleCardReviewLocal(this.writeDB, review);\n }\n public async removeScheduledCardReview(reviewId: string): Promise<void> {\n return removeScheduledCardReviewLocal(this.writeDB, reviewId);\n }\n\n public async registerForClassroom(\n _classId: string,\n _registerAs: 'student' | 'teacher' | 'aide' | 'admin'\n ): Promise<PouchDB.Core.Response> {\n return registerUserForClassroom(this._username, _classId, _registerAs);\n }\n\n public async dropFromClassroom(classId: string): Promise<PouchDB.Core.Response> {\n return dropUserFromClassroom(this._username, classId);\n }\n public async getUserClassrooms(): Promise<ClassroomRegistrationDoc> {\n return getUserClassrooms(this._username);\n }\n\n public async updateUserElo(courseId: string, elo: CourseElo): Promise<PouchDB.Core.Response> {\n return updateUserElo(this._username, courseId, elo);\n }\n\n public async getStrategyState<T>(courseId: string, strategyKey: string): Promise<T | null> {\n const docId = buildStrategyStateId(courseId, strategyKey);\n try {\n const doc = await this.localDB.get<StrategyStateDoc<T>>(docId);\n return doc.data;\n } catch (e) {\n const err = e as PouchError;\n if (err.status === 404) {\n // `null` here means \"this user has no such state\" — a first-run signal\n // consumers act on. When the mirror is untrusted we cannot honestly say\n // that, so fail instead of reporting an established user as new.\n if (!this.canMaterializeDefaults()) {\n throw new Error(\n `Cannot read strategy state '${strategyKey}' for ${this._username}: the local mirror ` +\n `is unavailable (hydration state '${this._hydration.state}').`\n );\n }\n return null;\n }\n throw e;\n }\n }\n\n public async putStrategyState<T>(courseId: string, strategyKey: string, data: T): Promise<void> {\n const docId = buildStrategyStateId(courseId, strategyKey);\n let existingRev: string | undefined;\n\n try {\n const existing = await this.localDB.get<StrategyStateDoc<T>>(docId);\n existingRev = existing._rev;\n } catch (e) {\n const err = e as PouchError;\n if (err.status !== 404) {\n throw e;\n }\n }\n\n const doc: StrategyStateDoc<T> = {\n _id: docId,\n _rev: existingRev,\n docType: DocType.STRATEGY_STATE,\n courseId,\n strategyKey,\n data,\n updatedAt: new Date().toISOString(),\n };\n\n await this.localDB.put(doc);\n }\n\n /**\n * Open and close write the same `_id`, so the 409 path is the expected\n * route for the second write, not an error case.\n */\n public async putStudySession(doc: StudySessionDoc): Promise<void> {\n try {\n await this.localDB.put(doc);\n } catch (err: any) {\n if (err.status === 409) {\n const existing = await this.localDB.get(doc._id);\n await this.localDB.put({ ...doc, _rev: existing._rev });\n } else {\n throw err;\n }\n }\n }\n\n public async getStudySessions(courseId?: string): Promise<StudySessionDoc[]> {\n const prefix = courseId\n ? `${DocTypePrefixes[DocType.STUDY_SESSION]}::${courseId}::`\n : `${DocTypePrefixes[DocType.STUDY_SESSION]}::`;\n const keys = getStartAndEndKeys(prefix);\n\n const res = await this.localDB.allDocs<StudySessionDoc>({\n startkey: keys.startkey,\n endkey: keys.endkey,\n include_docs: true,\n });\n\n return res.rows\n .map((r) => r.doc)\n .filter((d): d is StudySessionDoc & PouchDB.Core.RevisionIdMeta => !!d)\n .sort((a, b) => b.startTime.localeCompare(a.startTime));\n }\n\n public async putUserOutcome(record: UserOutcomeRecord): Promise<void> {\n try {\n await this.localDB.put(record);\n } catch (err: any) {\n if (err.status === 409) {\n // Overwrite if exists\n const existing = await this.localDB.get(record._id);\n (record as any)._rev = existing._rev;\n await this.localDB.put(record);\n } else {\n throw err;\n }\n }\n }\n\n public async deleteStrategyState(courseId: string, strategyKey: string): Promise<void> {\n const docId = buildStrategyStateId(courseId, strategyKey);\n try {\n const doc = await this.localDB.get(docId);\n await this.localDB.remove(doc);\n } catch (e) {\n const err = e as PouchError;\n if (err.status === 404) {\n return;\n }\n throw e;\n }\n }\n}\n\nexport function accomodateGuest(): {\n username: string;\n firstVisit: boolean;\n} {\n logger.log('[funnel] accomodateGuest() called');\n\n // Check if localStorage is available (browser environment)\n if (typeof localStorage === 'undefined') {\n logger.log(\n '[funnel] localStorage not available (Node.js environment), returning default guest'\n );\n return {\n username: GuestUsername + 'nodejs-test',\n firstVisit: true,\n };\n }\n\n const dbUUID = 'sk-guest-uuid';\n let firstVisit: boolean;\n\n const existingUUID = localStorage.getItem(dbUUID);\n logger.log('[funnel] Checking localStorage for key:', dbUUID);\n logger.log('[funnel] Existing UUID value:', existingUUID);\n logger.log('[funnel] existingUUID !== null:', existingUUID !== null);\n\n if (existingUUID !== null) {\n firstVisit = false;\n logger.log(`[funnel] Returning guest ${existingUUID} \"logging in\".`);\n } else {\n firstVisit = true;\n logger.log('[funnel] No existing UUID, generating new one...');\n const uuid = generateUUID();\n logger.log('[funnel] Generated UUID:', uuid);\n logger.log('[funnel] UUID length:', uuid.length);\n\n try {\n localStorage.setItem(dbUUID, uuid);\n logger.log('[funnel] Successfully stored UUID in localStorage');\n const verification = localStorage.getItem(dbUUID);\n logger.log('[funnel] Verification read from localStorage:', verification);\n } catch (e) {\n logger.error('[funnel] ERROR storing UUID:', e);\n }\n\n logger.log(`[funnel] Accommodating a new guest with account: ${uuid}`);\n }\n\n const finalUUID = localStorage.getItem(dbUUID);\n const finalUsername = GuestUsername + finalUUID;\n logger.log('[funnel] Final UUID from localStorage:', finalUUID);\n logger.log('[funnel] GuestUsername constant:', GuestUsername);\n logger.log('[funnel] Final username to return:', finalUsername);\n\n return {\n username: finalUsername,\n firstVisit: firstVisit,\n };\n\n // Use cryptographically secure UUID generation\n function generateUUID() {\n logger.log('[funnel] Inside generateUUID()');\n\n // Use crypto.randomUUID() if available (Node 14.17+ / modern browsers)\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n const uuid = crypto.randomUUID();\n logger.log('[funnel] Generated UUID using crypto.randomUUID():', uuid);\n return uuid;\n }\n\n // Fallback for older environments: use crypto.getRandomValues()\n if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n\n // Set version (4) and variant bits according to RFC 4122\n bytes[6] = (bytes[6] & 0x0f) | 0x40; // Version 4\n bytes[8] = (bytes[8] & 0x3f) | 0x80; // Variant 10\n\n const uuid = [\n Array.from(bytes.slice(0, 4))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join(''),\n Array.from(bytes.slice(4, 6))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join(''),\n Array.from(bytes.slice(6, 8))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join(''),\n Array.from(bytes.slice(8, 10))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join(''),\n Array.from(bytes.slice(10, 16))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join(''),\n ].join('-');\n\n logger.log('[funnel] Generated UUID using crypto.getRandomValues():', uuid);\n return uuid;\n }\n\n // Last resort fallback (should never happen in modern environments)\n logger.warn('[funnel] crypto API not available, using timestamp-based UUID (NOT SECURE)');\n let d = new Date().getTime();\n if (typeof performance !== 'undefined' && typeof performance.now === 'function') {\n d += performance.now();\n }\n const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (d + Math.random() * 16) % 16 | 0;\n d = Math.floor(d / 16);\n return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);\n });\n logger.log('[funnel] Generated UUID (fallback):', uuid);\n return uuid;\n }\n}\n\nconst userCoursesDoc = 'CourseRegistrations';\nconst userClassroomsDoc = 'ClassroomRegistrations';\n\nasync function getOrCreateClassroomRegistrationsDoc(\n user: string\n): Promise<ClassroomRegistrationDoc & PouchDB.Core.IdMeta & PouchDB.Core.GetMeta> {\n let ret;\n\n try {\n ret = await getLocalUserDB(user).get<ClassroomRegistrationDoc>(userClassroomsDoc);\n } catch (e) {\n const err = e as PouchError;\n\n if (err.status === 404) {\n // doc does not exist. Create it and then run this fcn again.\n await getLocalUserDB(user).put<ClassroomRegistrationDoc>({\n _id: userClassroomsDoc,\n registrations: [],\n });\n ret = await getOrCreateClassroomRegistrationsDoc(user);\n } else {\n // Properly serialize error information\n const errorDetails = {\n name: err.name,\n status: err.status,\n message: err.message,\n reason: err.reason,\n error: err.error,\n };\n\n logger.error(\n 'Database error in getOrCreateClassroomRegistrationsDoc (standalone function):',\n errorDetails\n );\n\n throw new Error(\n `Database error accessing classroom registrations: ${err.message || err.name || 'Unknown error'} (status: ${err.status})`\n );\n }\n }\n\n return ret;\n}\n\nasync function getOrCreateCourseRegistrationsDoc(\n user: string\n): Promise<CourseRegistrationDoc & PouchDB.Core.IdMeta & PouchDB.Core.GetMeta> {\n let ret;\n\n try {\n ret = await getLocalUserDB(user).get<CourseRegistrationDoc>(userCoursesDoc);\n } catch (e) {\n const err = e as PouchError;\n if (err.status === 404) {\n // doc does not exist. Create it and then run this fcn again.\n await getLocalUserDB(user).put<CourseRegistrationDoc>({\n _id: userCoursesDoc,\n courses: [],\n studyWeight: {},\n });\n ret = await getOrCreateCourseRegistrationsDoc(user);\n } else {\n throw new Error(\n `Unexpected error ${JSON.stringify(e)} in getOrCreateCourseRegistrationDoc...`\n );\n }\n }\n\n return ret;\n}\n\nexport async function updateUserElo(user: string, course_id: string, elo: CourseElo) {\n const regDoc = await getOrCreateCourseRegistrationsDoc(user);\n const course = regDoc.courses.find((c) => c.courseID === course_id)!;\n course.elo = elo;\n return getLocalUserDB(user).put(regDoc);\n}\n\nexport async function registerUserForClassroom(\n user: string,\n classID: string,\n registerAs: 'student' | 'teacher' | 'aide' | 'admin'\n) {\n log(`Registering user: ${user} in course: ${classID}`);\n return getOrCreateClassroomRegistrationsDoc(user).then((doc) => {\n const regItem = {\n classID: classID,\n registeredAs: registerAs,\n };\n\n if (\n doc.registrations.filter((reg) => {\n return reg.classID === regItem.classID && reg.registeredAs === regItem.registeredAs;\n }).length === 0\n ) {\n doc.registrations.push(regItem);\n } else {\n log(`User ${user} is already registered for class ${classID}`);\n }\n\n return getLocalUserDB(user).put(doc);\n });\n}\n\nexport async function dropUserFromClassroom(user: string, classID: string) {\n return getOrCreateClassroomRegistrationsDoc(user).then((doc) => {\n let index: number = -1;\n\n for (let i = 0; i < doc.registrations.length; i++) {\n if (doc.registrations[i].classID === classID) {\n index = i;\n }\n }\n\n if (index !== -1) {\n doc.registrations.splice(index, 1);\n }\n return getLocalUserDB(user).put(doc);\n });\n}\n\nexport async function getUserClassrooms(user: string) {\n return getOrCreateClassroomRegistrationsDoc(user);\n}\n"],"mappings":";;;;;;;;;;;;;;;AA6CA,MAAM,OAAO,MAAW;AACtB,QAAO,KAAK,EAAE;;;;;;;;AAoBhB,MAAM,uBAAuB;;;;;;;AAQ7B,SAAS,YAAe,GAAe,IAAY,OAA2B;CAC5E,IAAI;AAEJ,QAAO,QAAQ,KAAK,CAClB,GACA,IAAI,SAAgB,UAAU,WAAW;AACvC,UAAQ,iBAAiB,uBAAO,IAAI,MAAM,GAAG,MAAM,mBAAmB,GAAG,IAAI,CAAC,EAAE,GAAG;GACnF,CACH,CAAC,CAAC,cAAc;AACf,MAAI,UAAU,KAAA,EACZ,cAAa,MAAM;GAErB;;;;;;AAOJ,IAAa,WAAb,MAAa,SAAqD;CAChE,OAAe;CACf,OAAe,eAAwB;CAEvC,OAAc,MAAM,cAAsC;AACxD,SAAO,IAAI,SAAS,MAAM,aAAa;;CAGzC,OAAgB,UAAU;EACxB,QAAQ;EACR,sBAAsB;EACtB,yBAAyB;EAC1B;CAGD;CACA;CAE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qC,KAAK,CAAC,MAAM,QAAQ;EAC9D,IAAI,QAAgB;AAEpB,OAAK,IAAI,IAAI,GAAG,IAAI,IAAI,cAAc,QAAQ,IAC5C,KAAI,IAAI,cAAc,GAAG,YAAY,QACnC,SAAQ;AAIZ,MAAI,UAAU,GACZ,KAAI,cAAc,OAAO,OAAO,EAAE;AAEpC,SAAO,eAAe,KAAK,CAAC,IAAI,IAAI;GACpC;;AAGJ,eAAsB,kBAAkB,MAAc;AACpD,QAAO,qCAAqC,KAAK"}
1
+ {"version":3,"file":"BaseUserDB.mjs","names":[],"sources":["../../../src/impl/common/BaseUserDB.ts"],"sourcesContent":["import {\n DocType,\n DocTypePrefixes,\n StrategyStateDoc,\n buildStrategyStateId,\n HYDRATION_MARKER_ID,\n type HydrationMarker,\n type UserHydrationStatus,\n} from '@db/core';\nimport { areQuestionRecords, getCardHistoryID } from '@db/core/util';\nimport { CourseElo, Status } from '@vue-skuilder/common';\nimport moment, { Moment } from 'moment';\nimport { GuestUsername } from '../../core/types/types-legacy';\nimport { logger } from '../../util/logger';\n\nimport {\n ClassroomRegistrationDoc,\n UserCourseSetting,\n UserDBInterface,\n UsrCrsDataInterface,\n} from '@db/core';\nimport {\n ActivityRecord,\n CourseRegistration,\n CourseRegistrationDoc,\n ScheduledCard,\n UserConfig,\n} from '@db/core/types/user';\nimport { DocumentUpdater, getLapses, getStreak } from '@db/study';\nimport { CardHistory, CardRecord } from '../../core/types/types-legacy';\nimport { UserOutcomeRecord } from '../../core/types/userOutcome';\nimport { StudySessionDoc } from '../../core/types/studySession';\nimport type { SyncStrategy } from './SyncStrategy';\nimport { filterAllDocsByPrefix, getStartAndEndKeys, REVIEW_TIME_FORMAT } from './userDBKeys';\nimport {\n getLocalUserDB,\n scheduleCardReviewLocal,\n removeScheduledCardReviewLocal,\n} from './userDBHelpers';\nimport { PouchError } from '../couch/types';\nimport type { AdoptSessionResult } from './types';\nimport UpdateQueue, { Update } from '../couch/updateQueue';\nimport { UsrCrsData } from '../couch/user-course-relDB';\nimport { getCredentialledCourseConfig } from '../couch/index';\n\nconst log = (s: any) => {\n logger.info(s);\n};\n\n// logger.log(`Connecting to remote: ${remoteStr}`);\n\ninterface DesignDoc {\n _id: string;\n views: {\n [viewName: string]: {\n map: string; // String representation of the map function\n };\n };\n}\n\n/**\n * Ceiling on the initial pull of a user's data before we give up and report\n * `failed`. Generous relative to the expected payload (a user database is a\n * config doc, registrations, strategy state, and per-card history), so hitting\n * it indicates a genuinely unusable connection rather than a large account.\n */\nconst HYDRATION_TIMEOUT_MS = 15_000;\n\n/**\n * Reject if `p` has not settled within `ms`.\n *\n * Note the underlying work is not cancelled by this — callers that need the\n * operation stopped must do so themselves.\n */\nfunction withTimeout<T>(p: Promise<T>, ms: number, label: string): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n return Promise.race([\n p,\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);\n }),\n ]).finally(() => {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n }) as Promise<T>;\n}\n\n/**\n * Base user database implementation that uses a pluggable sync strategy.\n * Handles local storage operations and delegates sync/remote operations to the strategy.\n */\nexport class BaseUser implements UserDBInterface, DocumentUpdater {\n private static _instance: BaseUser;\n private static _initialized: boolean = false;\n\n public static Dummy(syncStrategy: SyncStrategy): BaseUser {\n return new BaseUser('Me', syncStrategy);\n }\n\n static readonly DOC_IDS = {\n CONFIG: 'CONFIG',\n COURSE_REGISTRATIONS: 'CourseRegistrations',\n CLASSROOM_REGISTRATIONS: 'ClassroomRegistrations',\n };\n\n // private email: string;\n private _username: string;\n private syncStrategy: SyncStrategy;\n\n public getUsername(): string {\n return this._username;\n }\n\n public isLoggedIn(): boolean {\n return !this._username.startsWith(GuestUsername);\n }\n\n public remote(): PouchDB.Database {\n return this.remoteDB;\n }\n\n private localDB!: PouchDB.Database;\n private remoteDB!: PouchDB.Database;\n private writeDB!: PouchDB.Database; // Database to use for write operations (local-first approach)\n private updateQueue!: UpdateQueue;\n\n private _hydration: UserHydrationStatus = { state: 'not-required' };\n /** In-flight hydration, so concurrent callers can wait for a real answer. */\n private _hydrationPromise: Promise<void> | null = null;\n /**\n * Sequence the local mirror was filled to by a hydration that succeeded in\n * THIS init(), handed to startSync() so the live pull can skip history it\n * would otherwise re-walk. Undefined whenever there is no such guarantee —\n * hydration skipped, not required, or failed. Never persisted; see the\n * `since` note in CouchDBSyncStrategy.startSync().\n */\n private _hydratedSeq?: string | number;\n\n /**\n * How far the local mirror can be trusted, RIGHT NOW. See\n * {@link UserHydrationStatus}.\n *\n * This is a snapshot, and during login it can legitimately read\n * `hydrating` — prefer awaitHydration() anywhere a decision hangs on the\n * answer.\n */\n public hydrationStatus(): UserHydrationStatus {\n return { ...this._hydration };\n }\n\n /**\n * The hydration status once it has settled — never `hydrating`.\n *\n * Resolves immediately unless a pull is in flight. Exists for callers that\n * must decide something (a route guard, a first-run branch) and would\n * otherwise sample `hydrating` and guess. Since init() is awaited by both\n * app startup and login(), that only happens when something navigates\n * concurrently with a login still in progress — a window that stretches to\n * HYDRATION_TIMEOUT_MS on a slow connection.\n */\n public async awaitHydration(): Promise<UserHydrationStatus> {\n // hydrateLocalMirror() records failures rather than throwing, so this\n // cannot reject — but a stray rejection must not become the caller's\n // problem when a status is available either way.\n try {\n await this._hydrationPromise;\n } catch {\n // fall through to the recorded status\n }\n return this.hydrationStatus();\n }\n\n /**\n * Whether a missing document may be treated as genuinely absent, allowing\n * callers to create it with defaults.\n *\n * False only when hydration failed or is still running: a 404 then may just\n * mean \"not pulled down yet\", and materializing a default would both lie to\n * the user and, once live sync starts, push a rev-1 document that loses to\n * the real one — silently discarding it.\n */\n private canMaterializeDefaults(): boolean {\n return this._hydration.state !== 'failed' && this._hydration.state !== 'hydrating';\n }\n\n public async createAccount(\n username: string,\n password: string\n ): Promise<{\n status: Status;\n error: string;\n }> {\n if (!this.syncStrategy.canCreateAccount()) {\n throw new Error('Account creation not supported by current sync strategy');\n }\n\n if (!this._username.startsWith(GuestUsername)) {\n throw new Error(\n `Cannot create a new account while logged in:\nCurrently logged-in as ${this._username}.`\n );\n }\n\n const result = await this.syncStrategy.createAccount!(username, password);\n\n // If account creation was successful, update the username and reinitialize\n if (result.status === Status.ok) {\n log(`Account created successfully, updating username to ${username}`);\n this._username = username;\n try {\n localStorage.removeItem('sk-guest-uuid');\n } catch (e) {\n logger.warn('localStorage not available (Node.js environment):', e);\n }\n await this.init();\n }\n\n return {\n status: result.status,\n error: result.error || '',\n };\n }\n public async login(username: string, password: string) {\n if (!this.syncStrategy.canAuthenticate()) {\n throw new Error('Authentication not supported by current sync strategy');\n }\n\n if (!this._username.startsWith(GuestUsername) && this._username != username) {\n if (this._username != username) {\n throw new Error(`Cannot change accounts while logged in.\n Log out of account ${this.getUsername()} before logging in as ${username}.`);\n }\n logger.warn(`User ${this._username} is already logged in, but executing login again.`);\n }\n\n const loginResult = await this.syncStrategy.authenticate!(username, password);\n if (loginResult.ok) {\n log(`Logged in as ${username}`);\n this._username = username;\n try {\n localStorage.removeItem('sk-guest-uuid');\n } catch (e) {\n logger.warn('localStorage not available (Node.js environment):', e);\n }\n await this.init();\n }\n return loginResult;\n }\n\n /**\n * Adopt a remote session that was established outside this client — e.g. a\n * backend verified a third-party sign-in (Google) and set the session cookie\n * on its response. Afterwards the user is logged in exactly as after\n * login(): username switched, guest pointer cleared, init() re-run.\n *\n * @param opts.migrateGuestData Carry the current guest account's local data\n * into the adopted account. Pass true for a freshly created account (as\n * createAccount() does), false for an existing one (as login() does).\n */\n public async adoptSession(opts: { migrateGuestData: boolean }): Promise<AdoptSessionResult> {\n if (!this.syncStrategy.canAuthenticate() || !this.syncStrategy.adoptSession) {\n throw new Error('Session adoption not supported by current sync strategy');\n }\n\n // Captured from memory, not the remote: the remote session already\n // belongs to the adopted user.\n const guestUsername = this._username.startsWith(GuestUsername) ? this._username : undefined;\n if (!guestUsername) {\n throw new Error(`Cannot adopt a session while logged in.\n Log out of account ${this.getUsername()} first.`);\n }\n\n const result = await this.syncStrategy.adoptSession(\n opts.migrateGuestData ? guestUsername : undefined\n );\n if (result.ok && result.username) {\n log(`Adopted session for ${result.username}`);\n this._username = result.username;\n try {\n localStorage.removeItem('sk-guest-uuid');\n } catch (e) {\n logger.warn('localStorage not available (Node.js environment):', e);\n }\n await this.init();\n }\n return result;\n }\n\n public async resetUserData(): Promise<{ status: Status; error?: string }> {\n // Only allow reset for local-only sync strategies\n if (this.syncStrategy.canAuthenticate()) {\n return {\n status: Status.error,\n error:\n 'Reset user data is only available for local-only mode. Use logout instead for remote sync.',\n };\n }\n\n try {\n const localDB = getLocalUserDB(this._username);\n\n // Get all documents to identify user data to clear\n const allDocs = await localDB.allDocs({ include_docs: false });\n\n // Identify documents to delete (preserve authentication and user identity)\n const docsToDelete = allDocs.rows\n .filter((row) => {\n const id = row.id;\n // Delete user progress data but preserve authentication and user identity\n return (\n id.startsWith(DocTypePrefixes[DocType.CARDRECORD]) || // Card interaction history\n id.startsWith(DocTypePrefixes[DocType.SCHEDULED_CARD]) || // Scheduled reviews\n id.startsWith(DocTypePrefixes[DocType.STRATEGY_STATE]) || // Strategy state (user prefs, progression)\n id.startsWith(DocTypePrefixes[DocType.USER_OUTCOME]) || // Evolutionary orchestration outcomes\n id.startsWith(DocTypePrefixes[DocType.STRATEGY_LEARNING_STATE]) || // Strategy learning state\n id === BaseUser.DOC_IDS.COURSE_REGISTRATIONS || // Course registrations\n id === BaseUser.DOC_IDS.CLASSROOM_REGISTRATIONS || // Classroom registrations\n id === BaseUser.DOC_IDS.CONFIG // User config\n );\n })\n .map((row) => ({ _id: row.id, _rev: row.value.rev, _deleted: true }));\n\n if (docsToDelete.length > 0) {\n await localDB.bulkDocs(docsToDelete);\n }\n\n // Reinitialize to create fresh default documents\n await this.init();\n\n return { status: Status.ok };\n } catch (error) {\n logger.error('Failed to reset user data:', error);\n return {\n status: Status.error,\n error: error instanceof Error ? error.message : 'Unknown error during reset',\n };\n }\n }\n\n public async logout() {\n if (!this.syncStrategy.canAuthenticate()) {\n // For strategies that don't support authentication, just switch to guest\n this._username = await this.syncStrategy.getCurrentUsername();\n await this.init();\n return { ok: true };\n }\n\n const ret = await this.syncStrategy.logout!();\n\n // Mint a FRESH guest identity on logout rather than re-adopting whatever\n // sk-guest-uuid happens to survive in localStorage. A stale UUID can point\n // at an already-consumed guest DB (one previously migrated into a real\n // account); re-adopting it would resurface that account's progress and, on\n // the next signup, migrate it into the new account. Clearing the pointer\n // forces accomodateGuest() to generate a new UUID + empty guest DB.\n try {\n localStorage.removeItem('sk-guest-uuid');\n } catch (e) {\n logger.warn('localStorage not available (Node.js environment):', e);\n }\n\n // return to 'guest' mode\n this._username = await this.syncStrategy.getCurrentUsername();\n await this.init();\n\n return ret;\n }\n\n public async get<T>(id: string): Promise<T & PouchDB.Core.RevisionIdMeta> {\n return this.localDB.get<T>(id);\n }\n\n public update<T extends PouchDB.Core.Document<object>>(id: string, update: Update<T>) {\n return this.updateQueue.update(id, update);\n }\n\n /**\n * Create a default doc after a 404. Concurrent first reads (e.g. two\n * components on a brand-new user) both see the 404 and both create; the\n * loser's conflict just means the doc now exists, which is what it wanted.\n */\n private async putDefaultUnlessCreated<T extends object>(doc: PouchDB.Core.PutDocument<T>) {\n try {\n await this.localDB.put<T>(doc);\n } catch (e) {\n if ((e as PouchError).status !== 409) throw e;\n }\n }\n\n public async getCourseRegistrationsDoc(): Promise<\n CourseRegistrationDoc & PouchDB.Core.IdMeta & PouchDB.Core.GetMeta\n > {\n logger.debug(`Fetching courseRegistrations for ${this.getUsername()}`);\n\n let ret;\n\n try {\n const regDoc = await this.localDB.get<CourseRegistrationDoc>(\n BaseUser.DOC_IDS.COURSE_REGISTRATIONS\n );\n return regDoc;\n } catch (e) {\n const err = e as PouchError;\n if (err.status === 404) {\n if (!this.canMaterializeDefaults()) {\n throw new Error(\n `Cannot read course registrations for ${this._username}: the local mirror is ` +\n `unavailable (hydration state '${this._hydration.state}'). Refusing to create an ` +\n `empty registration doc — that would report an existing user as unregistered, and ` +\n `then lose to their real document once sync resumes.`\n );\n }\n await this.putDefaultUnlessCreated<CourseRegistrationDoc>({\n _id: BaseUser.DOC_IDS.COURSE_REGISTRATIONS,\n courses: [],\n studyWeight: {},\n });\n ret = await this.getCourseRegistrationsDoc();\n } else {\n throw new Error(\n `Unexpected error ${JSON.stringify(e)} in getOrCreateCourseRegistrationDoc...`\n );\n }\n }\n\n return ret;\n }\n\n public async getActiveCourses() {\n const reg = await this.getCourseRegistrationsDoc();\n return reg.courses.filter((c) => {\n return c.status === undefined || c.status === 'active';\n });\n }\n\n /**\n * Returns a promise of the card IDs that the user has\n * a scheduled review for.\n *\n */\n public async getActiveCards() {\n const keys = getStartAndEndKeys(DocTypePrefixes[DocType.SCHEDULED_CARD]);\n\n const reviews = await this.remoteDB.allDocs<ScheduledCard>({\n startkey: keys.startkey,\n endkey: keys.endkey,\n include_docs: true,\n });\n\n return reviews.rows.map((r) => {\n return {\n courseID: r.doc!.courseId,\n cardID: r.doc!.cardId,\n };\n });\n }\n\n public async getActivityRecords(): Promise<ActivityRecord[]> {\n try {\n const hist = await this.getHistory();\n\n const allRecords: ActivityRecord[] = [];\n if (!Array.isArray(hist)) {\n logger.error('getHistory did not return an array:', hist);\n return allRecords;\n }\n\n // Sample the first few records to understand structure\n let sampleCount = 0;\n\n for (let i = 0; i < hist.length; i++) {\n try {\n if (hist[i] && Array.isArray(hist[i]!.records)) {\n hist[i]!.records.forEach((record: CardRecord) => {\n try {\n // Skip this record if timeStamp is missing\n if (!record.timeStamp) {\n return;\n }\n\n let timeStamp;\n\n // Handle different timestamp formats\n if (typeof record.timeStamp === 'object') {\n // It's likely a Moment object\n if (typeof record.timeStamp.toDate === 'function') {\n // It's definitely a Moment object\n timeStamp = record.timeStamp.toISOString();\n } else if (record.timeStamp instanceof Date) {\n // It's a Date object\n timeStamp = record.timeStamp.toISOString();\n } else {\n // Log a sample of unknown object types, but don't flood logger\n if (sampleCount < 3) {\n logger.warn('Unknown timestamp object type:', record.timeStamp);\n sampleCount++;\n }\n return;\n }\n } else if (typeof record.timeStamp === 'string') {\n // It's already a string, but make sure it's a valid date\n const date = new Date(record.timeStamp);\n if (isNaN(date.getTime())) {\n return; // Invalid date string\n }\n timeStamp = record.timeStamp;\n } else if (typeof record.timeStamp === 'number') {\n // Assume it's a Unix timestamp (milliseconds since epoch)\n timeStamp = new Date(record.timeStamp).toISOString();\n } else {\n // Unknown type, skip\n return;\n }\n\n allRecords.push({\n timeStamp,\n courseID: record.courseID || 'unknown',\n cardID: record.cardID || 'unknown',\n timeSpent: record.timeSpent || 0,\n type: 'card_view',\n });\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (err) {\n // Silently skip problematic records to avoid flooding logs\n }\n });\n }\n } catch (err) {\n logger.error('Error processing history item:', err);\n }\n }\n\n logger.debug(`Found ${allRecords.length} activity records`);\n return allRecords;\n } catch (err) {\n logger.error('Error in getActivityRecords:', err);\n return [];\n }\n }\n\n private async getReviewstoDate(targetDate: Moment, course_id?: string) {\n const keys = getStartAndEndKeys(DocTypePrefixes[DocType.SCHEDULED_CARD]);\n\n const reviews = await this.remoteDB.allDocs<ScheduledCard>({\n startkey: keys.startkey,\n endkey: keys.endkey,\n include_docs: true,\n });\n\n log(\n `Fetching ${this._username}'s scheduled reviews${\n course_id ? ` for course ${course_id}` : ''\n }.`\n );\n return reviews.rows\n .filter((r) => {\n if (r.id.startsWith(DocTypePrefixes[DocType.SCHEDULED_CARD])) {\n const date = moment.utc(\n r.id.substr(DocTypePrefixes[DocType.SCHEDULED_CARD].length),\n REVIEW_TIME_FORMAT\n );\n if (targetDate.isAfter(date)) {\n if (course_id === undefined || r.doc!.courseId === course_id) {\n return true;\n }\n }\n }\n })\n .map((r) => r.doc!);\n }\n\n public async getReviewsForcast(daysCount: number, course_id?: string) {\n const time = moment.utc().add(daysCount, 'days');\n return this.getReviewstoDate(time, course_id);\n }\n\n public async getPendingReviews(course_id?: string) {\n const now = moment.utc();\n return this.getReviewstoDate(now, course_id);\n }\n\n public async getScheduledReviewCount(course_id: string): Promise<number> {\n return (await this.getPendingReviews(course_id)).length;\n }\n\n public async getRegisteredCourses() {\n const regDoc = await this.getCourseRegistrationsDoc();\n return regDoc.courses.filter((c) => {\n return !c.status || c.status === 'active' || c.status === 'maintenance-mode';\n });\n }\n\n public async getCourseRegDoc(courseID: string) {\n const regDocs = await this.getCourseRegistrationsDoc();\n const ret = regDocs.courses.find((c) => c.courseID === courseID);\n if (ret) {\n return ret;\n } else {\n throw new Error(`Course registration not found for course ID: ${courseID}`);\n }\n }\n\n public async registerForCourse(course_id: string, previewMode: boolean = false) {\n return this.getCourseRegistrationsDoc()\n .then((doc: CourseRegistrationDoc) => {\n const status = previewMode ? 'preview' : 'active';\n logger.debug(`Registering for ${course_id} with status: ${status}`);\n\n const regItem: CourseRegistration = {\n status: status,\n courseID: course_id,\n user: true,\n admin: false,\n moderator: false,\n elo: {\n global: {\n score: 1000,\n count: 0,\n },\n tags: {},\n misc: {},\n },\n };\n\n if (\n doc.courses.filter((course) => {\n return course.courseID === regItem.courseID;\n }).length === 0\n ) {\n log(`It's a new course registration!`);\n doc.courses.push(regItem);\n doc.studyWeight[course_id] = 1;\n } else {\n doc.courses.forEach((c) => {\n log(`Found the previously registered course!`);\n if (c.courseID === course_id) {\n c.status = status;\n }\n });\n }\n\n return this.localDB.put<CourseRegistrationDoc>(doc);\n })\n .catch((e) => {\n log(`Registration failed because of: ${JSON.stringify(e)}`);\n throw e;\n });\n }\n public async dropCourse(course_id: string, dropStatus: CourseRegistration['status'] = 'dropped') {\n return this.getCourseRegistrationsDoc().then((doc) => {\n let index: number = -1;\n for (let i = 0; i < doc.courses.length; i++) {\n if (doc.courses[i].courseID === course_id) {\n index = i;\n }\n }\n\n if (index !== -1) {\n // remove from the relative-weighting of course study\n delete doc.studyWeight[course_id];\n // set drop status\n doc.courses[index].status = dropStatus;\n } else {\n throw new Error(\n `User ${this.getUsername()} is not currently registered for course ${course_id}`\n );\n }\n\n return this.localDB.put<CourseRegistrationDoc>(doc);\n });\n }\n\n public async getCourseInterface(courseId: string): Promise<UsrCrsDataInterface> {\n return new UsrCrsData(this, courseId);\n }\n\n public async getUserEditableCourses() {\n let courseIDs: string[] = [];\n\n const registeredCourses = await this.getCourseRegistrationsDoc();\n\n courseIDs = courseIDs.concat(\n registeredCourses.courses.map((course) => {\n return course.courseID;\n })\n );\n\n const cfgs = await Promise.all(\n courseIDs.map(async (id) => {\n return await getCredentialledCourseConfig(id);\n })\n );\n return cfgs;\n }\n\n public async getConfig(): Promise<UserConfig & PouchDB.Core.IdMeta & PouchDB.Core.GetMeta> {\n const defaultConfig: PouchDB.Core.Document<UserConfig> = {\n _id: BaseUser.DOC_IDS.CONFIG,\n darkMode: false,\n likesConfetti: false,\n sessionTimeLimit: 5,\n };\n\n try {\n const cfg = await this.localDB.get<UserConfig>(BaseUser.DOC_IDS.CONFIG);\n logger.debug('Raw config from DB:', cfg);\n\n return cfg;\n } catch (e) {\n const err = e as PouchError;\n if (err.name && err.name === 'not_found') {\n if (!this.canMaterializeDefaults()) {\n throw new Error(\n `Cannot read config for ${this._username}: the local mirror is unavailable ` +\n `(hydration state '${this._hydration.state}'). Refusing to write a default config ` +\n `over what may be an existing one.`\n );\n }\n await this.putDefaultUnlessCreated<UserConfig>(defaultConfig);\n return this.getConfig();\n } else {\n logger.error(`Error setting user default config:`, e);\n throw new Error(`Error returning the user's configuration: ${JSON.stringify(e)}`);\n }\n }\n }\n\n public async setConfig(items: Partial<UserConfig>) {\n logger.debug(`Setting Config items ${JSON.stringify(items)}`);\n\n const c = await this.getConfig();\n const put = await this.localDB.put<UserConfig>({\n ...c,\n ...items,\n });\n\n if (put.ok) {\n logger.debug(`Config items set: ${JSON.stringify(items)}`);\n } else {\n logger.error(`Error setting config items: ${JSON.stringify(put)}`);\n }\n }\n\n /**\n *\n * This function should be called *only* by the pouchdb datalayer provider\n * auth store.\n *\n *\n * Anyone else seeking the current user should use the auth store's\n * exported `getCurrentUser` method.\n *\n */\n public static async instance(syncStrategy: SyncStrategy, username?: string): Promise<BaseUser> {\n if (username) {\n BaseUser._instance = new BaseUser(username, syncStrategy);\n await BaseUser._instance.init();\n return BaseUser._instance;\n } else if (BaseUser._instance && BaseUser._initialized) {\n // log(`USER.instance() returning user ${BaseUser._instance._username}`);\n return BaseUser._instance;\n } else if (BaseUser._instance) {\n return new Promise((resolve) => {\n (function waitForUser() {\n if (BaseUser._initialized) {\n return resolve(BaseUser._instance);\n } else {\n setTimeout(waitForUser, 50);\n }\n })();\n });\n } else {\n const guestUsername = await syncStrategy.getCurrentUsername();\n BaseUser._instance = new BaseUser(guestUsername, syncStrategy);\n await BaseUser._instance.init();\n return BaseUser._instance;\n }\n }\n\n private constructor(username: string, syncStrategy: SyncStrategy) {\n BaseUser._initialized = false;\n this._username = username;\n this.syncStrategy = syncStrategy;\n this.setDBandQ();\n }\n\n private setDBandQ() {\n this.localDB = getLocalUserDB(this._username);\n this.remoteDB = this.syncStrategy.setupRemoteDB(this._username);\n // writeDB follows local-first pattern: static mode writes to local, CouchDB writes to remote/local as appropriate\n this.writeDB = this.syncStrategy.getWriteDB\n ? this.syncStrategy.getWriteDB(this._username)\n : this.localDB;\n this.updateQueue = new UpdateQueue(this.localDB, this.writeDB);\n }\n\n private async init() {\n BaseUser._initialized = false;\n\n // Skip admin user\n if (this._username === 'admin') {\n BaseUser._initialized = true;\n return;\n }\n\n // Cancel replication left over from the previous identity BEFORE rebinding\n // the DB handles below. init() runs on every identity change (login,\n // logout, account creation, data reset), and each one points localDB /\n // remoteDB somewhere new — so without this, the prior sync keeps running\n // against handles nobody holds a reference to anymore.\n //\n // Logout is the case that bites: the guest branch of startSync() never\n // replaces the handle (it only ever assigns when a sync is actually\n // started), so the departing user's live sync survived indefinitely. Its\n // session cookie is gone by then, leaving it to 401-and-retry forever.\n this.syncStrategy.stopSync?.();\n\n this.setDBandQ();\n\n // Populate the local mirror BEFORE anything can read it, and before live\n // sync can push local state upward. See hydrateLocalMirror().\n //\n // Retained (not just awaited) so awaitHydration() can hand the same\n // promise to anything that asks mid-flight. Assigned synchronously with\n // respect to init()'s entry, so no caller can observe a previous\n // identity's promise here.\n this._hydrationPromise = this.hydrateLocalMirror();\n await this._hydrationPromise;\n\n // _hydratedSeq is set only by a hydration that just succeeded above, for\n // this identity — see hydrateLocalMirror(). Anything else leaves it\n // undefined and the live sync resumes from its own checkpoint.\n this.syncStrategy.startSync(this.localDB, this.remoteDB, this._hydratedSeq);\n this.applyDesignDocs().catch((error) => {\n log(`Error in applyDesignDocs background task: ${error}`);\n if (error && typeof error === 'object') {\n log(`Full error details in applyDesignDocs: ${JSON.stringify(error)}`);\n }\n });\n this.deduplicateReviews().catch((error) => {\n log(`Error in deduplicateReviews background task: ${error}`);\n if (error && typeof error === 'object') {\n log(`Full error details in background task: ${JSON.stringify(error)}`);\n }\n });\n BaseUser._initialized = true;\n }\n\n /**\n * Pull this account's documents into the local mirror, if that hasn't\n * happened on this device before.\n *\n * Runs between setDBandQ() and startSync() — after the handles exist, before\n * anything can observe an empty local DB or replicate one upward.\n *\n * Never throws: a failure is recorded as `failed` state and reported through\n * hydrationStatus(), because throwing here would abort init() and leave\n * BaseUser._initialized false forever (BaseUser.instance() polls it with no\n * ceiling). Callers decide what a failure means for them.\n */\n private async hydrateLocalMirror(): Promise<void> {\n // Clear first: init() reruns on every identity change, and a sequence from\n // the departing account would be meaningless against the incoming one's\n // database. Every path below either sets it or leaves it unset.\n this._hydratedSeq = undefined;\n\n // Guests and static-mode users have no remote — setupRemoteDB() hands back\n // the local database itself, so there is nothing to pull from.\n if (this.localDB.name === this.remoteDB.name || !this.syncStrategy.hydrate) {\n this._hydration = { state: 'not-required' };\n return;\n }\n\n if (await this.hasHydrationMarker()) {\n // A full pull already completed on this device, so local reads return\n // real data and live sync will close any gap. Blocking here would break\n // offline startup to re-fetch what we already have.\n this._hydration = { state: 'stale' };\n return;\n }\n\n this._hydration = { state: 'hydrating' };\n const start = Date.now();\n\n try {\n const { docsWritten, lastSeq } = await withTimeout(\n this.syncStrategy.hydrate(this.localDB, this.remoteDB),\n HYDRATION_TIMEOUT_MS,\n `Hydration of local mirror for ${this._username}`\n );\n this._hydratedSeq = lastSeq;\n await this.writeHydrationMarker();\n this._hydration = {\n state: 'hydrated',\n docsWritten,\n durationMs: Date.now() - start,\n };\n log(\n `Hydrated local mirror for ${this._username}: ` +\n `${docsWritten} docs in ${this._hydration.durationMs}ms`\n );\n } catch (e) {\n // Cancel the pull if it is merely slow rather than dead — otherwise it\n // races the live sync we are about to start over the same documents.\n this.syncStrategy.stopSync?.();\n this._hydration = {\n state: 'failed',\n durationMs: Date.now() - start,\n error: e instanceof Error ? e.message : String(e),\n };\n logger.error(`Failed to hydrate local mirror for ${this._username}:`, e);\n }\n }\n\n /**\n * Has a full pull completed on this device for the CURRENT account?\n *\n * The marker is a `_local/` document, which never replicates — so its\n * presence describes this device's mirror and cannot arrive from elsewhere.\n */\n private async hasHydrationMarker(): Promise<boolean> {\n try {\n const marker = await this.localDB.get<HydrationMarker>(HYDRATION_MARKER_ID);\n return marker.username === this._username;\n } catch {\n // Absent, or unreadable — either way, treat as never hydrated. The cost\n // of a false negative is one redundant pull.\n return false;\n }\n }\n\n private async writeHydrationMarker(): Promise<void> {\n try {\n let existingRev: string | undefined;\n try {\n existingRev = (await this.localDB.get<HydrationMarker>(HYDRATION_MARKER_ID))._rev;\n } catch {\n // First hydration on this device.\n }\n\n await this.localDB.put<HydrationMarker>({\n _id: HYDRATION_MARKER_ID,\n _rev: existingRev,\n username: this._username,\n hydratedAt: new Date().toISOString(),\n });\n } catch (e) {\n // Costs a redundant pull on next startup, not correctness.\n logger.warn(`Could not write hydration marker for ${this._username}: ${e}`);\n }\n }\n\n private static designDocs: DesignDoc[] = [\n {\n _id: '_design/reviewCards',\n views: {\n reviewCards: {\n map: `function (doc) {\n if (doc._id && doc._id.indexOf('card_review') === 0 && doc.courseId && doc.cardId) {\n emit(doc._id, doc.courseId + '-' + doc.cardId);\n }\n }`,\n },\n },\n },\n ];\n\n private async applyDesignDocs() {\n log(`Starting applyDesignDocs for user: ${this._username}`);\n log(`Remote DB name: ${this.remoteDB.name || 'unknown'}`);\n\n if (this._username === 'admin') {\n // Skip admin user\n log('Skipping design docs for admin user');\n return;\n }\n\n log(`Applying ${BaseUser.designDocs.length} design docs`);\n for (const doc of BaseUser.designDocs) {\n log(`Applying design doc: ${doc._id}`);\n try {\n // Try to get existing doc\n try {\n const existingDoc = await this.remoteDB.get(doc._id);\n // Update existing doc\n await this.remoteDB.put({\n ...doc,\n _rev: existingDoc._rev,\n });\n } catch (e: unknown) {\n // NB: PouchDB errors are plain objects ({error, reason, status, name,\n // message, ...}), not Error instances — `e instanceof Error` is false\n // for them. Check `.name` directly. The outer catch at line ~697\n // already does this correctly; mirror that style here so the\n // not_found → \"create new doc\" path actually fires for fresh user DBs.\n if ((e as { name?: string })?.name === 'not_found') {\n // Create new doc\n await this.remoteDB.put(doc);\n } else {\n throw e; // Re-throw unexpected errors\n }\n }\n } catch (error: unknown) {\n if ((error as any).name && (error as any).name === 'conflict') {\n logger.warn(`Design doc ${doc._id} update conflict - will retry`);\n // Wait a bit and try again\n await new Promise((resolve) => setTimeout(resolve, 1000));\n await this.applyDesignDoc(doc); // Recursive retry\n } else {\n logger.error(`Failed to apply design doc ${doc._id}:`, error);\n throw error;\n }\n }\n }\n }\n\n // Helper method for single doc update with retry\n private async applyDesignDoc(doc: DesignDoc, retries = 3): Promise<void> {\n try {\n const existingDoc = await this.remoteDB.get(doc._id);\n await this.remoteDB.put({\n ...doc,\n _rev: existingDoc._rev,\n });\n } catch (e: unknown) {\n // NB: PouchDB errors are plain objects, not Error instances — see\n // applyDesignDocs() above. Check `.name` directly so the conflict-retry\n // path actually fires.\n if ((e as { name?: string })?.name === 'conflict' && retries > 0) {\n await new Promise((resolve) => setTimeout(resolve, 1000));\n return this.applyDesignDoc(doc, retries - 1);\n }\n throw e;\n }\n }\n\n /**\n * Logs a record of the user's interaction with the card and returns the card's\n * up-to-date history.\n *\n * **Automatic Initialization:**\n * If this is the user's first interaction with the card (CardHistory doesn't exist),\n * this method automatically creates the CardHistory document with initial values\n * (lapses: 0, streak: 0, bestInterval: 0).\n *\n * **Error Handling:**\n * - Handles 404 errors by creating initial CardHistory document\n * - Re-throws all other errors from UpdateQueue\n *\n * // [ ] #db-refactor extract to a smaller scope - eg, UserStudySession\n *\n * @param record - The recent recorded interaction between user and card\n * @returns The updated state of the card's CardHistory data\n * @throws Error if document creation fails or non-404 database error occurs\n */\n\n public async putCardRecord<T extends CardRecord>(\n record: T\n ): Promise<CardHistory<CardRecord> & PouchDB.Core.RevisionIdMeta> {\n const cardHistoryID = getCardHistoryID(record.courseID, record.cardID);\n // stringify the current record to make it writable to couchdb\n record.timeStamp = moment.utc(record.timeStamp).toString() as unknown as Moment;\n\n const append = (h: CardHistory<T>): CardHistory<T> => {\n h.records.push(record);\n h.bestInterval = h.bestInterval || 0;\n // Scheduling (SpacedRepetition.newQuestionInterval) re-derives\n // lapses/streak from `records` on every call, so these persisted\n // fields are informational — kept current so the stored doc reads\n // truthfully when inspected outside a session.\n if (areQuestionRecords(h)) {\n h.lapses = getLapses(h.records);\n h.streak = getStreak(h.records);\n } else {\n h.lapses = h.lapses || 0;\n h.streak = h.streak || 0;\n }\n return h;\n };\n const appendToExisting = async () => {\n const cardHistory = await this.update<CardHistory<T>>(cardHistoryID, append);\n // Convert timestamps to moment objects\n cardHistory.records = cardHistory.records.map<T>((record) => {\n const ret: T = {\n ...(record as object),\n } as T;\n ret.timeStamp = moment.utc(record.timeStamp);\n return ret;\n });\n return cardHistory;\n };\n\n try {\n return await appendToExisting();\n } catch (e) {\n const reason = e as PouchError;\n if (reason.status === 404) {\n try {\n const initCardHistory: CardHistory<T> = {\n _id: cardHistoryID,\n cardID: record.cardID,\n courseID: record.courseID,\n records: [record],\n lapses: 0,\n streak: 0,\n bestInterval: 0,\n };\n const putResult = await this.writeDB.put<CardHistory<T>>(initCardHistory);\n return { ...initCardHistory, _rev: putResult.rev };\n } catch (creationError) {\n // Another record for this card created the doc first (two first\n // records in flight at once): it exists now, so append to it.\n if ((creationError as PouchError).name === 'conflict') {\n return appendToExisting();\n }\n throw new Error(\n `Failed to create CardHistory for ${cardHistoryID}. Reason: ${creationError}`\n );\n }\n } else {\n throw new Error(`putCardRecord failed because of:\n name:${reason.name}\n error: ${reason.error}\n message: ${reason.message}`);\n }\n }\n }\n\n private async deduplicateReviews() {\n try {\n log('Starting deduplication of scheduled reviews...');\n log(`Remote DB name: ${this.remoteDB.name || 'unknown'}`);\n log(`Write DB name: ${this.writeDB.name || 'unknown'}`);\n /**\n * Maps the qualified-id of a scheduled review card to\n * the docId of the same scheduled review.\n *\n * EG: {\n * courseId-cardId: 'card_review_2021-06--17:12:165'\n * }\n */\n const reviewsMap: { [index: string]: string } = {};\n const duplicateDocIds: string[] = [];\n\n log(\n `Attempting to query remoteDB for reviewCards/reviewCards. Database: ${this.remoteDB.name || 'unknown'}`\n );\n const scheduledReviews = await this.remoteDB.query<{\n id: string;\n value: string;\n }>('reviewCards/reviewCards');\n\n log(`Found ${scheduledReviews.rows.length} scheduled reviews to process`);\n\n // First pass: identify duplicates\n scheduledReviews.rows.forEach((r) => {\n const qualifiedCardId = r.value; // courseId-cardId\n const docId = r.key; // card_review_2021-06--17:12:165\n\n if (reviewsMap[qualifiedCardId]) {\n // this card is scheduled more than once! mark the earlier one for deletion\n log(`Found duplicate scheduled review for card: ${qualifiedCardId}`);\n log(\n `Marking earlier review ${reviewsMap[qualifiedCardId]} for deletion, keeping ${docId}`\n );\n duplicateDocIds.push(reviewsMap[qualifiedCardId]);\n // replace with the later-dated scheduled review\n reviewsMap[qualifiedCardId] = docId;\n } else {\n // note that this card is scheduled for review\n reviewsMap[qualifiedCardId] = docId;\n }\n });\n\n // Second pass: remove duplicates\n if (duplicateDocIds.length > 0) {\n log(`Removing ${duplicateDocIds.length} duplicate reviews...`);\n const deletePromises = duplicateDocIds.map(async (docId) => {\n try {\n const doc = await this.remoteDB.get(docId);\n await this.writeDB.remove(doc);\n log(`Successfully removed duplicate review: ${docId}`);\n } catch (error) {\n log(`Failed to remove duplicate review ${docId}: ${error}`);\n }\n });\n\n await Promise.all(deletePromises);\n log(`Deduplication complete. Processed ${duplicateDocIds.length} duplicates`);\n } else {\n log('No duplicate reviews found');\n }\n } catch (error) {\n log(`Error during review deduplication: ${error}`);\n if (error && typeof error === 'object' && 'status' in error && error.status === 404) {\n log(\n `Database not found (404) during review deduplication. Database: ${this.remoteDB.name || 'unknown'}`\n );\n log(\n `This might indicate the user database doesn't exist or the reviewCards view isn't available`\n );\n }\n // Log full error details for debugging\n if (error && typeof error === 'object') {\n log(`Full error details: ${JSON.stringify(error)}`);\n }\n }\n }\n\n /**\n * Returns a promise of the card IDs that the user has\n * encountered in the past.\n *\n * @param course_id optional specification of individual course\n */\n async getSeenCards(course_id?: string) {\n // Doc IDs follow the pattern: cardH-{courseId}-{cardId}\n // (see getCardHistoryID in core/util)\n const basePrefix = DocTypePrefixes[DocType.CARDRECORD];\n let filterPrefix = basePrefix;\n if (course_id) {\n filterPrefix += `-${course_id}-`;\n }\n const docs = await filterAllDocsByPrefix(this.localDB, filterPrefix, {\n include_docs: false,\n });\n const ret: PouchDB.Core.DocumentId[] = [];\n docs.rows.forEach((row) => {\n if (row.id.startsWith(filterPrefix)) {\n // Strip the full prefix to return bare cardId\n ret.push(row.id.substr(filterPrefix.length));\n }\n });\n return ret;\n }\n\n /**\n *\n * @returns A promise of the cards that the user has seen in the past.\n */\n async getHistory() {\n const cards = await filterAllDocsByPrefix<CardHistory<CardRecord>>(\n this.remoteDB,\n DocTypePrefixes[DocType.CARDRECORD],\n {\n include_docs: true,\n attachments: false,\n }\n );\n return cards.rows.map((r) => r.doc);\n }\n\n async updateCourseSettings(course_id: string, settings: UserCourseSetting[]) {\n void this.getCourseRegistrationsDoc().then((doc) => {\n const crs = doc.courses.find((c) => c.courseID === course_id);\n if (crs) {\n if (crs.settings === null || crs.settings === undefined) {\n crs.settings = {};\n }\n settings.forEach((setting) => {\n crs!.settings![setting.key] = setting.value;\n });\n }\n\n return this.localDB.put(doc);\n });\n }\n async getCourseSettings(course_id: string) {\n const regDoc = await this.getCourseRegistrationsDoc();\n const crsDoc = regDoc.courses.find((c) => c.courseID === course_id);\n\n if (crsDoc) {\n return crsDoc.settings;\n } else {\n throw new Error(`getCourseSettings Failed:\n User is not registered for course ${course_id}`);\n }\n }\n\n private async getOrCreateClassroomRegistrationsDoc(): Promise<\n ClassroomRegistrationDoc & PouchDB.Core.IdMeta & PouchDB.Core.GetMeta\n > {\n let ret;\n\n try {\n ret = await this.remoteDB.get<ClassroomRegistrationDoc>(\n BaseUser.DOC_IDS.CLASSROOM_REGISTRATIONS\n );\n } catch (e) {\n const err = e as PouchError;\n\n if (err.status === 404) {\n // doc does not exist. Create it and then run this fcn again.\n await this.writeDB.put<ClassroomRegistrationDoc>({\n _id: BaseUser.DOC_IDS.CLASSROOM_REGISTRATIONS,\n registrations: [],\n });\n ret = await this.getOrCreateClassroomRegistrationsDoc();\n } else {\n // Properly serialize error information\n const errorDetails = {\n name: err.name,\n status: err.status,\n message: err.message,\n reason: err.reason,\n error: err.error,\n };\n\n logger.error(\n 'Database error in getOrCreateClassroomRegistrationsDoc (private method):',\n errorDetails\n );\n\n throw new Error(\n `Database error accessing classroom registrations: ${err.message || err.name || 'Unknown error'} (status: ${err.status})`\n );\n }\n }\n\n logger.debug(`Returning classroom registrations doc: ${JSON.stringify(ret)}`);\n return ret;\n }\n\n /**\n * Retrieves the list of active classroom IDs where the user is registered as a student.\n *\n * @returns Promise<string[]> - Array of classroom IDs, or empty array if classroom\n * registration document is unavailable due to database errors\n *\n * @description This method gracefully handles database connectivity issues by returning\n * an empty array when the classroom registrations document cannot be accessed.\n * This ensures that users can still access other application features even\n * when classroom functionality is temporarily unavailable.\n */\n public async getActiveClasses(): Promise<string[]> {\n try {\n return (await this.getOrCreateClassroomRegistrationsDoc()).registrations\n .filter((c) => c.registeredAs === 'student')\n .map((c) => c.classID);\n } catch (error) {\n logger.warn(\n 'Failed to load classroom registrations, continuing without classroom data:',\n error\n );\n // Return empty array so user can still access other features\n return [];\n }\n }\n\n public async scheduleCardReview(review: {\n user: string;\n course_id: string;\n card_id: PouchDB.Core.DocumentId;\n time: Moment;\n scheduledFor: ScheduledCard['scheduledFor'];\n schedulingAgentId: ScheduledCard['schedulingAgentId'];\n }) {\n return scheduleCardReviewLocal(this.writeDB, review);\n }\n public async removeScheduledCardReview(reviewId: string): Promise<void> {\n return removeScheduledCardReviewLocal(this.writeDB, reviewId);\n }\n\n public async registerForClassroom(\n _classId: string,\n _registerAs: 'student' | 'teacher' | 'aide' | 'admin'\n ): Promise<PouchDB.Core.Response> {\n return registerUserForClassroom(this._username, _classId, _registerAs);\n }\n\n public async dropFromClassroom(classId: string): Promise<PouchDB.Core.Response> {\n return dropUserFromClassroom(this._username, classId);\n }\n public async getUserClassrooms(): Promise<ClassroomRegistrationDoc> {\n return getUserClassrooms(this._username);\n }\n\n public async updateUserElo(courseId: string, elo: CourseElo): Promise<PouchDB.Core.Response> {\n return updateUserElo(this._username, courseId, elo);\n }\n\n public async getStrategyState<T>(courseId: string, strategyKey: string): Promise<T | null> {\n const docId = buildStrategyStateId(courseId, strategyKey);\n try {\n const doc = await this.localDB.get<StrategyStateDoc<T>>(docId);\n return doc.data;\n } catch (e) {\n const err = e as PouchError;\n if (err.status === 404) {\n // `null` here means \"this user has no such state\" — a first-run signal\n // consumers act on. When the mirror is untrusted we cannot honestly say\n // that, so fail instead of reporting an established user as new.\n if (!this.canMaterializeDefaults()) {\n throw new Error(\n `Cannot read strategy state '${strategyKey}' for ${this._username}: the local mirror ` +\n `is unavailable (hydration state '${this._hydration.state}').`\n );\n }\n return null;\n }\n throw e;\n }\n }\n\n public async putStrategyState<T>(courseId: string, strategyKey: string, data: T): Promise<void> {\n const docId = buildStrategyStateId(courseId, strategyKey);\n let existingRev: string | undefined;\n\n try {\n const existing = await this.localDB.get<StrategyStateDoc<T>>(docId);\n existingRev = existing._rev;\n } catch (e) {\n const err = e as PouchError;\n if (err.status !== 404) {\n throw e;\n }\n }\n\n const doc: StrategyStateDoc<T> = {\n _id: docId,\n _rev: existingRev,\n docType: DocType.STRATEGY_STATE,\n courseId,\n strategyKey,\n data,\n updatedAt: new Date().toISOString(),\n };\n\n await this.localDB.put(doc);\n }\n\n /**\n * Open and close write the same `_id`, so the 409 path is the expected\n * route for the second write, not an error case.\n */\n public async putStudySession(doc: StudySessionDoc): Promise<void> {\n try {\n await this.localDB.put(doc);\n } catch (err: any) {\n if (err.status === 409) {\n const existing = await this.localDB.get(doc._id);\n await this.localDB.put({ ...doc, _rev: existing._rev });\n } else {\n throw err;\n }\n }\n }\n\n public async getStudySessions(courseId?: string): Promise<StudySessionDoc[]> {\n const prefix = courseId\n ? `${DocTypePrefixes[DocType.STUDY_SESSION]}::${courseId}::`\n : `${DocTypePrefixes[DocType.STUDY_SESSION]}::`;\n const keys = getStartAndEndKeys(prefix);\n\n const res = await this.localDB.allDocs<StudySessionDoc>({\n startkey: keys.startkey,\n endkey: keys.endkey,\n include_docs: true,\n });\n\n return res.rows\n .map((r) => r.doc)\n .filter((d): d is StudySessionDoc & PouchDB.Core.RevisionIdMeta => !!d)\n .sort((a, b) => b.startTime.localeCompare(a.startTime));\n }\n\n public async putUserOutcome(record: UserOutcomeRecord): Promise<void> {\n try {\n await this.localDB.put(record);\n } catch (err: any) {\n if (err.status === 409) {\n // Overwrite if exists\n const existing = await this.localDB.get(record._id);\n (record as any)._rev = existing._rev;\n await this.localDB.put(record);\n } else {\n throw err;\n }\n }\n }\n\n public async deleteStrategyState(courseId: string, strategyKey: string): Promise<void> {\n const docId = buildStrategyStateId(courseId, strategyKey);\n try {\n const doc = await this.localDB.get(docId);\n await this.localDB.remove(doc);\n } catch (e) {\n const err = e as PouchError;\n if (err.status === 404) {\n return;\n }\n throw e;\n }\n }\n}\n\nexport function accomodateGuest(): {\n username: string;\n firstVisit: boolean;\n} {\n logger.log('[funnel] accomodateGuest() called');\n\n // Check if localStorage is available (browser environment)\n if (typeof localStorage === 'undefined') {\n logger.log(\n '[funnel] localStorage not available (Node.js environment), returning default guest'\n );\n return {\n username: GuestUsername + 'nodejs-test',\n firstVisit: true,\n };\n }\n\n const dbUUID = 'sk-guest-uuid';\n let firstVisit: boolean;\n\n const existingUUID = localStorage.getItem(dbUUID);\n logger.log('[funnel] Checking localStorage for key:', dbUUID);\n logger.log('[funnel] Existing UUID value:', existingUUID);\n logger.log('[funnel] existingUUID !== null:', existingUUID !== null);\n\n if (existingUUID !== null) {\n firstVisit = false;\n logger.log(`[funnel] Returning guest ${existingUUID} \"logging in\".`);\n } else {\n firstVisit = true;\n logger.log('[funnel] No existing UUID, generating new one...');\n const uuid = generateUUID();\n logger.log('[funnel] Generated UUID:', uuid);\n logger.log('[funnel] UUID length:', uuid.length);\n\n try {\n localStorage.setItem(dbUUID, uuid);\n logger.log('[funnel] Successfully stored UUID in localStorage');\n const verification = localStorage.getItem(dbUUID);\n logger.log('[funnel] Verification read from localStorage:', verification);\n } catch (e) {\n logger.error('[funnel] ERROR storing UUID:', e);\n }\n\n logger.log(`[funnel] Accommodating a new guest with account: ${uuid}`);\n }\n\n const finalUUID = localStorage.getItem(dbUUID);\n const finalUsername = GuestUsername + finalUUID;\n logger.log('[funnel] Final UUID from localStorage:', finalUUID);\n logger.log('[funnel] GuestUsername constant:', GuestUsername);\n logger.log('[funnel] Final username to return:', finalUsername);\n\n return {\n username: finalUsername,\n firstVisit: firstVisit,\n };\n\n // Use cryptographically secure UUID generation\n function generateUUID() {\n logger.log('[funnel] Inside generateUUID()');\n\n // Use crypto.randomUUID() if available (Node 14.17+ / modern browsers)\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n const uuid = crypto.randomUUID();\n logger.log('[funnel] Generated UUID using crypto.randomUUID():', uuid);\n return uuid;\n }\n\n // Fallback for older environments: use crypto.getRandomValues()\n if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n\n // Set version (4) and variant bits according to RFC 4122\n bytes[6] = (bytes[6] & 0x0f) | 0x40; // Version 4\n bytes[8] = (bytes[8] & 0x3f) | 0x80; // Variant 10\n\n const uuid = [\n Array.from(bytes.slice(0, 4))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join(''),\n Array.from(bytes.slice(4, 6))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join(''),\n Array.from(bytes.slice(6, 8))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join(''),\n Array.from(bytes.slice(8, 10))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join(''),\n Array.from(bytes.slice(10, 16))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join(''),\n ].join('-');\n\n logger.log('[funnel] Generated UUID using crypto.getRandomValues():', uuid);\n return uuid;\n }\n\n // Last resort fallback (should never happen in modern environments)\n logger.warn('[funnel] crypto API not available, using timestamp-based UUID (NOT SECURE)');\n let d = new Date().getTime();\n if (typeof performance !== 'undefined' && typeof performance.now === 'function') {\n d += performance.now();\n }\n const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (d + Math.random() * 16) % 16 | 0;\n d = Math.floor(d / 16);\n return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);\n });\n logger.log('[funnel] Generated UUID (fallback):', uuid);\n return uuid;\n }\n}\n\nconst userCoursesDoc = 'CourseRegistrations';\nconst userClassroomsDoc = 'ClassroomRegistrations';\n\nasync function getOrCreateClassroomRegistrationsDoc(\n user: string\n): Promise<ClassroomRegistrationDoc & PouchDB.Core.IdMeta & PouchDB.Core.GetMeta> {\n let ret;\n\n try {\n ret = await getLocalUserDB(user).get<ClassroomRegistrationDoc>(userClassroomsDoc);\n } catch (e) {\n const err = e as PouchError;\n\n if (err.status === 404) {\n // doc does not exist. Create it and then run this fcn again.\n await getLocalUserDB(user).put<ClassroomRegistrationDoc>({\n _id: userClassroomsDoc,\n registrations: [],\n });\n ret = await getOrCreateClassroomRegistrationsDoc(user);\n } else {\n // Properly serialize error information\n const errorDetails = {\n name: err.name,\n status: err.status,\n message: err.message,\n reason: err.reason,\n error: err.error,\n };\n\n logger.error(\n 'Database error in getOrCreateClassroomRegistrationsDoc (standalone function):',\n errorDetails\n );\n\n throw new Error(\n `Database error accessing classroom registrations: ${err.message || err.name || 'Unknown error'} (status: ${err.status})`\n );\n }\n }\n\n return ret;\n}\n\nasync function getOrCreateCourseRegistrationsDoc(\n user: string\n): Promise<CourseRegistrationDoc & PouchDB.Core.IdMeta & PouchDB.Core.GetMeta> {\n let ret;\n\n try {\n ret = await getLocalUserDB(user).get<CourseRegistrationDoc>(userCoursesDoc);\n } catch (e) {\n const err = e as PouchError;\n if (err.status === 404) {\n // doc does not exist. Create it and then run this fcn again.\n await getLocalUserDB(user).put<CourseRegistrationDoc>({\n _id: userCoursesDoc,\n courses: [],\n studyWeight: {},\n });\n ret = await getOrCreateCourseRegistrationsDoc(user);\n } else {\n throw new Error(\n `Unexpected error ${JSON.stringify(e)} in getOrCreateCourseRegistrationDoc...`\n );\n }\n }\n\n return ret;\n}\n\nexport async function updateUserElo(user: string, course_id: string, elo: CourseElo) {\n const regDoc = await getOrCreateCourseRegistrationsDoc(user);\n const course = regDoc.courses.find((c) => c.courseID === course_id)!;\n course.elo = elo;\n return getLocalUserDB(user).put(regDoc);\n}\n\nexport async function registerUserForClassroom(\n user: string,\n classID: string,\n registerAs: 'student' | 'teacher' | 'aide' | 'admin'\n) {\n log(`Registering user: ${user} in course: ${classID}`);\n return getOrCreateClassroomRegistrationsDoc(user).then((doc) => {\n const regItem = {\n classID: classID,\n registeredAs: registerAs,\n };\n\n if (\n doc.registrations.filter((reg) => {\n return reg.classID === regItem.classID && reg.registeredAs === regItem.registeredAs;\n }).length === 0\n ) {\n doc.registrations.push(regItem);\n } else {\n log(`User ${user} is already registered for class ${classID}`);\n }\n\n return getLocalUserDB(user).put(doc);\n });\n}\n\nexport async function dropUserFromClassroom(user: string, classID: string) {\n return getOrCreateClassroomRegistrationsDoc(user).then((doc) => {\n let index: number = -1;\n\n for (let i = 0; i < doc.registrations.length; i++) {\n if (doc.registrations[i].classID === classID) {\n index = i;\n }\n }\n\n if (index !== -1) {\n doc.registrations.splice(index, 1);\n }\n return getLocalUserDB(user).put(doc);\n });\n}\n\nexport async function getUserClassrooms(user: string) {\n return getOrCreateClassroomRegistrationsDoc(user);\n}\n"],"mappings":";;;;;;;;;;;;;;;AA6CA,MAAM,OAAO,MAAW;AACtB,QAAO,KAAK,EAAE;;;;;;;;AAoBhB,MAAM,uBAAuB;;;;;;;AAQ7B,SAAS,YAAe,GAAe,IAAY,OAA2B;CAC5E,IAAI;AAEJ,QAAO,QAAQ,KAAK,CAClB,GACA,IAAI,SAAgB,UAAU,WAAW;AACvC,UAAQ,iBAAiB,uBAAO,IAAI,MAAM,GAAG,MAAM,mBAAmB,GAAG,IAAI,CAAC,EAAE,GAAG;GACnF,CACH,CAAC,CAAC,cAAc;AACf,MAAI,UAAU,KAAA,EACZ,cAAa,MAAM;GAErB;;;;;;AAOJ,IAAa,WAAb,MAAa,SAAqD;CAChE,OAAe;CACf,OAAe,eAAwB;CAEvC,OAAc,MAAM,cAAsC;AACxD,SAAO,IAAI,SAAS,MAAM,aAAa;;CAGzC,OAAgB,UAAU;EACxB,QAAQ;EACR,sBAAsB;EACtB,yBAAyB;EAC1B;CAGD;CACA;CAEA,cAA6B;AAC3B,SAAO,KAAK;;CAGd,aAA6B;AAC3B,SAAO,CAAC,KAAK,UAAU,WAAW,cAAc;;CAGlD,SAAkC;AAChC,SAAO,KAAK;;CAGd;CACA;CACA;CACA;CAEA,aAA0C,EAAE,OAAO,gBAAgB;;CAEnE,oBAAkD;;;;;;;;CAQlD;;;;;;;;;CAUA,kBAA8C;AAC5C,SAAO,EAAE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AAC,MAAM,QAAQ;EAC9D,IAAI,QAAgB;AAEpB,OAAK,IAAI,IAAI,GAAG,IAAI,IAAI,cAAc,QAAQ,IAC5C,KAAI,IAAI,cAAc,GAAG,YAAY,QACnC,SAAQ;AAIZ,MAAI,UAAU,GACZ,KAAI,cAAc,OAAO,OAAO,EAAE;AAEpC,SAAO,eAAe,KAAK,CAAC,IAAI,IAAI;GACpC;;AAGJ,eAAsB,kBAAkB,MAAc;AACpD,QAAO,qCAAqC,KAAK"}
@@ -1,8 +1,14 @@
1
1
  import "../../_virtual/_rolldown/runtime.mjs";
2
2
  import { logger } from "../../util/logger.mjs";
3
3
  import pouchdb_setup_default from "./pouchdb-setup.mjs";
4
+ import { perfMark } from "../../util/perfMarks.mjs";
4
5
  import { getCourseDB } from "./index.mjs";
5
6
  //#region src/impl/couch/CourseSyncService.ts
7
+ /**
8
+ * Written into the local replica when a sync completes. `_local/` docs don't
9
+ * replicate, so it describes this device's copy.
10
+ */
11
+ const SYNC_MARKER_ID = "_local/sk-course-sync-complete";
6
12
  const DEFAULT_REPLICATION = {
7
13
  batchSize: 1e3,
8
14
  batchesLimit: 5
@@ -59,15 +65,7 @@ var CourseSyncService = class CourseSyncService {
59
65
  */
60
66
  async ensureSynced(courseId, forceEnabled) {
61
67
  const existing = this.entries.get(courseId);
62
- if (existing?.status.state === "ready" && existing.localDB) {
63
- if (!await this.isLocalEpochStale(courseId, existing.localDB)) return;
64
- logger.info(`[CourseSyncService] Remote DB epoch changed for course ${courseId} — destroying stale local replica`);
65
- try {
66
- await existing.localDB.destroy();
67
- } catch {}
68
- existing.localDB = null;
69
- existing.readyPromise = null;
70
- }
68
+ if (existing?.status.state === "ready" && existing.localDB) return;
71
69
  if (existing?.status.state === "disabled") return;
72
70
  if (existing?.readyPromise) return existing.readyPromise;
73
71
  const entry = {
@@ -76,10 +74,100 @@ var CourseSyncService = class CourseSyncService {
76
74
  readyPromise: null
77
75
  };
78
76
  this.entries.set(courseId, entry);
79
- entry.readyPromise = this.performSync(courseId, entry, forceEnabled);
77
+ entry.readyPromise = this.startSync(courseId, entry, forceEnabled);
80
78
  return entry.readyPromise;
81
79
  }
82
80
  /**
81
+ * A replica completed on an earlier page load is ready now, refreshed in the
82
+ * background; anything else goes through a full performSync.
83
+ */
84
+ async startSync(courseId, entry, forceEnabled) {
85
+ const localDB = new pouchdb_setup_default(this.localDBName(courseId));
86
+ if (await this.hasSyncMarker(localDB)) {
87
+ entry.localDB = localDB;
88
+ entry.status = { state: "ready" };
89
+ entry.readyPromise = null;
90
+ perfMark("sk:course-sync-ready", {
91
+ courseId,
92
+ from: "marker"
93
+ });
94
+ logger.info(`[CourseSyncService] Using this device's replica of course ${courseId}; refreshing in the background`);
95
+ this.refreshInBackground(courseId, entry, forceEnabled);
96
+ return;
97
+ }
98
+ return this.performSync(courseId, entry, forceEnabled);
99
+ }
100
+ /**
101
+ * Bring a ready replica up to date without taking it away from readers.
102
+ * Failures leave it ready (and outdated).
103
+ */
104
+ async refreshInBackground(courseId, entry, forceEnabled) {
105
+ const localDB = entry.localDB;
106
+ try {
107
+ if (!forceEnabled && !await this.checkLocalSyncEnabled(courseId)) {
108
+ await this.clearSyncMarker(localDB);
109
+ logger.info(`[CourseSyncService] Local sync no longer enabled for course ${courseId}; replica kept for this page only`);
110
+ return;
111
+ }
112
+ if (await this.isLocalEpochStale(courseId, localDB)) {
113
+ await this.clearSyncMarker(localDB);
114
+ logger.info(`[CourseSyncService] Remote DB recreated for course ${courseId}: keeping the outdated replica for this page; it is rebuilt on the next page load`);
115
+ return;
116
+ }
117
+ const start = Date.now();
118
+ const result = await this.replicate(this.getRemoteDB(courseId), localDB);
119
+ const syncTimeMs = Date.now() - start;
120
+ const warmStart = Date.now();
121
+ await this.warmViewIndices(localDB);
122
+ const viewWarmTimeMs = Date.now() - warmStart;
123
+ await this.writeSyncMarker(localDB);
124
+ entry.status = {
125
+ state: "ready",
126
+ docsReplicated: result.docs_written,
127
+ syncTimeMs,
128
+ viewWarmTimeMs
129
+ };
130
+ perfMark("sk:course-sync-refreshed", {
131
+ courseId,
132
+ docs: result.docs_written,
133
+ syncTimeMs,
134
+ viewWarmTimeMs
135
+ });
136
+ logger.info(`[CourseSyncService] Background refresh of course ${courseId}: ${result.docs_written} docs in ${syncTimeMs}ms, views ${viewWarmTimeMs}ms`);
137
+ } catch (e) {
138
+ logger.warn(`[CourseSyncService] Background refresh of course ${courseId} failed; replica kept as is: ${e}`);
139
+ }
140
+ }
141
+ async hasSyncMarker(localDB) {
142
+ try {
143
+ await localDB.get(SYNC_MARKER_ID);
144
+ return true;
145
+ } catch {
146
+ return false;
147
+ }
148
+ }
149
+ async writeSyncMarker(localDB) {
150
+ try {
151
+ let _rev;
152
+ try {
153
+ _rev = (await localDB.get(SYNC_MARKER_ID))._rev;
154
+ } catch {}
155
+ await localDB.put({
156
+ _id: SYNC_MARKER_ID,
157
+ _rev,
158
+ completedAt: (/* @__PURE__ */ new Date()).toISOString()
159
+ });
160
+ } catch (e) {
161
+ logger.warn(`[CourseSyncService] Could not write sync marker: ${e}`);
162
+ }
163
+ }
164
+ async clearSyncMarker(localDB) {
165
+ try {
166
+ const marker = await localDB.get(SYNC_MARKER_ID);
167
+ await localDB.remove(marker);
168
+ } catch {}
169
+ }
170
+ /**
83
171
  * Get the local PouchDB for a course, or null if not available.
84
172
  *
85
173
  * Returns null when:
@@ -130,18 +218,29 @@ var CourseSyncService = class CourseSyncService {
130
218
  logger.info(`[CourseSyncService] Starting one-shot replication for course ${courseId} (batch_size=${this.replicationOptions.batchSize}, batches_limit=${this.replicationOptions.batchesLimit})`);
131
219
  const result = await this.replicate(remoteDB, localDB);
132
220
  const syncTimeMs = Date.now() - syncStart;
221
+ perfMark("sk:course-sync-replicated", {
222
+ courseId,
223
+ docs: result.docs_written,
224
+ ms: syncTimeMs
225
+ });
133
226
  logger.info(`[CourseSyncService] Replication complete for course ${courseId}: ${result.docs_written} docs in ${syncTimeMs}ms`);
134
227
  entry.status = { state: "warming-views" };
135
228
  const warmStart = Date.now();
136
229
  await this.warmViewIndices(localDB);
137
230
  const viewWarmTimeMs = Date.now() - warmStart;
138
231
  logger.info(`[CourseSyncService] View indices warmed for course ${courseId} in ${viewWarmTimeMs}ms`);
232
+ await this.writeSyncMarker(localDB);
139
233
  entry.status = {
140
234
  state: "ready",
141
235
  docsReplicated: result.docs_written,
142
236
  syncTimeMs,
143
237
  viewWarmTimeMs
144
238
  };
239
+ perfMark("sk:course-sync-ready", {
240
+ courseId,
241
+ from: "sync",
242
+ viewWarmTimeMs
243
+ });
145
244
  } catch (e) {
146
245
  const errorMsg = e instanceof Error ? e.message : String(e);
147
246
  logger.error(`[CourseSyncService] Sync failed for course ${courseId}: ${errorMsg}`);
@@ -216,7 +315,8 @@ var CourseSyncService = class CourseSyncService {
216
315
  try {
217
316
  localEpoch = await localDB.get("db-epoch");
218
317
  } catch {
219
- return true;
318
+ const info = await localDB.info();
319
+ return info.doc_count > 0 || !!info.update_seq;
220
320
  }
221
321
  return remoteEpoch.epoch !== localEpoch.epoch;
222
322
  } catch {