@vue-skuilder/db 0.2.37 → 0.3.1
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.
- package/dist/{contentSource-D_E7JaxR.d.ts → contentSource-2zVmcjKA.d.ts} +6 -1
- package/dist/core/index.cjs +155 -100
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.ts +5 -5
- package/dist/core/navigators/Pipeline.mjs +8 -0
- package/dist/core/navigators/Pipeline.mjs.map +1 -1
- package/dist/core/versionStamps.mjs +1 -1
- package/dist/{dataLayerProvider-BDshhSp_.d.ts → dataLayerProvider-rGyLQ93v.d.ts} +1 -1
- package/dist/diagnostics/index.d.ts +3 -3
- package/dist/impl/common/BaseUserDB.mjs +61 -34
- package/dist/impl/common/BaseUserDB.mjs.map +1 -1
- package/dist/impl/couch/CourseSyncService.mjs +23 -1
- package/dist/impl/couch/CourseSyncService.mjs.map +1 -1
- package/dist/impl/couch/courseDB.mjs +4 -0
- package/dist/impl/couch/courseDB.mjs.map +1 -1
- package/dist/impl/couch/index.cjs +177 -101
- package/dist/impl/couch/index.cjs.map +1 -1
- package/dist/impl/couch/index.d.ts +5 -3
- package/dist/impl/couch/updateQueue.mjs +69 -46
- package/dist/impl/couch/updateQueue.mjs.map +1 -1
- package/dist/impl/static/index.cjs +151 -100
- package/dist/impl/static/index.cjs.map +1 -1
- package/dist/impl/static/index.d.ts +4 -4
- package/dist/{index-BLDpFYG3.d.ts → index-C745YB_6.d.ts} +1 -1
- package/dist/index.cjs +187 -102
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +23 -10
- package/dist/index.mjs +2 -1
- package/dist/study/SessionController.mjs +4 -0
- package/dist/study/SessionController.mjs.map +1 -1
- package/dist/{types-DChCz22D.d.ts → types-DF0JuPbs.d.ts} +1 -1
- package/dist/{types-legacy-fT5Y1Wuy.d.ts → types-legacy-DdVjg81H.d.ts} +1 -1
- package/dist/util/packer/index.d.ts +3 -3
- package/dist/util/perfMarks.mjs +30 -0
- package/dist/util/perfMarks.mjs.map +1 -0
- package/docs/session-lifecycle-and-replan.md +71 -58
- package/package.json +3 -3
- package/src/core/interfaces/courseDB.ts +6 -0
- package/src/core/navigators/Pipeline.ts +8 -0
- package/src/impl/common/BaseUserDB.ts +74 -46
- package/src/impl/couch/CourseSyncService.ts +19 -2
- package/src/impl/couch/courseDB.ts +5 -0
- package/src/impl/couch/updateQueue.ts +86 -82
- package/src/study/SessionController.ts +4 -0
- package/src/util/index.ts +1 -0
- package/src/util/perfMarks.ts +35 -0
- 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 /**\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 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;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,GAAG,KAAK,YAAY;;;;;;;;;;;;CAa/B,MAAa,iBA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ACZ,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 /** See scanScheduledCards. Bumped by every write to scheduled reviews. */\n private _scheduledScan: { generation: number; scan: Promise<ScheduledCard[]> } | null = null;\n private _scheduledGeneration = 0;\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 return (await this.scanScheduledCards()).map((doc) => ({\n courseID: doc.courseId,\n cardID: doc.cardId,\n }));\n }\n\n /**\n * The user's scheduled reviews (`card_review_*`), all of them: one `allDocs`\n * scan shared by concurrent readers. A pipeline run's generators start\n * together (`CompositeGenerator`), and each used to scan the range itself\n * (`getActiveCards` from ELO and Prescribed, `getReviewstoDate` from SRS).\n * Sharing only an in-flight scan keeps reads as fresh as before; a schedule\n * or removal of a review starts a new scan for anyone reading after it.\n * Docs are shared between callers: copy before mutating.\n */\n private scanScheduledCards(): Promise<ScheduledCard[]> {\n const inFlight = this._scheduledScan;\n if (inFlight && inFlight.generation === this._scheduledGeneration) return inFlight.scan;\n\n const keys = getStartAndEndKeys(DocTypePrefixes[DocType.SCHEDULED_CARD]);\n const entry = {\n generation: this._scheduledGeneration,\n scan: this.remoteDB\n .allDocs<ScheduledCard>({\n startkey: keys.startkey,\n endkey: keys.endkey,\n include_docs: true,\n })\n .then((res) => res.rows.map((row) => row.doc!)),\n };\n this._scheduledScan = entry;\n const done = () => {\n if (this._scheduledScan === entry) this._scheduledScan = null;\n };\n entry.scan.then(done, done);\n return entry.scan;\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 reviews = await this.scanScheduledCards();\n\n log(\n `Fetching ${this._username}'s scheduled reviews${\n course_id ? ` for course ${course_id}` : ''\n }.`\n );\n return reviews\n .filter((doc) => {\n if (doc._id.startsWith(DocTypePrefixes[DocType.SCHEDULED_CARD])) {\n const date = moment.utc(\n doc._id.substr(DocTypePrefixes[DocType.SCHEDULED_CARD].length),\n REVIEW_TIME_FORMAT\n );\n if (targetDate.isAfter(date)) {\n if (course_id === undefined || doc.courseId === course_id) {\n return true;\n }\n }\n }\n })\n .map((doc) => ({ ...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 this._scheduledGeneration++;\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 this._scheduledGeneration++;\n return scheduleCardReviewLocal(this.writeDB, review);\n }\n public async removeScheduledCardReview(reviewId: string): Promise<void> {\n this._scheduledGeneration++;\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;AACx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,QAAO;;AAGT,eAAsB,cAAc,MAAc,WAAmB,KAAgB;CACnF,MAAM,SAAS,MAAM,kCAAkC,KAAK;CAC5D,MAAM,SAAS,OAAO,QAAQ,MAAM,MAAM,EAAE,aAAa,UAAU;AACnE,QAAO,MAAM;AACb,QAAO,eAAe,KAAK,CAAC,IAAI,OAAO;;AAGzC,eAAsB,yBACpB,MACA,SACA,YACA;AACA,KAAI,qBAAqB,KAAK,cAAc,UAAU;AACtD,QAAO,qCAAqC,KAAK,CAAC,MAAM,QAAQ;EAC9D,MAAM,UAAU;GACL;GACT,cAAc;GACf;AAED,MACE,IAAI,cAAc,QAAQ,QAAQ;AAChC,UAAO,IAAI,YAAY,QAAQ,WAAW,IAAI,iBAAiB,QAAQ;IACvE,CAAC,WAAW,EAEd,KAAI,cAAc,KAAK,QAAQ;MAE/B,KAAI,QAAQ,KAAK,mCAAmC,UAAU;AAGhE,SAAO,eAAe,KAAK,CAAC,IAAI,IAAI;GACpC;;AAGJ,eAAsB,sBAAsB,MAAc,SAAiB;AACzE,QAAO,qCAAqC,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,6 +1,7 @@
|
|
|
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
|
|
6
7
|
/**
|
|
@@ -86,6 +87,10 @@ var CourseSyncService = class CourseSyncService {
|
|
|
86
87
|
entry.localDB = localDB;
|
|
87
88
|
entry.status = { state: "ready" };
|
|
88
89
|
entry.readyPromise = null;
|
|
90
|
+
perfMark("sk:course-sync-ready", {
|
|
91
|
+
courseId,
|
|
92
|
+
from: "marker"
|
|
93
|
+
});
|
|
89
94
|
logger.info(`[CourseSyncService] Using this device's replica of course ${courseId}; refreshing in the background`);
|
|
90
95
|
this.refreshInBackground(courseId, entry, forceEnabled);
|
|
91
96
|
return;
|
|
@@ -122,6 +127,12 @@ var CourseSyncService = class CourseSyncService {
|
|
|
122
127
|
syncTimeMs,
|
|
123
128
|
viewWarmTimeMs
|
|
124
129
|
};
|
|
130
|
+
perfMark("sk:course-sync-refreshed", {
|
|
131
|
+
courseId,
|
|
132
|
+
docs: result.docs_written,
|
|
133
|
+
syncTimeMs,
|
|
134
|
+
viewWarmTimeMs
|
|
135
|
+
});
|
|
125
136
|
logger.info(`[CourseSyncService] Background refresh of course ${courseId}: ${result.docs_written} docs in ${syncTimeMs}ms, views ${viewWarmTimeMs}ms`);
|
|
126
137
|
} catch (e) {
|
|
127
138
|
logger.warn(`[CourseSyncService] Background refresh of course ${courseId} failed; replica kept as is: ${e}`);
|
|
@@ -207,6 +218,11 @@ var CourseSyncService = class CourseSyncService {
|
|
|
207
218
|
logger.info(`[CourseSyncService] Starting one-shot replication for course ${courseId} (batch_size=${this.replicationOptions.batchSize}, batches_limit=${this.replicationOptions.batchesLimit})`);
|
|
208
219
|
const result = await this.replicate(remoteDB, localDB);
|
|
209
220
|
const syncTimeMs = Date.now() - syncStart;
|
|
221
|
+
perfMark("sk:course-sync-replicated", {
|
|
222
|
+
courseId,
|
|
223
|
+
docs: result.docs_written,
|
|
224
|
+
ms: syncTimeMs
|
|
225
|
+
});
|
|
210
226
|
logger.info(`[CourseSyncService] Replication complete for course ${courseId}: ${result.docs_written} docs in ${syncTimeMs}ms`);
|
|
211
227
|
entry.status = { state: "warming-views" };
|
|
212
228
|
const warmStart = Date.now();
|
|
@@ -220,6 +236,11 @@ var CourseSyncService = class CourseSyncService {
|
|
|
220
236
|
syncTimeMs,
|
|
221
237
|
viewWarmTimeMs
|
|
222
238
|
};
|
|
239
|
+
perfMark("sk:course-sync-ready", {
|
|
240
|
+
courseId,
|
|
241
|
+
from: "sync",
|
|
242
|
+
viewWarmTimeMs
|
|
243
|
+
});
|
|
223
244
|
} catch (e) {
|
|
224
245
|
const errorMsg = e instanceof Error ? e.message : String(e);
|
|
225
246
|
logger.error(`[CourseSyncService] Sync failed for course ${courseId}: ${errorMsg}`);
|
|
@@ -294,7 +315,8 @@ var CourseSyncService = class CourseSyncService {
|
|
|
294
315
|
try {
|
|
295
316
|
localEpoch = await localDB.get("db-epoch");
|
|
296
317
|
} catch {
|
|
297
|
-
|
|
318
|
+
const info = await localDB.info();
|
|
319
|
+
return info.doc_count > 0 || !!info.update_seq;
|
|
298
320
|
}
|
|
299
321
|
return remoteEpoch.epoch !== localEpoch.epoch;
|
|
300
322
|
} catch {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CourseSyncService.mjs","names":["pouch"],"sources":["../../../src/impl/couch/CourseSyncService.ts"],"sourcesContent":["import pouch from './pouchdb-setup';\nimport { getCourseDB } from '.';\nimport { logger } from '../../util/logger';\nimport type { CourseConfig } from '@vue-skuilder/common';\n\n// ============================================================================\n// COURSE SYNC SERVICE\n// ============================================================================\n//\n// Manages client-side PouchDB replicas of course databases.\n//\n// Courses opt in to local sync via CourseConfig.localSync.enabled. When\n// enabled, the service performs a one-shot replication from remote CouchDB\n// to a local PouchDB on first visit, then incremental sync on subsequent\n// visits. Pipeline scoring, tag hydration, and card lookup then run against\n// the local replica — eliminating network round trips from the study-session\n// hot path.\n//\n// Read/write split:\n// Local DB = read-only snapshot (pipeline, filters, card lookup)\n// Remote DB = all writes (ELO updates, tag mutations, admin ops)\n//\n// This avoids propagating per-interaction ELO write noise to every syncing\n// client. Each client's local snapshot refreshes on the next page load.\n//\n// A replica that completed a sync on an earlier page load carries a\n// `_local/` marker, and is handed out as ready immediately; its refresh\n// (epoch check, incremental pull, view warming) runs in the background, into\n// the same DB. Sessions may therefore start on the previous visit's data and\n// catch up seconds later. If that refresh finds the remote DB recreated (an\n// epoch change), the replica is NOT destroyed under running readers: the\n// marker is dropped, this page keeps the outdated copy, and the next page\n// load rebuilds it from scratch (the path a device without a replica takes).\n//\n// Live replication is intentionally NOT supported. The remote course DB\n// receives high-frequency ELO updates from all concurrent users — live\n// sync would cause constant re-indexing of local PouchDB views.\n//\n// ============================================================================\n\n/**\n * Sync state for a single course database.\n */\nexport type CourseSyncState =\n | 'not-started'\n | 'checking-config'\n | 'syncing'\n | 'warming-views'\n | 'ready'\n | 'disabled'\n | 'error';\n\n/**\n * Written into the local replica when a sync completes. `_local/` docs don't\n * replicate, so it describes this device's copy.\n */\nconst SYNC_MARKER_ID = '_local/sk-course-sync-complete';\n\n/**\n * Detailed sync status for observability.\n */\nexport interface CourseSyncStatus {\n state: CourseSyncState;\n /** Number of documents replicated (set after sync completes) */\n docsReplicated?: number;\n /** Total replication time in ms */\n syncTimeMs?: number;\n /** View warming time in ms */\n viewWarmTimeMs?: number;\n /** Error message if state is 'error' */\n error?: string;\n}\n\n/**\n * Internal tracking entry per course.\n */\ninterface SyncEntry {\n localDB: PouchDB.Database | null;\n status: CourseSyncStatus;\n /** Promise that resolves when sync is complete (or rejects on failure) */\n readyPromise: Promise<void> | null;\n}\n\n/**\n * Service that manages local PouchDB replicas of course databases.\n *\n * Usage:\n * ```typescript\n * const syncService = CourseSyncService.getInstance();\n *\n * // Trigger sync (typically on app load / pre-session)\n * await syncService.ensureSynced(courseId);\n *\n * // Get local DB for reads (returns null if sync not ready/enabled)\n * const localDB = syncService.getLocalDB(courseId);\n * ```\n *\n * The service is a singleton — course sync state is shared across the app.\n */\n/**\n * Tuning knobs for one-shot remote→local replication.\n * Defaults are chosen for one-shot snapshot replication of bounded course\n * corpora (text/JSON docs, no large attachments). PouchDB's built-in\n * defaults (100/10) target live continuous sync — too conservative for\n * cold-load UX on a course of a few thousand docs.\n *\n * Apps with smaller/larger corpora can override via\n * `initializeDataLayer({ options: { courseSync: { replication: {...} } } })`.\n */\nexport interface ReplicationOptions {\n /** Docs per `_bulk_get` HTTP request. Higher = fewer roundtrips. */\n batchSize?: number;\n /** Concurrent batches in flight. */\n batchesLimit?: number;\n}\n\nconst DEFAULT_REPLICATION: Required<ReplicationOptions> = {\n batchSize: 1000,\n batchesLimit: 5,\n};\n\nexport class CourseSyncService {\n private static instance: CourseSyncService | null = null;\n\n private entries: Map<string, SyncEntry> = new Map();\n private replicationOptions: Required<ReplicationOptions> = DEFAULT_REPLICATION;\n\n private constructor() {}\n\n static getInstance(): CourseSyncService {\n if (!CourseSyncService.instance) {\n CourseSyncService.instance = new CourseSyncService();\n }\n return CourseSyncService.instance;\n }\n\n /**\n * Apply replication tuning. Typically called once from `initializeDataLayer`.\n * Partial overrides merge with defaults.\n */\n configure(opts: { replication?: ReplicationOptions }): void {\n if (opts.replication) {\n this.replicationOptions = {\n ...DEFAULT_REPLICATION,\n ...opts.replication,\n };\n logger.info(\n `[CourseSyncService] Replication configured: ` +\n `batch_size=${this.replicationOptions.batchSize}, ` +\n `batches_limit=${this.replicationOptions.batchesLimit}`\n );\n }\n }\n\n /**\n * Reset the singleton (for testing).\n */\n static resetInstance(): void {\n if (CourseSyncService.instance) {\n // Close all local DBs\n for (const [, entry] of CourseSyncService.instance.entries) {\n if (entry.localDB) {\n entry.localDB.close().catch(() => {});\n }\n }\n CourseSyncService.instance.entries.clear();\n }\n CourseSyncService.instance = null;\n }\n\n // --------------------------------------------------------------------------\n // Public API\n // --------------------------------------------------------------------------\n\n /**\n * Ensure a course's local replica is synced.\n *\n * On first call for a course:\n * 1. Fetches CourseConfig from remote to check localSync.enabled\n * 2. If enabled, performs one-shot replication remote → local\n * 3. Pre-warms PouchDB view indices (elo, getTags)\n *\n * On subsequent calls: returns immediately if already synced, or awaits\n * the in-flight sync if one is in progress.\n *\n * Safe to call multiple times — concurrent calls coalesce to one sync.\n *\n * @param courseId - The course to sync\n * @param forceEnabled - Skip the CourseConfig check and sync regardless.\n * Useful when the caller already knows local sync is desired (e.g.,\n * LettersPractice hardcodes this).\n */\n async ensureSynced(courseId: string, forceEnabled?: boolean): Promise<void> {\n const existing = this.entries.get(courseId);\n\n // Ready on this page load. Its epoch was checked on the way (by\n // performSync, or by the background refresh, which keeps an outdated\n // replica rather than destroy it under running sessions).\n if (existing?.status.state === 'ready' && existing.localDB) {\n return;\n }\n\n // Already disabled\n if (existing?.status.state === 'disabled') {\n return;\n }\n\n // Sync in flight — coalesce\n if (existing?.readyPromise) {\n return existing.readyPromise;\n }\n\n // Start a new sync\n const entry: SyncEntry = {\n localDB: null,\n status: { state: 'not-started' },\n readyPromise: null,\n };\n this.entries.set(courseId, entry);\n\n entry.readyPromise = this.startSync(courseId, entry, forceEnabled);\n return entry.readyPromise;\n }\n\n /**\n * A replica completed on an earlier page load is ready now, refreshed in the\n * background; anything else goes through a full performSync.\n */\n private async startSync(\n courseId: string,\n entry: SyncEntry,\n forceEnabled?: boolean\n ): Promise<void> {\n const localDB = new pouch(this.localDBName(courseId));\n if (await this.hasSyncMarker(localDB)) {\n entry.localDB = localDB;\n entry.status = { state: 'ready' };\n entry.readyPromise = null;\n logger.info(\n `[CourseSyncService] Using this device's replica of course ${courseId}; refreshing in the background`\n );\n void this.refreshInBackground(courseId, entry, forceEnabled);\n return;\n }\n return this.performSync(courseId, entry, forceEnabled);\n }\n\n /**\n * Bring a ready replica up to date without taking it away from readers.\n * Failures leave it ready (and outdated).\n */\n private async refreshInBackground(\n courseId: string,\n entry: SyncEntry,\n forceEnabled?: boolean\n ): Promise<void> {\n const localDB = entry.localDB!;\n try {\n if (!forceEnabled && !(await this.checkLocalSyncEnabled(courseId))) {\n await this.clearSyncMarker(localDB);\n logger.info(\n `[CourseSyncService] Local sync no longer enabled for course ${courseId}; replica kept for this page only`\n );\n return;\n }\n\n if (await this.isLocalEpochStale(courseId, localDB)) {\n await this.clearSyncMarker(localDB);\n logger.info(\n `[CourseSyncService] Remote DB recreated for course ${courseId}: keeping the outdated replica ` +\n `for this page; it is rebuilt on the next page load`\n );\n return;\n }\n\n const start = Date.now();\n const result = await this.replicate(this.getRemoteDB(courseId), localDB);\n const syncTimeMs = Date.now() - start;\n const warmStart = Date.now();\n await this.warmViewIndices(localDB);\n const viewWarmTimeMs = Date.now() - warmStart;\n await this.writeSyncMarker(localDB);\n entry.status = {\n state: 'ready',\n docsReplicated: result.docs_written,\n syncTimeMs,\n viewWarmTimeMs,\n };\n logger.info(\n `[CourseSyncService] Background refresh of course ${courseId}: ` +\n `${result.docs_written} docs in ${syncTimeMs}ms, views ${viewWarmTimeMs}ms`\n );\n } catch (e) {\n logger.warn(\n `[CourseSyncService] Background refresh of course ${courseId} failed; replica kept as is: ${e}`\n );\n }\n }\n\n private async hasSyncMarker(localDB: PouchDB.Database): Promise<boolean> {\n try {\n await localDB.get(SYNC_MARKER_ID);\n return true;\n } catch {\n return false;\n }\n }\n\n private async writeSyncMarker(localDB: PouchDB.Database): Promise<void> {\n try {\n let _rev: string | undefined;\n try {\n _rev = (await localDB.get(SYNC_MARKER_ID))._rev;\n } catch {\n // First completion on this device.\n }\n await localDB.put({ _id: SYNC_MARKER_ID, _rev, completedAt: new Date().toISOString() });\n } catch (e) {\n // Costs the next page load the full-sync path, not correctness.\n logger.warn(`[CourseSyncService] Could not write sync marker: ${e}`);\n }\n }\n\n private async clearSyncMarker(localDB: PouchDB.Database): Promise<void> {\n try {\n const marker = await localDB.get(SYNC_MARKER_ID);\n await localDB.remove(marker);\n } catch {\n // Absent already.\n }\n }\n\n /**\n * Get the local PouchDB for a course, or null if not available.\n *\n * Returns null when:\n * - Local sync is not enabled for this course\n * - Sync has not been triggered yet\n * - Sync is still in progress\n * - Sync failed\n */\n getLocalDB(courseId: string): PouchDB.Database | null {\n const entry = this.entries.get(courseId);\n if (entry?.status.state === 'ready' && entry.localDB) {\n return entry.localDB;\n }\n return null;\n }\n\n /**\n * Check whether a course has a ready local replica.\n */\n isReady(courseId: string): boolean {\n return this.entries.get(courseId)?.status.state === 'ready';\n }\n\n /**\n * Get detailed sync status for a course.\n */\n getStatus(courseId: string): CourseSyncStatus {\n return (\n this.entries.get(courseId)?.status ?? { state: 'not-started' }\n );\n }\n\n // --------------------------------------------------------------------------\n // Internal\n // --------------------------------------------------------------------------\n\n private async performSync(\n courseId: string,\n entry: SyncEntry,\n forceEnabled?: boolean\n ): Promise<void> {\n try {\n // Step 1: Check if local sync is enabled for this course\n if (!forceEnabled) {\n entry.status = { state: 'checking-config' };\n const enabled = await this.checkLocalSyncEnabled(courseId);\n if (!enabled) {\n entry.status = { state: 'disabled' };\n entry.readyPromise = null;\n logger.debug(\n `[CourseSyncService] Local sync disabled for course ${courseId}`\n );\n return;\n }\n }\n\n // Step 2: Create local PouchDB and replicate\n entry.status = { state: 'syncing' };\n const localDBName = this.localDBName(courseId);\n let localDB = new pouch(localDBName);\n\n // Check for stale local replica before replicating. If the remote DB\n // was wiped and recreated (e.g., `yarn db:seed`), the local PouchDB\n // has documents at rev 1-oldHash while the remote has 1-newHash for\n // the same _ids. PouchDB replication treats this as a conflict rather\n // than an update, and the stale revision can win — causing partial or\n // incorrect data. Destroying the stale local DB avoids this entirely.\n const stale = await this.isLocalEpochStale(courseId, localDB);\n if (stale) {\n logger.info(\n `[CourseSyncService] Stale local DB detected for course ${courseId} — destroying before sync`\n );\n await localDB.destroy();\n localDB = new pouch(localDBName);\n }\n\n entry.localDB = localDB;\n\n const remoteDB = this.getRemoteDB(courseId);\n const syncStart = Date.now();\n\n logger.info(\n `[CourseSyncService] Starting one-shot replication for course ${courseId} ` +\n `(batch_size=${this.replicationOptions.batchSize}, ` +\n `batches_limit=${this.replicationOptions.batchesLimit})`\n );\n\n const result = await this.replicate(remoteDB, localDB);\n const syncTimeMs = Date.now() - syncStart;\n\n logger.info(\n `[CourseSyncService] Replication complete for course ${courseId}: ` +\n `${result.docs_written} docs in ${syncTimeMs}ms`\n );\n\n // Step 3: Pre-warm view indices\n entry.status = { state: 'warming-views' };\n const warmStart = Date.now();\n await this.warmViewIndices(localDB);\n const viewWarmTimeMs = Date.now() - warmStart;\n\n logger.info(\n `[CourseSyncService] View indices warmed for course ${courseId} in ${viewWarmTimeMs}ms`\n );\n\n await this.writeSyncMarker(localDB);\n\n // Done\n entry.status = {\n state: 'ready',\n docsReplicated: result.docs_written,\n syncTimeMs,\n viewWarmTimeMs,\n };\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n logger.error(\n `[CourseSyncService] Sync failed for course ${courseId}: ${errorMsg}`\n );\n entry.status = { state: 'error', error: errorMsg };\n entry.readyPromise = null;\n\n // Clean up the local DB on failure — don't leave a partial replica\n if (entry.localDB) {\n try {\n await entry.localDB.destroy();\n } catch {\n // Ignore cleanup errors\n }\n entry.localDB = null;\n }\n }\n }\n\n /**\n * Check CourseConfig.localSync.enabled on the remote DB.\n */\n private async checkLocalSyncEnabled(courseId: string): Promise<boolean> {\n try {\n const remoteDB = this.getRemoteDB(courseId);\n const config = await remoteDB.get<CourseConfig>('CourseConfig');\n return config.localSync?.enabled === true;\n } catch (e) {\n logger.warn(\n `[CourseSyncService] Could not read CourseConfig for ${courseId}, ` +\n `assuming local sync disabled: ${e}`\n );\n return false;\n }\n }\n\n /**\n * One-shot replication from remote to local.\n */\n private replicate(\n source: PouchDB.Database,\n target: PouchDB.Database\n ): Promise<PouchDB.Replication.ReplicationResultComplete<object>> {\n return new Promise((resolve, reject) => {\n void pouch.replicate(source, target, {\n // One-shot, not live. Local is a read-only snapshot.\n batch_size: this.replicationOptions.batchSize,\n batches_limit: this.replicationOptions.batchesLimit,\n })\n .on('complete', (info) => {\n resolve(info);\n })\n .on('error', (err) => {\n reject(err);\n });\n });\n }\n\n /**\n * Pre-warm PouchDB view indices by running a minimal query against each\n * design doc. This forces PouchDB to build the MapReduce index now\n * (during a loading phase) rather than on first pipeline query.\n */\n private async warmViewIndices(localDB: PouchDB.Database): Promise<void> {\n const viewsToWarm = ['elo', 'getTags'];\n\n for (const viewName of viewsToWarm) {\n try {\n await localDB.query(viewName, { limit: 1 });\n logger.debug(\n `[CourseSyncService] Warmed view index: ${viewName}`\n );\n } catch (e) {\n // View might not exist in this course DB — that's OK.\n // Not all courses have all design docs.\n logger.debug(\n `[CourseSyncService] Could not warm view ${viewName}: ${e}`\n );\n }\n }\n }\n\n /**\n * Check whether the local replica's `db-epoch` doc matches the remote.\n *\n * The seed script (and optionally upload-cards) writes a `db-epoch`\n * document with a numeric timestamp. If the remote epoch differs from\n * the local copy, the remote DB was recreated (e.g., `yarn db:seed`)\n * and the local PouchDB is stale.\n *\n * Returns `true` if stale (epoch mismatch or remote has epoch but local\n * doesn't). Returns `false` (not stale) if epochs match, or if the\n * remote doesn't have an epoch doc at all (backwards compat).\n */\n private async isLocalEpochStale(\n courseId: string,\n localDB: PouchDB.Database\n ): Promise<boolean> {\n try {\n const remoteDB = this.getRemoteDB(courseId);\n const remoteEpoch = await remoteDB.get<{ epoch: number }>('db-epoch');\n\n let localEpoch: { epoch: number } | null = null;\n try {\n localEpoch = await localDB.get<{ epoch: number }>('db-epoch');\n } catch {\n // Local doesn't have the epoch doc — stale\n return true;\n }\n\n return remoteEpoch.epoch !== localEpoch.epoch;\n } catch {\n // Remote doesn't have db-epoch — no epoch tracking, not stale\n return false;\n }\n }\n\n /**\n * Get a remote PouchDB handle for a course.\n */\n private getRemoteDB(courseId: string): PouchDB.Database {\n return getCourseDB(courseId);\n }\n\n /**\n * Local DB naming convention.\n */\n private localDBName(courseId: string): string {\n return `coursedb-local-${courseId}`;\n }\n}"],"mappings":";;;;;;;;;AAwDA,MAAM,iBAAiB;AA4DvB,MAAM,sBAAoD;CACxD,WAAW;CACX,cAAc;CACf;AAED,IAAa,oBAAb,MAAa,kBAAkB;CAC7B,OAAe,WAA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UAAO,MACL,0CAA0C,WAC3C;WACM,GAAG;AAGV,UAAO,MACL,2CAA2C,SAAS,IAAI,IACzD;;;;;;;;;;;;;;;CAiBP,MAAc,kBACZ,UACA,SACkB;AAClB,MAAI;GAEF,MAAM,cAAc,MADH,KAAK,YAAY,SAAS,CACR,IAAuB,WAAW;GAErE,IAAI,aAAuC;AAC3C,OAAI;AACF,iBAAa,MAAM,QAAQ,IAAuB,WAAW;WACvD;AAEN,WAAO;;AAGT,UAAO,YAAY,UAAU,WAAW;UAClC;AAEN,UAAO;;;;;;CAOX,YAAoB,UAAoC;AACtD,SAAO,YAAY,SAAS;;;;;CAM9B,YAAoB,UAA0B;AAC5C,SAAO,kBAAkB"}
|
|
1
|
+
{"version":3,"file":"CourseSyncService.mjs","names":["pouch"],"sources":["../../../src/impl/couch/CourseSyncService.ts"],"sourcesContent":["import pouch from './pouchdb-setup';\nimport { getCourseDB } from '.';\nimport { logger } from '../../util/logger';\nimport { perfMark } from '../../util/perfMarks';\nimport type { CourseConfig } from '@vue-skuilder/common';\n\n// ============================================================================\n// COURSE SYNC SERVICE\n// ============================================================================\n//\n// Manages client-side PouchDB replicas of course databases.\n//\n// Courses opt in to local sync via CourseConfig.localSync.enabled. When\n// enabled, the service performs a one-shot replication from remote CouchDB\n// to a local PouchDB on first visit, then incremental sync on subsequent\n// visits. Pipeline scoring, tag hydration, and card lookup then run against\n// the local replica — eliminating network round trips from the study-session\n// hot path.\n//\n// Read/write split:\n// Local DB = read-only snapshot (pipeline, filters, card lookup)\n// Remote DB = all writes (ELO updates, tag mutations, admin ops)\n//\n// This avoids propagating per-interaction ELO write noise to every syncing\n// client. Each client's local snapshot refreshes on the next page load.\n//\n// A replica that completed a sync on an earlier page load carries a\n// `_local/` marker, and is handed out as ready immediately; its refresh\n// (epoch check, incremental pull, view warming) runs in the background, into\n// the same DB. Sessions may therefore start on the previous visit's data and\n// catch up seconds later. If that refresh finds the remote DB recreated (an\n// epoch change), the replica is NOT destroyed under running readers: the\n// marker is dropped, this page keeps the outdated copy, and the next page\n// load rebuilds it from scratch (the path a device without a replica takes).\n//\n// Live replication is intentionally NOT supported. The remote course DB\n// receives high-frequency ELO updates from all concurrent users — live\n// sync would cause constant re-indexing of local PouchDB views.\n//\n// ============================================================================\n\n/**\n * Sync state for a single course database.\n */\nexport type CourseSyncState =\n | 'not-started'\n | 'checking-config'\n | 'syncing'\n | 'warming-views'\n | 'ready'\n | 'disabled'\n | 'error';\n\n/**\n * Written into the local replica when a sync completes. `_local/` docs don't\n * replicate, so it describes this device's copy.\n */\nconst SYNC_MARKER_ID = '_local/sk-course-sync-complete';\n\n/**\n * Detailed sync status for observability.\n */\nexport interface CourseSyncStatus {\n state: CourseSyncState;\n /** Number of documents replicated (set after sync completes) */\n docsReplicated?: number;\n /** Total replication time in ms */\n syncTimeMs?: number;\n /** View warming time in ms */\n viewWarmTimeMs?: number;\n /** Error message if state is 'error' */\n error?: string;\n}\n\n/**\n * Internal tracking entry per course.\n */\ninterface SyncEntry {\n localDB: PouchDB.Database | null;\n status: CourseSyncStatus;\n /** Promise that resolves when sync is complete (or rejects on failure) */\n readyPromise: Promise<void> | null;\n}\n\n/**\n * Service that manages local PouchDB replicas of course databases.\n *\n * Usage:\n * ```typescript\n * const syncService = CourseSyncService.getInstance();\n *\n * // Trigger sync (typically on app load / pre-session)\n * await syncService.ensureSynced(courseId);\n *\n * // Get local DB for reads (returns null if sync not ready/enabled)\n * const localDB = syncService.getLocalDB(courseId);\n * ```\n *\n * The service is a singleton — course sync state is shared across the app.\n */\n/**\n * Tuning knobs for one-shot remote→local replication.\n * Defaults are chosen for one-shot snapshot replication of bounded course\n * corpora (text/JSON docs, no large attachments). PouchDB's built-in\n * defaults (100/10) target live continuous sync — too conservative for\n * cold-load UX on a course of a few thousand docs.\n *\n * Apps with smaller/larger corpora can override via\n * `initializeDataLayer({ options: { courseSync: { replication: {...} } } })`.\n */\nexport interface ReplicationOptions {\n /** Docs per `_bulk_get` HTTP request. Higher = fewer roundtrips. */\n batchSize?: number;\n /** Concurrent batches in flight. */\n batchesLimit?: number;\n}\n\nconst DEFAULT_REPLICATION: Required<ReplicationOptions> = {\n batchSize: 1000,\n batchesLimit: 5,\n};\n\nexport class CourseSyncService {\n private static instance: CourseSyncService | null = null;\n\n private entries: Map<string, SyncEntry> = new Map();\n private replicationOptions: Required<ReplicationOptions> = DEFAULT_REPLICATION;\n\n private constructor() {}\n\n static getInstance(): CourseSyncService {\n if (!CourseSyncService.instance) {\n CourseSyncService.instance = new CourseSyncService();\n }\n return CourseSyncService.instance;\n }\n\n /**\n * Apply replication tuning. Typically called once from `initializeDataLayer`.\n * Partial overrides merge with defaults.\n */\n configure(opts: { replication?: ReplicationOptions }): void {\n if (opts.replication) {\n this.replicationOptions = {\n ...DEFAULT_REPLICATION,\n ...opts.replication,\n };\n logger.info(\n `[CourseSyncService] Replication configured: ` +\n `batch_size=${this.replicationOptions.batchSize}, ` +\n `batches_limit=${this.replicationOptions.batchesLimit}`\n );\n }\n }\n\n /**\n * Reset the singleton (for testing).\n */\n static resetInstance(): void {\n if (CourseSyncService.instance) {\n // Close all local DBs\n for (const [, entry] of CourseSyncService.instance.entries) {\n if (entry.localDB) {\n entry.localDB.close().catch(() => {});\n }\n }\n CourseSyncService.instance.entries.clear();\n }\n CourseSyncService.instance = null;\n }\n\n // --------------------------------------------------------------------------\n // Public API\n // --------------------------------------------------------------------------\n\n /**\n * Ensure a course's local replica is synced.\n *\n * On first call for a course:\n * 1. Fetches CourseConfig from remote to check localSync.enabled\n * 2. If enabled, performs one-shot replication remote → local\n * 3. Pre-warms PouchDB view indices (elo, getTags)\n *\n * On subsequent calls: returns immediately if already synced, or awaits\n * the in-flight sync if one is in progress.\n *\n * Safe to call multiple times — concurrent calls coalesce to one sync.\n *\n * @param courseId - The course to sync\n * @param forceEnabled - Skip the CourseConfig check and sync regardless.\n * Useful when the caller already knows local sync is desired (e.g.,\n * LettersPractice hardcodes this).\n */\n async ensureSynced(courseId: string, forceEnabled?: boolean): Promise<void> {\n const existing = this.entries.get(courseId);\n\n // Ready on this page load. Its epoch was checked on the way (by\n // performSync, or by the background refresh, which keeps an outdated\n // replica rather than destroy it under running sessions).\n if (existing?.status.state === 'ready' && existing.localDB) {\n return;\n }\n\n // Already disabled\n if (existing?.status.state === 'disabled') {\n return;\n }\n\n // Sync in flight — coalesce\n if (existing?.readyPromise) {\n return existing.readyPromise;\n }\n\n // Start a new sync\n const entry: SyncEntry = {\n localDB: null,\n status: { state: 'not-started' },\n readyPromise: null,\n };\n this.entries.set(courseId, entry);\n\n entry.readyPromise = this.startSync(courseId, entry, forceEnabled);\n return entry.readyPromise;\n }\n\n /**\n * A replica completed on an earlier page load is ready now, refreshed in the\n * background; anything else goes through a full performSync.\n */\n private async startSync(\n courseId: string,\n entry: SyncEntry,\n forceEnabled?: boolean\n ): Promise<void> {\n const localDB = new pouch(this.localDBName(courseId));\n if (await this.hasSyncMarker(localDB)) {\n entry.localDB = localDB;\n entry.status = { state: 'ready' };\n entry.readyPromise = null;\n perfMark('sk:course-sync-ready', { courseId, from: 'marker' });\n logger.info(\n `[CourseSyncService] Using this device's replica of course ${courseId}; refreshing in the background`\n );\n void this.refreshInBackground(courseId, entry, forceEnabled);\n return;\n }\n return this.performSync(courseId, entry, forceEnabled);\n }\n\n /**\n * Bring a ready replica up to date without taking it away from readers.\n * Failures leave it ready (and outdated).\n */\n private async refreshInBackground(\n courseId: string,\n entry: SyncEntry,\n forceEnabled?: boolean\n ): Promise<void> {\n const localDB = entry.localDB!;\n try {\n if (!forceEnabled && !(await this.checkLocalSyncEnabled(courseId))) {\n await this.clearSyncMarker(localDB);\n logger.info(\n `[CourseSyncService] Local sync no longer enabled for course ${courseId}; replica kept for this page only`\n );\n return;\n }\n\n if (await this.isLocalEpochStale(courseId, localDB)) {\n await this.clearSyncMarker(localDB);\n logger.info(\n `[CourseSyncService] Remote DB recreated for course ${courseId}: keeping the outdated replica ` +\n `for this page; it is rebuilt on the next page load`\n );\n return;\n }\n\n const start = Date.now();\n const result = await this.replicate(this.getRemoteDB(courseId), localDB);\n const syncTimeMs = Date.now() - start;\n const warmStart = Date.now();\n await this.warmViewIndices(localDB);\n const viewWarmTimeMs = Date.now() - warmStart;\n await this.writeSyncMarker(localDB);\n entry.status = {\n state: 'ready',\n docsReplicated: result.docs_written,\n syncTimeMs,\n viewWarmTimeMs,\n };\n perfMark('sk:course-sync-refreshed', {\n courseId,\n docs: result.docs_written,\n syncTimeMs,\n viewWarmTimeMs,\n });\n logger.info(\n `[CourseSyncService] Background refresh of course ${courseId}: ` +\n `${result.docs_written} docs in ${syncTimeMs}ms, views ${viewWarmTimeMs}ms`\n );\n } catch (e) {\n logger.warn(\n `[CourseSyncService] Background refresh of course ${courseId} failed; replica kept as is: ${e}`\n );\n }\n }\n\n private async hasSyncMarker(localDB: PouchDB.Database): Promise<boolean> {\n try {\n await localDB.get(SYNC_MARKER_ID);\n return true;\n } catch {\n return false;\n }\n }\n\n private async writeSyncMarker(localDB: PouchDB.Database): Promise<void> {\n try {\n let _rev: string | undefined;\n try {\n _rev = (await localDB.get(SYNC_MARKER_ID))._rev;\n } catch {\n // First completion on this device.\n }\n await localDB.put({ _id: SYNC_MARKER_ID, _rev, completedAt: new Date().toISOString() });\n } catch (e) {\n // Costs the next page load the full-sync path, not correctness.\n logger.warn(`[CourseSyncService] Could not write sync marker: ${e}`);\n }\n }\n\n private async clearSyncMarker(localDB: PouchDB.Database): Promise<void> {\n try {\n const marker = await localDB.get(SYNC_MARKER_ID);\n await localDB.remove(marker);\n } catch {\n // Absent already.\n }\n }\n\n /**\n * Get the local PouchDB for a course, or null if not available.\n *\n * Returns null when:\n * - Local sync is not enabled for this course\n * - Sync has not been triggered yet\n * - Sync is still in progress\n * - Sync failed\n */\n getLocalDB(courseId: string): PouchDB.Database | null {\n const entry = this.entries.get(courseId);\n if (entry?.status.state === 'ready' && entry.localDB) {\n return entry.localDB;\n }\n return null;\n }\n\n /**\n * Check whether a course has a ready local replica.\n */\n isReady(courseId: string): boolean {\n return this.entries.get(courseId)?.status.state === 'ready';\n }\n\n /**\n * Get detailed sync status for a course.\n */\n getStatus(courseId: string): CourseSyncStatus {\n return (\n this.entries.get(courseId)?.status ?? { state: 'not-started' }\n );\n }\n\n // --------------------------------------------------------------------------\n // Internal\n // --------------------------------------------------------------------------\n\n private async performSync(\n courseId: string,\n entry: SyncEntry,\n forceEnabled?: boolean\n ): Promise<void> {\n try {\n // Step 1: Check if local sync is enabled for this course\n if (!forceEnabled) {\n entry.status = { state: 'checking-config' };\n const enabled = await this.checkLocalSyncEnabled(courseId);\n if (!enabled) {\n entry.status = { state: 'disabled' };\n entry.readyPromise = null;\n logger.debug(\n `[CourseSyncService] Local sync disabled for course ${courseId}`\n );\n return;\n }\n }\n\n // Step 2: Create local PouchDB and replicate\n entry.status = { state: 'syncing' };\n const localDBName = this.localDBName(courseId);\n let localDB = new pouch(localDBName);\n\n // Check for stale local replica before replicating. If the remote DB\n // was wiped and recreated (e.g., `yarn db:seed`), the local PouchDB\n // has documents at rev 1-oldHash while the remote has 1-newHash for\n // the same _ids. PouchDB replication treats this as a conflict rather\n // than an update, and the stale revision can win — causing partial or\n // incorrect data. Destroying the stale local DB avoids this entirely.\n const stale = await this.isLocalEpochStale(courseId, localDB);\n if (stale) {\n logger.info(\n `[CourseSyncService] Stale local DB detected for course ${courseId} — destroying before sync`\n );\n await localDB.destroy();\n localDB = new pouch(localDBName);\n }\n\n entry.localDB = localDB;\n\n const remoteDB = this.getRemoteDB(courseId);\n const syncStart = Date.now();\n\n logger.info(\n `[CourseSyncService] Starting one-shot replication for course ${courseId} ` +\n `(batch_size=${this.replicationOptions.batchSize}, ` +\n `batches_limit=${this.replicationOptions.batchesLimit})`\n );\n\n const result = await this.replicate(remoteDB, localDB);\n const syncTimeMs = Date.now() - syncStart;\n perfMark('sk:course-sync-replicated', {\n courseId,\n docs: result.docs_written,\n ms: syncTimeMs,\n });\n\n logger.info(\n `[CourseSyncService] Replication complete for course ${courseId}: ` +\n `${result.docs_written} docs in ${syncTimeMs}ms`\n );\n\n // Step 3: Pre-warm view indices\n entry.status = { state: 'warming-views' };\n const warmStart = Date.now();\n await this.warmViewIndices(localDB);\n const viewWarmTimeMs = Date.now() - warmStart;\n\n logger.info(\n `[CourseSyncService] View indices warmed for course ${courseId} in ${viewWarmTimeMs}ms`\n );\n\n await this.writeSyncMarker(localDB);\n\n // Done\n entry.status = {\n state: 'ready',\n docsReplicated: result.docs_written,\n syncTimeMs,\n viewWarmTimeMs,\n };\n perfMark('sk:course-sync-ready', { courseId, from: 'sync', viewWarmTimeMs });\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n logger.error(\n `[CourseSyncService] Sync failed for course ${courseId}: ${errorMsg}`\n );\n entry.status = { state: 'error', error: errorMsg };\n entry.readyPromise = null;\n\n // Clean up the local DB on failure — don't leave a partial replica\n if (entry.localDB) {\n try {\n await entry.localDB.destroy();\n } catch {\n // Ignore cleanup errors\n }\n entry.localDB = null;\n }\n }\n }\n\n /**\n * Check CourseConfig.localSync.enabled on the remote DB.\n */\n private async checkLocalSyncEnabled(courseId: string): Promise<boolean> {\n try {\n const remoteDB = this.getRemoteDB(courseId);\n const config = await remoteDB.get<CourseConfig>('CourseConfig');\n return config.localSync?.enabled === true;\n } catch (e) {\n logger.warn(\n `[CourseSyncService] Could not read CourseConfig for ${courseId}, ` +\n `assuming local sync disabled: ${e}`\n );\n return false;\n }\n }\n\n /**\n * One-shot replication from remote to local.\n */\n private replicate(\n source: PouchDB.Database,\n target: PouchDB.Database\n ): Promise<PouchDB.Replication.ReplicationResultComplete<object>> {\n return new Promise((resolve, reject) => {\n void pouch.replicate(source, target, {\n // One-shot, not live. Local is a read-only snapshot.\n batch_size: this.replicationOptions.batchSize,\n batches_limit: this.replicationOptions.batchesLimit,\n })\n .on('complete', (info) => {\n resolve(info);\n })\n .on('error', (err) => {\n reject(err);\n });\n });\n }\n\n /**\n * Pre-warm PouchDB view indices by running a minimal query against each\n * design doc. This forces PouchDB to build the MapReduce index now\n * (during a loading phase) rather than on first pipeline query.\n */\n private async warmViewIndices(localDB: PouchDB.Database): Promise<void> {\n const viewsToWarm = ['elo', 'getTags'];\n\n for (const viewName of viewsToWarm) {\n try {\n await localDB.query(viewName, { limit: 1 });\n logger.debug(\n `[CourseSyncService] Warmed view index: ${viewName}`\n );\n } catch (e) {\n // View might not exist in this course DB — that's OK.\n // Not all courses have all design docs.\n logger.debug(\n `[CourseSyncService] Could not warm view ${viewName}: ${e}`\n );\n }\n }\n }\n\n /**\n * Check whether the local replica's `db-epoch` doc matches the remote.\n *\n * The seed script (and optionally upload-cards) writes a `db-epoch`\n * document with a numeric timestamp. If the remote epoch differs from\n * the local copy, the remote DB was recreated (e.g., `yarn db:seed`)\n * and the local PouchDB is stale.\n *\n * Returns `true` if stale (epoch mismatch or remote has epoch but local\n * doesn't). Returns `false` (not stale) if epochs match, or if the\n * remote doesn't have an epoch doc at all (backwards compat).\n */\n private async isLocalEpochStale(\n courseId: string,\n localDB: PouchDB.Database\n ): Promise<boolean> {\n try {\n const remoteDB = this.getRemoteDB(courseId);\n const remoteEpoch = await remoteDB.get<{ epoch: number }>('db-epoch');\n\n let localEpoch: { epoch: number } | null = null;\n try {\n localEpoch = await localDB.get<{ epoch: number }>('db-epoch');\n } catch {\n // No epoch doc locally: a DB never written to (this device's first\n // sync) has nothing to be stale; anything else (e.g. an interrupted\n // earlier sync) is.\n const info = await localDB.info();\n return info.doc_count > 0 || !!info.update_seq;\n }\n\n return remoteEpoch.epoch !== localEpoch.epoch;\n } catch {\n // Remote doesn't have db-epoch — no epoch tracking, not stale\n return false;\n }\n }\n\n /**\n * Get a remote PouchDB handle for a course.\n */\n private getRemoteDB(courseId: string): PouchDB.Database {\n return getCourseDB(courseId);\n }\n\n /**\n * Local DB naming convention.\n */\n private localDBName(courseId: string): string {\n return `coursedb-local-${courseId}`;\n }\n}"],"mappings":";;;;;;;;;;AAyDA,MAAM,iBAAiB;AA4DvB,MAA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