@vue-skuilder/db 0.2.34 → 0.2.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (262) hide show
  1. package/CLAUDE.md +15 -4
  2. package/build.entries.mjs +12 -0
  3. package/dist/_virtual/_rolldown/runtime.mjs +8 -0
  4. package/dist/{contentSource-CTQ4kWhR.d.cts → contentSource-D_E7JaxR.d.ts} +2 -2
  5. package/dist/core/UserDBDebugger.mjs +285 -0
  6. package/dist/core/UserDBDebugger.mjs.map +1 -0
  7. package/dist/core/bulkImport/cardProcessor.mjs +106 -0
  8. package/dist/core/bulkImport/cardProcessor.mjs.map +1 -0
  9. package/dist/core/{index.js → index.cjs} +6438 -7784
  10. package/dist/core/index.cjs.map +1 -0
  11. package/dist/core/index.d.ts +5 -5
  12. package/dist/core/index.mjs +20 -11368
  13. package/dist/core/interfaces/contentSource.mjs +20 -0
  14. package/dist/core/interfaces/contentSource.mjs.map +1 -0
  15. package/dist/core/navigators/Pipeline.mjs +723 -0
  16. package/dist/core/navigators/Pipeline.mjs.map +1 -0
  17. package/dist/core/navigators/PipelineAssembler.mjs +86 -0
  18. package/dist/core/navigators/PipelineAssembler.mjs.map +1 -0
  19. package/dist/core/navigators/PipelineDebugger.mjs +771 -0
  20. package/dist/core/navigators/PipelineDebugger.mjs.map +1 -0
  21. package/dist/core/navigators/SrsDebugger.mjs +34 -0
  22. package/dist/core/navigators/SrsDebugger.mjs.map +1 -0
  23. package/dist/core/navigators/StrategyPressureDebugger.mjs +19 -0
  24. package/dist/core/navigators/StrategyPressureDebugger.mjs.map +1 -0
  25. package/dist/core/navigators/defaults.mjs +96 -0
  26. package/dist/core/navigators/defaults.mjs.map +1 -0
  27. package/dist/core/navigators/diversityRerank.mjs +85 -0
  28. package/dist/core/navigators/diversityRerank.mjs.map +1 -0
  29. package/dist/core/navigators/filters/WeightedFilter.mjs +81 -0
  30. package/dist/core/navigators/filters/WeightedFilter.mjs.map +1 -0
  31. package/dist/core/navigators/filters/eloDistance.mjs +244 -0
  32. package/dist/core/navigators/filters/eloDistance.mjs.map +1 -0
  33. package/dist/core/navigators/filters/hierarchyDefinition.mjs +235 -0
  34. package/dist/core/navigators/filters/hierarchyDefinition.mjs.map +1 -0
  35. package/dist/core/navigators/filters/interferenceMitigator.mjs +201 -0
  36. package/dist/core/navigators/filters/interferenceMitigator.mjs.map +1 -0
  37. package/dist/core/navigators/filters/relativePriority.mjs +135 -0
  38. package/dist/core/navigators/filters/relativePriority.mjs.map +1 -0
  39. package/dist/core/navigators/filters/userTagPreference.mjs +101 -0
  40. package/dist/core/navigators/filters/userTagPreference.mjs.map +1 -0
  41. package/dist/core/navigators/generators/CompositeGenerator.mjs +203 -0
  42. package/dist/core/navigators/generators/CompositeGenerator.mjs.map +1 -0
  43. package/dist/core/navigators/generators/elo.mjs +77 -0
  44. package/dist/core/navigators/generators/elo.mjs.map +1 -0
  45. package/dist/core/navigators/generators/prescribed.mjs +676 -0
  46. package/dist/core/navigators/generators/prescribed.mjs.map +1 -0
  47. package/dist/core/navigators/generators/srs.mjs +158 -0
  48. package/dist/core/navigators/generators/srs.mjs.map +1 -0
  49. package/dist/core/navigators/index.mjs +345 -0
  50. package/dist/core/navigators/index.mjs.map +1 -0
  51. package/dist/core/navigators/pipelinePlan.mjs +109 -0
  52. package/dist/core/navigators/pipelinePlan.mjs.map +1 -0
  53. package/dist/core/navigators/regulators.mjs +128 -0
  54. package/dist/core/navigators/regulators.mjs.map +1 -0
  55. package/dist/core/orchestration/gradient.mjs +101 -0
  56. package/dist/core/orchestration/gradient.mjs.map +1 -0
  57. package/dist/core/orchestration/index.mjs +115 -0
  58. package/dist/core/orchestration/index.mjs.map +1 -0
  59. package/dist/core/orchestration/learning.mjs +140 -0
  60. package/dist/core/orchestration/learning.mjs.map +1 -0
  61. package/dist/core/orchestration/recording.mjs +64 -0
  62. package/dist/core/orchestration/recording.mjs.map +1 -0
  63. package/dist/core/orchestration/signal.mjs +40 -0
  64. package/dist/core/orchestration/signal.mjs.map +1 -0
  65. package/dist/core/types/contentNavigationStrategy.mjs +10 -0
  66. package/dist/core/types/contentNavigationStrategy.mjs.map +1 -0
  67. package/dist/core/types/hydration.mjs +13 -0
  68. package/dist/core/types/hydration.mjs.map +1 -0
  69. package/dist/core/types/strategyState.mjs +16 -0
  70. package/dist/core/types/strategyState.mjs.map +1 -0
  71. package/dist/core/types/studySession.mjs +14 -0
  72. package/dist/core/types/studySession.mjs.map +1 -0
  73. package/dist/core/types/types-legacy.mjs +44 -0
  74. package/dist/core/types/types-legacy.mjs.map +1 -0
  75. package/dist/core/util/index.mjs +31 -0
  76. package/dist/core/util/index.mjs.map +1 -0
  77. package/dist/core/versionStamps.mjs +46 -0
  78. package/dist/core/versionStamps.mjs.map +1 -0
  79. package/dist/courseConfigRegistration.mjs +306 -0
  80. package/dist/courseConfigRegistration.mjs.map +1 -0
  81. package/dist/{dataLayerProvider-rlLE2Mf-.d.ts → dataLayerProvider-BDshhSp_.d.ts} +1 -1
  82. package/dist/diagnostics/dataset.mjs +118 -0
  83. package/dist/diagnostics/dataset.mjs.map +1 -0
  84. package/dist/diagnostics/derive.mjs +318 -0
  85. package/dist/diagnostics/derive.mjs.map +1 -0
  86. package/dist/diagnostics/{index.js → index.cjs} +130 -1
  87. package/dist/diagnostics/index.cjs.map +1 -0
  88. package/dist/diagnostics/index.d.ts +108 -5
  89. package/dist/diagnostics/index.mjs +7 -914
  90. package/dist/diagnostics/loader.mjs +151 -0
  91. package/dist/diagnostics/loader.mjs.map +1 -0
  92. package/dist/diagnostics/pipeline.mjs +161 -0
  93. package/dist/diagnostics/pipeline.mjs.map +1 -0
  94. package/dist/diagnostics/tagElo.mjs +177 -0
  95. package/dist/diagnostics/tagElo.mjs.map +1 -0
  96. package/dist/diagnostics/text.mjs +174 -0
  97. package/dist/diagnostics/text.mjs.map +1 -0
  98. package/dist/factory.mjs +70 -0
  99. package/dist/factory.mjs.map +1 -0
  100. package/dist/impl/common/BaseUserDB.mjs +1103 -0
  101. package/dist/impl/common/BaseUserDB.mjs.map +1 -0
  102. package/dist/impl/common/userDBHelpers.mjs +49 -0
  103. package/dist/impl/common/userDBHelpers.mjs.map +1 -0
  104. package/dist/impl/common/userDBKeys.mjs +45 -0
  105. package/dist/impl/common/userDBKeys.mjs.map +1 -0
  106. package/dist/impl/couch/CouchDBSyncStrategy.mjs +272 -0
  107. package/dist/impl/couch/CouchDBSyncStrategy.mjs.map +1 -0
  108. package/dist/impl/couch/CourseSyncService.mjs +242 -0
  109. package/dist/impl/couch/CourseSyncService.mjs.map +1 -0
  110. package/dist/impl/couch/PouchDataLayerProvider.mjs +74 -0
  111. package/dist/impl/couch/PouchDataLayerProvider.mjs.map +1 -0
  112. package/dist/impl/couch/adminDB.mjs +61 -0
  113. package/dist/impl/couch/adminDB.mjs.map +1 -0
  114. package/dist/impl/couch/auth.mjs +33 -0
  115. package/dist/impl/couch/auth.mjs.map +1 -0
  116. package/dist/impl/couch/classroomDB.mjs +227 -0
  117. package/dist/impl/couch/classroomDB.mjs.map +1 -0
  118. package/dist/impl/couch/clientCache.mjs +15 -0
  119. package/dist/impl/couch/clientCache.mjs.map +1 -0
  120. package/dist/impl/couch/courseAPI.mjs +183 -0
  121. package/dist/impl/couch/courseAPI.mjs.map +1 -0
  122. package/dist/impl/couch/courseDB.mjs +729 -0
  123. package/dist/impl/couch/courseDB.mjs.map +1 -0
  124. package/dist/impl/couch/courseLookupDB.mjs +94 -0
  125. package/dist/impl/couch/courseLookupDB.mjs.map +1 -0
  126. package/dist/impl/couch/{index.js → index.cjs} +6911 -10367
  127. package/dist/impl/couch/index.cjs.map +1 -0
  128. package/dist/impl/couch/index.d.ts +12 -5
  129. package/dist/impl/couch/index.mjs +134 -12146
  130. package/dist/impl/couch/index.mjs.map +1 -1
  131. package/dist/impl/couch/pouchdb-setup.mjs +15 -0
  132. package/dist/impl/couch/pouchdb-setup.mjs.map +1 -0
  133. package/dist/impl/couch/updateQueue.mjs +101 -0
  134. package/dist/impl/couch/updateQueue.mjs.map +1 -0
  135. package/dist/impl/couch/user-course-relDB.mjs +55 -0
  136. package/dist/impl/couch/user-course-relDB.mjs.map +1 -0
  137. package/dist/impl/static/NoOpSyncStrategy.mjs +49 -0
  138. package/dist/impl/static/NoOpSyncStrategy.mjs.map +1 -0
  139. package/dist/impl/static/StaticDataLayerProvider.mjs +94 -0
  140. package/dist/impl/static/StaticDataLayerProvider.mjs.map +1 -0
  141. package/dist/impl/static/StaticDataUnpacker.mjs +311 -0
  142. package/dist/impl/static/StaticDataUnpacker.mjs.map +1 -0
  143. package/dist/impl/static/courseDB.mjs +368 -0
  144. package/dist/impl/static/courseDB.mjs.map +1 -0
  145. package/dist/impl/static/coursesDB.mjs +38 -0
  146. package/dist/impl/static/coursesDB.mjs.map +1 -0
  147. package/dist/impl/static/{index.js → index.cjs} +2461 -5992
  148. package/dist/impl/static/index.cjs.map +1 -0
  149. package/dist/impl/static/index.d.ts +4 -4
  150. package/dist/impl/static/index.mjs +6 -10741
  151. package/dist/{index-CVGehe_t.d.ts → index-BLDpFYG3.d.ts} +1 -1
  152. package/dist/{index.js → index.cjs} +14070 -14239
  153. package/dist/index.cjs.map +1 -0
  154. package/dist/index.d.ts +12 -23
  155. package/dist/index.mjs +38 -16937
  156. package/dist/pouch/{index.js → index.cjs} +5 -1
  157. package/dist/pouch/index.cjs.map +1 -0
  158. package/dist/pouch/index.mjs +2 -19
  159. package/dist/study/ItemQueue.mjs +95 -0
  160. package/dist/study/ItemQueue.mjs.map +1 -0
  161. package/dist/study/MixerDebugger.mjs +303 -0
  162. package/dist/study/MixerDebugger.mjs.map +1 -0
  163. package/dist/study/SessionController.mjs +1187 -0
  164. package/dist/study/SessionController.mjs.map +1 -0
  165. package/dist/study/SessionDebugger.mjs +271 -0
  166. package/dist/study/SessionDebugger.mjs.map +1 -0
  167. package/dist/study/SessionOverlay.mjs +407 -0
  168. package/dist/study/SessionOverlay.mjs.map +1 -0
  169. package/dist/study/SourceMixer.mjs +45 -0
  170. package/dist/study/SourceMixer.mjs.map +1 -0
  171. package/dist/study/SpacedRepetition.mjs +108 -0
  172. package/dist/study/SpacedRepetition.mjs.map +1 -0
  173. package/dist/study/TagFilteredContentSource.mjs +136 -0
  174. package/dist/study/TagFilteredContentSource.mjs.map +1 -0
  175. package/dist/study/services/CardHydrationService.mjs +172 -0
  176. package/dist/study/services/CardHydrationService.mjs.map +1 -0
  177. package/dist/study/services/EloService.mjs +217 -0
  178. package/dist/study/services/EloService.mjs.map +1 -0
  179. package/dist/study/services/ResponseProcessor.mjs +190 -0
  180. package/dist/study/services/ResponseProcessor.mjs.map +1 -0
  181. package/dist/study/services/SrsService.mjs +49 -0
  182. package/dist/study/services/SrsService.mjs.map +1 -0
  183. package/dist/study/services/tagRecent.mjs +65 -0
  184. package/dist/study/services/tagRecent.mjs.map +1 -0
  185. package/dist/{types-dXWfyz9B.d.ts → types-DChCz22D.d.ts} +1 -1
  186. package/dist/{types-legacy-BkOYOR6U.d.cts → types-legacy-fT5Y1Wuy.d.ts} +1 -1
  187. package/dist/userDBKeys-ne1g4Xuq.d.ts +16 -0
  188. package/dist/util/Loggable.mjs +14 -0
  189. package/dist/util/Loggable.mjs.map +1 -0
  190. package/dist/util/dataDirectory.mjs +47 -0
  191. package/dist/util/dataDirectory.mjs.map +1 -0
  192. package/dist/util/logger.mjs +86 -0
  193. package/dist/util/logger.mjs.map +1 -0
  194. package/dist/util/migrator/FileSystemAdapter.mjs +18 -0
  195. package/dist/util/migrator/FileSystemAdapter.mjs.map +1 -0
  196. package/dist/util/migrator/StaticToCouchDBMigrator.mjs +428 -0
  197. package/dist/util/migrator/StaticToCouchDBMigrator.mjs.map +1 -0
  198. package/dist/util/migrator/types.mjs +11 -0
  199. package/dist/util/migrator/types.mjs.map +1 -0
  200. package/dist/util/migrator/validation.mjs +334 -0
  201. package/dist/util/migrator/validation.mjs.map +1 -0
  202. package/dist/util/packer/CouchDBToStaticPacker.mjs +438 -0
  203. package/dist/util/packer/CouchDBToStaticPacker.mjs.map +1 -0
  204. package/dist/util/packer/{index.js → index.cjs} +73 -9
  205. package/dist/util/packer/index.cjs.map +1 -0
  206. package/dist/util/packer/index.d.ts +3 -3
  207. package/dist/util/packer/index.mjs +2 -537
  208. package/eslint.config.mjs +9 -1
  209. package/package.json +25 -13
  210. package/rolldown.config.mjs +44 -0
  211. package/src/core/UserDBDebugger.ts +47 -46
  212. package/src/core/navigators/Pipeline.ts +10 -10
  213. package/src/core/navigators/PipelineDebugger.ts +55 -55
  214. package/src/core/navigators/filters/eloDistance.ts +11 -1
  215. package/src/core/navigators/generators/elo.ts +5 -1
  216. package/src/core/navigators/index.ts +9 -3
  217. package/src/diagnostics/derive.ts +6 -0
  218. package/src/diagnostics/index.ts +1 -0
  219. package/src/diagnostics/tagElo.ts +257 -0
  220. package/src/factory.ts +10 -1
  221. package/src/impl/common/BaseUserDB.ts +1 -3
  222. package/src/impl/common/index.ts +2 -0
  223. package/src/impl/common/userDBHelpers.ts +4 -58
  224. package/src/impl/common/userDBKeys.ts +64 -0
  225. package/src/impl/couch/courseDB.ts +15 -3
  226. package/src/impl/couch/index.ts +2 -18
  227. package/src/impl/couch/pouchdb-setup.ts +8 -0
  228. package/src/index.ts +1 -1
  229. package/src/study/MixerDebugger.ts +46 -46
  230. package/src/study/SessionDebugger.ts +20 -20
  231. package/src/study/SessionOverlay.ts +4 -4
  232. package/src/util/logger.ts +112 -13
  233. package/tests/core/navigators/eloGenerator.test.ts +36 -0
  234. package/tsup.config.ts +24 -21
  235. package/dist/SyncStrategy-BXliog1m.d.cts +0 -116
  236. package/dist/classroomDB-DLTtLZct.d.cts +0 -86
  237. package/dist/contentSource-JmWYu8IK.d.ts +0 -2007
  238. package/dist/core/index.d.cts +0 -521
  239. package/dist/core/index.js.map +0 -1
  240. package/dist/core/index.mjs.map +0 -1
  241. package/dist/dataLayerProvider-DfI_KYAe.d.cts +0 -61
  242. package/dist/diagnostics/index.d.cts +0 -458
  243. package/dist/diagnostics/index.js.map +0 -1
  244. package/dist/diagnostics/index.mjs.map +0 -1
  245. package/dist/impl/couch/index.d.cts +0 -620
  246. package/dist/impl/couch/index.js.map +0 -1
  247. package/dist/impl/static/index.d.cts +0 -232
  248. package/dist/impl/static/index.js.map +0 -1
  249. package/dist/impl/static/index.mjs.map +0 -1
  250. package/dist/index-Ktg72jKb.d.cts +0 -137
  251. package/dist/index.d.cts +0 -1663
  252. package/dist/index.js.map +0 -1
  253. package/dist/index.mjs.map +0 -1
  254. package/dist/pouch/index.d.cts +0 -1
  255. package/dist/pouch/index.js.map +0 -1
  256. package/dist/pouch/index.mjs.map +0 -1
  257. package/dist/types-D0oQeJAi.d.cts +0 -58
  258. package/dist/types-legacy-BkOYOR6U.d.ts +0 -168
  259. package/dist/util/packer/index.d.cts +0 -5
  260. package/dist/util/packer/index.js.map +0 -1
  261. package/dist/util/packer/index.mjs.map +0 -1
  262. package/src/study/getCardDataShape.ts +0 -34
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BaseUserDB.mjs","names":[],"sources":["../../../src/impl/common/BaseUserDB.ts"],"sourcesContent":["import {\n DocType,\n DocTypePrefixes,\n StrategyStateDoc,\n buildStrategyStateId,\n HYDRATION_MARKER_ID,\n type HydrationMarker,\n type UserHydrationStatus,\n} from '@db/core';\nimport { areQuestionRecords, getCardHistoryID } from '@db/core/util';\nimport { CourseElo, Status } from '@vue-skuilder/common';\nimport moment, { Moment } from 'moment';\nimport { GuestUsername } from '../../core/types/types-legacy';\nimport { logger } from '../../util/logger';\n\nimport {\n ClassroomRegistrationDoc,\n UserCourseSetting,\n UserDBInterface,\n UsrCrsDataInterface,\n} from '@db/core';\nimport {\n ActivityRecord,\n CourseRegistration,\n CourseRegistrationDoc,\n ScheduledCard,\n UserConfig,\n} from '@db/core/types/user';\nimport { DocumentUpdater, getLapses, getStreak } from '@db/study';\nimport { CardHistory, CardRecord } from '../../core/types/types-legacy';\nimport { UserOutcomeRecord } from '../../core/types/userOutcome';\nimport { StudySessionDoc } from '../../core/types/studySession';\nimport type { SyncStrategy } from './SyncStrategy';\nimport { filterAllDocsByPrefix, getStartAndEndKeys, REVIEW_TIME_FORMAT } from './userDBKeys';\nimport {\n getLocalUserDB,\n scheduleCardReviewLocal,\n removeScheduledCardReviewLocal,\n} from './userDBHelpers';\nimport { PouchError } from '../couch/types';\nimport type { AdoptSessionResult } from './types';\nimport UpdateQueue, { Update } from '../couch/updateQueue';\nimport { UsrCrsData } from '../couch/user-course-relDB';\nimport { getCredentialledCourseConfig } from '../couch/index';\n\nconst log = (s: any) => {\n logger.info(s);\n};\n\n// logger.log(`Connecting to remote: ${remoteStr}`);\n\ninterface DesignDoc {\n _id: string;\n views: {\n [viewName: string]: {\n map: string; // String representation of the map function\n };\n };\n}\n\n/**\n * Ceiling on the initial pull of a user's data before we give up and report\n * `failed`. Generous relative to the expected payload (a user database is a\n * config doc, registrations, strategy state, and per-card history), so hitting\n * it indicates a genuinely unusable connection rather than a large account.\n */\nconst HYDRATION_TIMEOUT_MS = 15_000;\n\n/**\n * Reject if `p` has not settled within `ms`.\n *\n * Note the underlying work is not cancelled by this — callers that need the\n * operation stopped must do so themselves.\n */\nfunction withTimeout<T>(p: Promise<T>, ms: number, label: string): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n return Promise.race([\n p,\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);\n }),\n ]).finally(() => {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n }) as Promise<T>;\n}\n\n/**\n * Base user database implementation that uses a pluggable sync strategy.\n * Handles local storage operations and delegates sync/remote operations to the strategy.\n */\nexport class BaseUser implements UserDBInterface, DocumentUpdater {\n private static _instance: BaseUser;\n private static _initialized: boolean = false;\n\n public static Dummy(syncStrategy: SyncStrategy): BaseUser {\n return new BaseUser('Me', syncStrategy);\n }\n\n static readonly DOC_IDS = {\n CONFIG: 'CONFIG',\n COURSE_REGISTRATIONS: 'CourseRegistrations',\n CLASSROOM_REGISTRATIONS: 'ClassroomRegistrations',\n };\n\n // private email: string;\n private _username: string;\n private syncStrategy: SyncStrategy;\n\n public getUsername(): string {\n return this._username;\n }\n\n public isLoggedIn(): boolean {\n return !this._username.startsWith(GuestUsername);\n }\n\n public remote(): PouchDB.Database {\n return this.remoteDB;\n }\n\n private localDB!: PouchDB.Database;\n private remoteDB!: PouchDB.Database;\n private writeDB!: PouchDB.Database; // Database to use for write operations (local-first approach)\n private updateQueue!: UpdateQueue;\n\n private _hydration: UserHydrationStatus = { state: 'not-required' };\n /** In-flight hydration, so concurrent callers can wait for a real answer. */\n private _hydrationPromise: Promise<void> | null = null;\n /**\n * Sequence the local mirror was filled to by a hydration that succeeded in\n * THIS init(), handed to startSync() so the live pull can skip history it\n * would otherwise re-walk. Undefined whenever there is no such guarantee —\n * hydration skipped, not required, or failed. Never persisted; see the\n * `since` note in CouchDBSyncStrategy.startSync().\n */\n private _hydratedSeq?: string | number;\n\n /**\n * How far the local mirror can be trusted, RIGHT NOW. See\n * {@link UserHydrationStatus}.\n *\n * This is a snapshot, and during login it can legitimately read\n * `hydrating` — prefer awaitHydration() anywhere a decision hangs on the\n * answer.\n */\n public hydrationStatus(): UserHydrationStatus {\n return { ...this._hydration };\n }\n\n /**\n * The hydration status once it has settled — never `hydrating`.\n *\n * Resolves immediately unless a pull is in flight. Exists for callers that\n * must decide something (a route guard, a first-run branch) and would\n * otherwise sample `hydrating` and guess. Since init() is awaited by both\n * app startup and login(), that only happens when something navigates\n * concurrently with a login still in progress — a window that stretches to\n * HYDRATION_TIMEOUT_MS on a slow connection.\n */\n public async awaitHydration(): Promise<UserHydrationStatus> {\n // hydrateLocalMirror() records failures rather than throwing, so this\n // cannot reject — but a stray rejection must not become the caller's\n // problem when a status is available either way.\n try {\n await this._hydrationPromise;\n } catch {\n // fall through to the recorded status\n }\n return this.hydrationStatus();\n }\n\n /**\n * Whether a missing document may be treated as genuinely absent, allowing\n * callers to create it with defaults.\n *\n * False only when hydration failed or is still running: a 404 then may just\n * mean \"not pulled down yet\", and materializing a default would both lie to\n * the user and, once live sync starts, push a rev-1 document that loses to\n * the real one — silently discarding it.\n */\n private canMaterializeDefaults(): boolean {\n return this._hydration.state !== 'failed' && this._hydration.state !== 'hydrating';\n }\n\n public async createAccount(\n username: string,\n password: string\n ): Promise<{\n status: Status;\n error: string;\n }> {\n if (!this.syncStrategy.canCreateAccount()) {\n throw new Error('Account creation not supported by current sync strategy');\n }\n\n if (!this._username.startsWith(GuestUsername)) {\n throw new Error(\n `Cannot create a new account while logged in:\nCurrently logged-in as ${this._username}.`\n );\n }\n\n const result = await this.syncStrategy.createAccount!(username, password);\n\n // If account creation was successful, update the username and reinitialize\n if (result.status === Status.ok) {\n log(`Account created successfully, updating username to ${username}`);\n this._username = username;\n try {\n localStorage.removeItem('sk-guest-uuid');\n } catch (e) {\n logger.warn('localStorage not available (Node.js environment):', e);\n }\n await this.init();\n }\n\n return {\n status: result.status,\n error: result.error || '',\n };\n }\n public async login(username: string, password: string) {\n if (!this.syncStrategy.canAuthenticate()) {\n throw new Error('Authentication not supported by current sync strategy');\n }\n\n if (!this._username.startsWith(GuestUsername) && this._username != username) {\n if (this._username != username) {\n throw new Error(`Cannot change accounts while logged in.\n Log out of account ${this.getUsername()} before logging in as ${username}.`);\n }\n logger.warn(`User ${this._username} is already logged in, but executing login again.`);\n }\n\n const loginResult = await this.syncStrategy.authenticate!(username, password);\n if (loginResult.ok) {\n log(`Logged in as ${username}`);\n this._username = username;\n try {\n localStorage.removeItem('sk-guest-uuid');\n } catch (e) {\n logger.warn('localStorage not available (Node.js environment):', e);\n }\n await this.init();\n }\n return loginResult;\n }\n\n /**\n * Adopt a remote session that was established outside this client — e.g. a\n * backend verified a third-party sign-in (Google) and set the session cookie\n * on its response. Afterwards the user is logged in exactly as after\n * login(): username switched, guest pointer cleared, init() re-run.\n *\n * @param opts.migrateGuestData Carry the current guest account's local data\n * into the adopted account. Pass true for a freshly created account (as\n * createAccount() does), false for an existing one (as login() does).\n */\n public async adoptSession(opts: { migrateGuestData: boolean }): Promise<AdoptSessionResult> {\n if (!this.syncStrategy.canAuthenticate() || !this.syncStrategy.adoptSession) {\n throw new Error('Session adoption not supported by current sync strategy');\n }\n\n // Captured from memory, not the remote: the remote session already\n // belongs to the adopted user.\n const guestUsername = this._username.startsWith(GuestUsername) ? this._username : undefined;\n if (!guestUsername) {\n throw new Error(`Cannot adopt a session while logged in.\n Log out of account ${this.getUsername()} first.`);\n }\n\n const result = await this.syncStrategy.adoptSession(\n opts.migrateGuestData ? guestUsername : undefined\n );\n if (result.ok && result.username) {\n log(`Adopted session for ${result.username}`);\n this._username = result.username;\n try {\n localStorage.removeItem('sk-guest-uuid');\n } catch (e) {\n logger.warn('localStorage not available (Node.js environment):', e);\n }\n await this.init();\n }\n return result;\n }\n\n public async resetUserData(): Promise<{ status: Status; error?: string }> {\n // Only allow reset for local-only sync strategies\n if (this.syncStrategy.canAuthenticate()) {\n return {\n status: Status.error,\n error:\n 'Reset user data is only available for local-only mode. Use logout instead for remote sync.',\n };\n }\n\n try {\n const localDB = getLocalUserDB(this._username);\n\n // Get all documents to identify user data to clear\n const allDocs = await localDB.allDocs({ include_docs: false });\n\n // Identify documents to delete (preserve authentication and user identity)\n const docsToDelete = allDocs.rows\n .filter((row) => {\n const id = row.id;\n // Delete user progress data but preserve authentication and user identity\n return (\n id.startsWith(DocTypePrefixes[DocType.CARDRECORD]) || // Card interaction history\n id.startsWith(DocTypePrefixes[DocType.SCHEDULED_CARD]) || // Scheduled reviews\n id.startsWith(DocTypePrefixes[DocType.STRATEGY_STATE]) || // Strategy state (user prefs, progression)\n id.startsWith(DocTypePrefixes[DocType.USER_OUTCOME]) || // Evolutionary orchestration outcomes\n id.startsWith(DocTypePrefixes[DocType.STRATEGY_LEARNING_STATE]) || // Strategy learning state\n id === BaseUser.DOC_IDS.COURSE_REGISTRATIONS || // Course registrations\n id === BaseUser.DOC_IDS.CLASSROOM_REGISTRATIONS || // Classroom registrations\n id === BaseUser.DOC_IDS.CONFIG // User config\n );\n })\n .map((row) => ({ _id: row.id, _rev: row.value.rev, _deleted: true }));\n\n if (docsToDelete.length > 0) {\n await localDB.bulkDocs(docsToDelete);\n }\n\n // Reinitialize to create fresh default documents\n await this.init();\n\n return { status: Status.ok };\n } catch (error) {\n logger.error('Failed to reset user data:', error);\n return {\n status: Status.error,\n error: error instanceof Error ? error.message : 'Unknown error during reset',\n };\n }\n }\n\n public async logout() {\n if (!this.syncStrategy.canAuthenticate()) {\n // For strategies that don't support authentication, just switch to guest\n this._username = await this.syncStrategy.getCurrentUsername();\n await this.init();\n return { ok: true };\n }\n\n const ret = await this.syncStrategy.logout!();\n\n // Mint a FRESH guest identity on logout rather than re-adopting whatever\n // sk-guest-uuid happens to survive in localStorage. A stale UUID can point\n // at an already-consumed guest DB (one previously migrated into a real\n // account); re-adopting it would resurface that account's progress and, on\n // the next signup, migrate it into the new account. Clearing the pointer\n // forces accomodateGuest() to generate a new UUID + empty guest DB.\n try {\n localStorage.removeItem('sk-guest-uuid');\n } catch (e) {\n logger.warn('localStorage not available (Node.js environment):', e);\n }\n\n // return to 'guest' mode\n this._username = await this.syncStrategy.getCurrentUsername();\n await this.init();\n\n return ret;\n }\n\n public async get<T>(id: string): Promise<T & PouchDB.Core.RevisionIdMeta> {\n return this.localDB.get<T>(id);\n }\n\n public update<T extends PouchDB.Core.Document<object>>(id: string, update: Update<T>) {\n return this.updateQueue.update(id, update);\n }\n\n public async getCourseRegistrationsDoc(): Promise<\n CourseRegistrationDoc & PouchDB.Core.IdMeta & PouchDB.Core.GetMeta\n > {\n logger.debug(`Fetching courseRegistrations for ${this.getUsername()}`);\n\n let ret;\n\n try {\n const regDoc = await this.localDB.get<CourseRegistrationDoc>(\n BaseUser.DOC_IDS.COURSE_REGISTRATIONS\n );\n return regDoc;\n } catch (e) {\n const err = e as PouchError;\n if (err.status === 404) {\n if (!this.canMaterializeDefaults()) {\n throw new Error(\n `Cannot read course registrations for ${this._username}: the local mirror is ` +\n `unavailable (hydration state '${this._hydration.state}'). Refusing to create an ` +\n `empty registration doc — that would report an existing user as unregistered, and ` +\n `then lose to their real document once sync resumes.`\n );\n }\n await this.localDB.put<CourseRegistrationDoc>({\n _id: BaseUser.DOC_IDS.COURSE_REGISTRATIONS,\n courses: [],\n studyWeight: {},\n });\n ret = await this.getCourseRegistrationsDoc();\n } else {\n throw new Error(\n `Unexpected error ${JSON.stringify(e)} in getOrCreateCourseRegistrationDoc...`\n );\n }\n }\n\n return ret;\n }\n\n public async getActiveCourses() {\n const reg = await this.getCourseRegistrationsDoc();\n return reg.courses.filter((c) => {\n return c.status === undefined || c.status === 'active';\n });\n }\n\n /**\n * Returns a promise of the card IDs that the user has\n * a scheduled review for.\n *\n */\n public async getActiveCards() {\n const keys = getStartAndEndKeys(DocTypePrefixes[DocType.SCHEDULED_CARD]);\n\n const reviews = await this.remoteDB.allDocs<ScheduledCard>({\n startkey: keys.startkey,\n endkey: keys.endkey,\n include_docs: true,\n });\n\n return reviews.rows.map((r) => {\n return {\n courseID: r.doc!.courseId,\n cardID: r.doc!.cardId,\n };\n });\n }\n\n public async getActivityRecords(): Promise<ActivityRecord[]> {\n try {\n const hist = await this.getHistory();\n\n const allRecords: ActivityRecord[] = [];\n if (!Array.isArray(hist)) {\n logger.error('getHistory did not return an array:', hist);\n return allRecords;\n }\n\n // Sample the first few records to understand structure\n let sampleCount = 0;\n\n for (let i = 0; i < hist.length; i++) {\n try {\n if (hist[i] && Array.isArray(hist[i]!.records)) {\n hist[i]!.records.forEach((record: CardRecord) => {\n try {\n // Skip this record if timeStamp is missing\n if (!record.timeStamp) {\n return;\n }\n\n let timeStamp;\n\n // Handle different timestamp formats\n if (typeof record.timeStamp === 'object') {\n // It's likely a Moment object\n if (typeof record.timeStamp.toDate === 'function') {\n // It's definitely a Moment object\n timeStamp = record.timeStamp.toISOString();\n } else if (record.timeStamp instanceof Date) {\n // It's a Date object\n timeStamp = record.timeStamp.toISOString();\n } else {\n // Log a sample of unknown object types, but don't flood logger\n if (sampleCount < 3) {\n logger.warn('Unknown timestamp object type:', record.timeStamp);\n sampleCount++;\n }\n return;\n }\n } else if (typeof record.timeStamp === 'string') {\n // It's already a string, but make sure it's a valid date\n const date = new Date(record.timeStamp);\n if (isNaN(date.getTime())) {\n return; // Invalid date string\n }\n timeStamp = record.timeStamp;\n } else if (typeof record.timeStamp === 'number') {\n // Assume it's a Unix timestamp (milliseconds since epoch)\n timeStamp = new Date(record.timeStamp).toISOString();\n } else {\n // Unknown type, skip\n return;\n }\n\n allRecords.push({\n timeStamp,\n courseID: record.courseID || 'unknown',\n cardID: record.cardID || 'unknown',\n timeSpent: record.timeSpent || 0,\n type: 'card_view',\n });\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (err) {\n // Silently skip problematic records to avoid flooding logs\n }\n });\n }\n } catch (err) {\n logger.error('Error processing history item:', err);\n }\n }\n\n logger.debug(`Found ${allRecords.length} activity records`);\n return allRecords;\n } catch (err) {\n logger.error('Error in getActivityRecords:', err);\n return [];\n }\n }\n\n private async getReviewstoDate(targetDate: Moment, course_id?: string) {\n const keys = getStartAndEndKeys(DocTypePrefixes[DocType.SCHEDULED_CARD]);\n\n const reviews = await this.remoteDB.allDocs<ScheduledCard>({\n startkey: keys.startkey,\n endkey: keys.endkey,\n include_docs: true,\n });\n\n log(\n `Fetching ${this._username}'s scheduled reviews${\n course_id ? ` for course ${course_id}` : ''\n }.`\n );\n return reviews.rows\n .filter((r) => {\n if (r.id.startsWith(DocTypePrefixes[DocType.SCHEDULED_CARD])) {\n const date = moment.utc(\n r.id.substr(DocTypePrefixes[DocType.SCHEDULED_CARD].length),\n REVIEW_TIME_FORMAT\n );\n if (targetDate.isAfter(date)) {\n if (course_id === undefined || r.doc!.courseId === course_id) {\n return true;\n }\n }\n }\n })\n .map((r) => r.doc!);\n }\n\n public async getReviewsForcast(daysCount: number, course_id?: string) {\n const time = moment.utc().add(daysCount, 'days');\n return this.getReviewstoDate(time, course_id);\n }\n\n public async getPendingReviews(course_id?: string) {\n const now = moment.utc();\n return this.getReviewstoDate(now, course_id);\n }\n\n public async getScheduledReviewCount(course_id: string): Promise<number> {\n return (await this.getPendingReviews(course_id)).length;\n }\n\n public async getRegisteredCourses() {\n const regDoc = await this.getCourseRegistrationsDoc();\n return regDoc.courses.filter((c) => {\n return !c.status || c.status === 'active' || c.status === 'maintenance-mode';\n });\n }\n\n public async getCourseRegDoc(courseID: string) {\n const regDocs = await this.getCourseRegistrationsDoc();\n const ret = regDocs.courses.find((c) => c.courseID === courseID);\n if (ret) {\n return ret;\n } else {\n throw new Error(`Course registration not found for course ID: ${courseID}`);\n }\n }\n\n public async registerForCourse(course_id: string, previewMode: boolean = false) {\n return this.getCourseRegistrationsDoc()\n .then((doc: CourseRegistrationDoc) => {\n const status = previewMode ? 'preview' : 'active';\n logger.debug(`Registering for ${course_id} with status: ${status}`);\n\n const regItem: CourseRegistration = {\n status: status,\n courseID: course_id,\n user: true,\n admin: false,\n moderator: false,\n elo: {\n global: {\n score: 1000,\n count: 0,\n },\n tags: {},\n misc: {},\n },\n };\n\n if (\n doc.courses.filter((course) => {\n return course.courseID === regItem.courseID;\n }).length === 0\n ) {\n log(`It's a new course registration!`);\n doc.courses.push(regItem);\n doc.studyWeight[course_id] = 1;\n } else {\n doc.courses.forEach((c) => {\n log(`Found the previously registered course!`);\n if (c.courseID === course_id) {\n c.status = status;\n }\n });\n }\n\n return this.localDB.put<CourseRegistrationDoc>(doc);\n })\n .catch((e) => {\n log(`Registration failed because of: ${JSON.stringify(e)}`);\n throw e;\n });\n }\n public async dropCourse(course_id: string, dropStatus: CourseRegistration['status'] = 'dropped') {\n return this.getCourseRegistrationsDoc().then((doc) => {\n let index: number = -1;\n for (let i = 0; i < doc.courses.length; i++) {\n if (doc.courses[i].courseID === course_id) {\n index = i;\n }\n }\n\n if (index !== -1) {\n // remove from the relative-weighting of course study\n delete doc.studyWeight[course_id];\n // set drop status\n doc.courses[index].status = dropStatus;\n } else {\n throw new Error(\n `User ${this.getUsername()} is not currently registered for course ${course_id}`\n );\n }\n\n return this.localDB.put<CourseRegistrationDoc>(doc);\n });\n }\n\n public async getCourseInterface(courseId: string): Promise<UsrCrsDataInterface> {\n return new UsrCrsData(this, courseId);\n }\n\n public async getUserEditableCourses() {\n let courseIDs: string[] = [];\n\n const registeredCourses = await this.getCourseRegistrationsDoc();\n\n courseIDs = courseIDs.concat(\n registeredCourses.courses.map((course) => {\n return course.courseID;\n })\n );\n\n const cfgs = await Promise.all(\n courseIDs.map(async (id) => {\n return await getCredentialledCourseConfig(id);\n })\n );\n return cfgs;\n }\n\n public async getConfig(): Promise<UserConfig & PouchDB.Core.IdMeta & PouchDB.Core.GetMeta> {\n const defaultConfig: PouchDB.Core.Document<UserConfig> = {\n _id: BaseUser.DOC_IDS.CONFIG,\n darkMode: false,\n likesConfetti: false,\n sessionTimeLimit: 5,\n };\n\n try {\n const cfg = await this.localDB.get<UserConfig>(BaseUser.DOC_IDS.CONFIG);\n logger.debug('Raw config from DB:', cfg);\n\n return cfg;\n } catch (e) {\n const err = e as PouchError;\n if (err.name && err.name === 'not_found') {\n if (!this.canMaterializeDefaults()) {\n throw new Error(\n `Cannot read config for ${this._username}: the local mirror is unavailable ` +\n `(hydration state '${this._hydration.state}'). Refusing to write a default config ` +\n `over what may be an existing one.`\n );\n }\n await this.localDB.put<UserConfig>(defaultConfig);\n return this.getConfig();\n } else {\n logger.error(`Error setting user default config:`, e);\n throw new Error(`Error returning the user's configuration: ${JSON.stringify(e)}`);\n }\n }\n }\n\n public async setConfig(items: Partial<UserConfig>) {\n logger.debug(`Setting Config items ${JSON.stringify(items)}`);\n\n const c = await this.getConfig();\n const put = await this.localDB.put<UserConfig>({\n ...c,\n ...items,\n });\n\n if (put.ok) {\n logger.debug(`Config items set: ${JSON.stringify(items)}`);\n } else {\n logger.error(`Error setting config items: ${JSON.stringify(put)}`);\n }\n }\n\n /**\n *\n * This function should be called *only* by the pouchdb datalayer provider\n * auth store.\n *\n *\n * Anyone else seeking the current user should use the auth store's\n * exported `getCurrentUser` method.\n *\n */\n public static async instance(syncStrategy: SyncStrategy, username?: string): Promise<BaseUser> {\n if (username) {\n BaseUser._instance = new BaseUser(username, syncStrategy);\n await BaseUser._instance.init();\n return BaseUser._instance;\n } else if (BaseUser._instance && BaseUser._initialized) {\n // log(`USER.instance() returning user ${BaseUser._instance._username}`);\n return BaseUser._instance;\n } else if (BaseUser._instance) {\n return new Promise((resolve) => {\n (function waitForUser() {\n if (BaseUser._initialized) {\n return resolve(BaseUser._instance);\n } else {\n setTimeout(waitForUser, 50);\n }\n })();\n });\n } else {\n const guestUsername = await syncStrategy.getCurrentUsername();\n BaseUser._instance = new BaseUser(guestUsername, syncStrategy);\n await BaseUser._instance.init();\n return BaseUser._instance;\n }\n }\n\n private constructor(username: string, syncStrategy: SyncStrategy) {\n BaseUser._initialized = false;\n this._username = username;\n this.syncStrategy = syncStrategy;\n this.setDBandQ();\n }\n\n private setDBandQ() {\n this.localDB = getLocalUserDB(this._username);\n this.remoteDB = this.syncStrategy.setupRemoteDB(this._username);\n // writeDB follows local-first pattern: static mode writes to local, CouchDB writes to remote/local as appropriate\n this.writeDB = this.syncStrategy.getWriteDB\n ? this.syncStrategy.getWriteDB(this._username)\n : this.localDB;\n this.updateQueue = new UpdateQueue(this.localDB, this.writeDB);\n }\n\n private async init() {\n BaseUser._initialized = false;\n\n // Skip admin user\n if (this._username === 'admin') {\n BaseUser._initialized = true;\n return;\n }\n\n // Cancel replication left over from the previous identity BEFORE rebinding\n // the DB handles below. init() runs on every identity change (login,\n // logout, account creation, data reset), and each one points localDB /\n // remoteDB somewhere new — so without this, the prior sync keeps running\n // against handles nobody holds a reference to anymore.\n //\n // Logout is the case that bites: the guest branch of startSync() never\n // replaces the handle (it only ever assigns when a sync is actually\n // started), so the departing user's live sync survived indefinitely. Its\n // session cookie is gone by then, leaving it to 401-and-retry forever.\n this.syncStrategy.stopSync?.();\n\n this.setDBandQ();\n\n // Populate the local mirror BEFORE anything can read it, and before live\n // sync can push local state upward. See hydrateLocalMirror().\n //\n // Retained (not just awaited) so awaitHydration() can hand the same\n // promise to anything that asks mid-flight. Assigned synchronously with\n // respect to init()'s entry, so no caller can observe a previous\n // identity's promise here.\n this._hydrationPromise = this.hydrateLocalMirror();\n await this._hydrationPromise;\n\n // _hydratedSeq is set only by a hydration that just succeeded above, for\n // this identity — see hydrateLocalMirror(). Anything else leaves it\n // undefined and the live sync resumes from its own checkpoint.\n this.syncStrategy.startSync(this.localDB, this.remoteDB, this._hydratedSeq);\n this.applyDesignDocs().catch((error) => {\n log(`Error in applyDesignDocs background task: ${error}`);\n if (error && typeof error === 'object') {\n log(`Full error details in applyDesignDocs: ${JSON.stringify(error)}`);\n }\n });\n this.deduplicateReviews().catch((error) => {\n log(`Error in deduplicateReviews background task: ${error}`);\n if (error && typeof error === 'object') {\n log(`Full error details in background task: ${JSON.stringify(error)}`);\n }\n });\n BaseUser._initialized = true;\n }\n\n /**\n * Pull this account's documents into the local mirror, if that hasn't\n * happened on this device before.\n *\n * Runs between setDBandQ() and startSync() — after the handles exist, before\n * anything can observe an empty local DB or replicate one upward.\n *\n * Never throws: a failure is recorded as `failed` state and reported through\n * hydrationStatus(), because throwing here would abort init() and leave\n * BaseUser._initialized false forever (BaseUser.instance() polls it with no\n * ceiling). Callers decide what a failure means for them.\n */\n private async hydrateLocalMirror(): Promise<void> {\n // Clear first: init() reruns on every identity change, and a sequence from\n // the departing account would be meaningless against the incoming one's\n // database. Every path below either sets it or leaves it unset.\n this._hydratedSeq = undefined;\n\n // Guests and static-mode users have no remote — setupRemoteDB() hands back\n // the local database itself, so there is nothing to pull from.\n if (this.localDB.name === this.remoteDB.name || !this.syncStrategy.hydrate) {\n this._hydration = { state: 'not-required' };\n return;\n }\n\n if (await this.hasHydrationMarker()) {\n // A full pull already completed on this device, so local reads return\n // real data and live sync will close any gap. Blocking here would break\n // offline startup to re-fetch what we already have.\n this._hydration = { state: 'stale' };\n return;\n }\n\n this._hydration = { state: 'hydrating' };\n const start = Date.now();\n\n try {\n const { docsWritten, lastSeq } = await withTimeout(\n this.syncStrategy.hydrate(this.localDB, this.remoteDB),\n HYDRATION_TIMEOUT_MS,\n `Hydration of local mirror for ${this._username}`\n );\n this._hydratedSeq = lastSeq;\n await this.writeHydrationMarker();\n this._hydration = {\n state: 'hydrated',\n docsWritten,\n durationMs: Date.now() - start,\n };\n log(\n `Hydrated local mirror for ${this._username}: ` +\n `${docsWritten} docs in ${this._hydration.durationMs}ms`\n );\n } catch (e) {\n // Cancel the pull if it is merely slow rather than dead — otherwise it\n // races the live sync we are about to start over the same documents.\n this.syncStrategy.stopSync?.();\n this._hydration = {\n state: 'failed',\n durationMs: Date.now() - start,\n error: e instanceof Error ? e.message : String(e),\n };\n logger.error(`Failed to hydrate local mirror for ${this._username}:`, e);\n }\n }\n\n /**\n * Has a full pull completed on this device for the CURRENT account?\n *\n * The marker is a `_local/` document, which never replicates — so its\n * presence describes this device's mirror and cannot arrive from elsewhere.\n */\n private async hasHydrationMarker(): Promise<boolean> {\n try {\n const marker = await this.localDB.get<HydrationMarker>(HYDRATION_MARKER_ID);\n return marker.username === this._username;\n } catch {\n // Absent, or unreadable — either way, treat as never hydrated. The cost\n // of a false negative is one redundant pull.\n return false;\n }\n }\n\n private async writeHydrationMarker(): Promise<void> {\n try {\n let existingRev: string | undefined;\n try {\n existingRev = (await this.localDB.get<HydrationMarker>(HYDRATION_MARKER_ID))._rev;\n } catch {\n // First hydration on this device.\n }\n\n await this.localDB.put<HydrationMarker>({\n _id: HYDRATION_MARKER_ID,\n _rev: existingRev,\n username: this._username,\n hydratedAt: new Date().toISOString(),\n });\n } catch (e) {\n // Costs a redundant pull on next startup, not correctness.\n logger.warn(`Could not write hydration marker for ${this._username}: ${e}`);\n }\n }\n\n private static designDocs: DesignDoc[] = [\n {\n _id: '_design/reviewCards',\n views: {\n reviewCards: {\n map: `function (doc) {\n if (doc._id && doc._id.indexOf('card_review') === 0 && doc.courseId && doc.cardId) {\n emit(doc._id, doc.courseId + '-' + doc.cardId);\n }\n }`,\n },\n },\n },\n ];\n\n private async applyDesignDocs() {\n log(`Starting applyDesignDocs for user: ${this._username}`);\n log(`Remote DB name: ${this.remoteDB.name || 'unknown'}`);\n\n if (this._username === 'admin') {\n // Skip admin user\n log('Skipping design docs for admin user');\n return;\n }\n\n log(`Applying ${BaseUser.designDocs.length} design docs`);\n for (const doc of BaseUser.designDocs) {\n log(`Applying design doc: ${doc._id}`);\n try {\n // Try to get existing doc\n try {\n const existingDoc = await this.remoteDB.get(doc._id);\n // Update existing doc\n await this.remoteDB.put({\n ...doc,\n _rev: existingDoc._rev,\n });\n } catch (e: unknown) {\n // NB: PouchDB errors are plain objects ({error, reason, status, name,\n // message, ...}), not Error instances — `e instanceof Error` is false\n // for them. Check `.name` directly. The outer catch at line ~697\n // already does this correctly; mirror that style here so the\n // not_found → \"create new doc\" path actually fires for fresh user DBs.\n if ((e as { name?: string })?.name === 'not_found') {\n // Create new doc\n await this.remoteDB.put(doc);\n } else {\n throw e; // Re-throw unexpected errors\n }\n }\n } catch (error: unknown) {\n if ((error as any).name && (error as any).name === 'conflict') {\n logger.warn(`Design doc ${doc._id} update conflict - will retry`);\n // Wait a bit and try again\n await new Promise((resolve) => setTimeout(resolve, 1000));\n await this.applyDesignDoc(doc); // Recursive retry\n } else {\n logger.error(`Failed to apply design doc ${doc._id}:`, error);\n throw error;\n }\n }\n }\n }\n\n // Helper method for single doc update with retry\n private async applyDesignDoc(doc: DesignDoc, retries = 3): Promise<void> {\n try {\n const existingDoc = await this.remoteDB.get(doc._id);\n await this.remoteDB.put({\n ...doc,\n _rev: existingDoc._rev,\n });\n } catch (e: unknown) {\n // NB: PouchDB errors are plain objects, not Error instances — see\n // applyDesignDocs() above. Check `.name` directly so the conflict-retry\n // path actually fires.\n if ((e as { name?: string })?.name === 'conflict' && retries > 0) {\n await new Promise((resolve) => setTimeout(resolve, 1000));\n return this.applyDesignDoc(doc, retries - 1);\n }\n throw e;\n }\n }\n\n /**\n * Logs a record of the user's interaction with the card and returns the card's\n * up-to-date history.\n *\n * **Automatic Initialization:**\n * If this is the user's first interaction with the card (CardHistory doesn't exist),\n * this method automatically creates the CardHistory document with initial values\n * (lapses: 0, streak: 0, bestInterval: 0).\n *\n * **Error Handling:**\n * - Handles 404 errors by creating initial CardHistory document\n * - Re-throws all other errors from UpdateQueue\n *\n * // [ ] #db-refactor extract to a smaller scope - eg, UserStudySession\n *\n * @param record - The recent recorded interaction between user and card\n * @returns The updated state of the card's CardHistory data\n * @throws Error if document creation fails or non-404 database error occurs\n */\n\n public async putCardRecord<T extends CardRecord>(\n record: T\n ): Promise<CardHistory<CardRecord> & PouchDB.Core.RevisionIdMeta> {\n const cardHistoryID = getCardHistoryID(record.courseID, record.cardID);\n // stringify the current record to make it writable to couchdb\n record.timeStamp = moment.utc(record.timeStamp).toString() as unknown as Moment;\n\n try {\n const cardHistory = await this.update<CardHistory<T>>(\n cardHistoryID,\n function (h: CardHistory<T>) {\n h.records.push(record);\n h.bestInterval = h.bestInterval || 0;\n // Scheduling (SpacedRepetition.newQuestionInterval) re-derives\n // lapses/streak from `records` on every call, so these persisted\n // fields are informational — kept current so the stored doc reads\n // truthfully when inspected outside a session.\n if (areQuestionRecords(h)) {\n h.lapses = getLapses(h.records);\n h.streak = getStreak(h.records);\n } else {\n h.lapses = h.lapses || 0;\n h.streak = h.streak || 0;\n }\n return h;\n }\n );\n\n // Convert timestamps to moment objects\n cardHistory.records = cardHistory.records.map<T>((record) => {\n const ret: T = {\n ...(record as object),\n } as T;\n ret.timeStamp = moment.utc(record.timeStamp);\n return ret;\n });\n return cardHistory;\n } catch (e) {\n const reason = e as PouchError;\n if (reason.status === 404) {\n try {\n const initCardHistory: CardHistory<T> = {\n _id: cardHistoryID,\n cardID: record.cardID,\n courseID: record.courseID,\n records: [record],\n lapses: 0,\n streak: 0,\n bestInterval: 0,\n };\n const putResult = await this.writeDB.put<CardHistory<T>>(initCardHistory);\n return { ...initCardHistory, _rev: putResult.rev };\n } catch (creationError) {\n throw new Error(\n `Failed to create CardHistory for ${cardHistoryID}. Reason: ${creationError}`\n );\n }\n } else {\n throw new Error(`putCardRecord failed because of:\n name:${reason.name}\n error: ${reason.error}\n message: ${reason.message}`);\n }\n }\n }\n\n private async deduplicateReviews() {\n try {\n log('Starting deduplication of scheduled reviews...');\n log(`Remote DB name: ${this.remoteDB.name || 'unknown'}`);\n log(`Write DB name: ${this.writeDB.name || 'unknown'}`);\n /**\n * Maps the qualified-id of a scheduled review card to\n * the docId of the same scheduled review.\n *\n * EG: {\n * courseId-cardId: 'card_review_2021-06--17:12:165'\n * }\n */\n const reviewsMap: { [index: string]: string } = {};\n const duplicateDocIds: string[] = [];\n\n log(\n `Attempting to query remoteDB for reviewCards/reviewCards. Database: ${this.remoteDB.name || 'unknown'}`\n );\n const scheduledReviews = await this.remoteDB.query<{\n id: string;\n value: string;\n }>('reviewCards/reviewCards');\n\n log(`Found ${scheduledReviews.rows.length} scheduled reviews to process`);\n\n // First pass: identify duplicates\n scheduledReviews.rows.forEach((r) => {\n const qualifiedCardId = r.value; // courseId-cardId\n const docId = r.key; // card_review_2021-06--17:12:165\n\n if (reviewsMap[qualifiedCardId]) {\n // this card is scheduled more than once! mark the earlier one for deletion\n log(`Found duplicate scheduled review for card: ${qualifiedCardId}`);\n log(\n `Marking earlier review ${reviewsMap[qualifiedCardId]} for deletion, keeping ${docId}`\n );\n duplicateDocIds.push(reviewsMap[qualifiedCardId]);\n // replace with the later-dated scheduled review\n reviewsMap[qualifiedCardId] = docId;\n } else {\n // note that this card is scheduled for review\n reviewsMap[qualifiedCardId] = docId;\n }\n });\n\n // Second pass: remove duplicates\n if (duplicateDocIds.length > 0) {\n log(`Removing ${duplicateDocIds.length} duplicate reviews...`);\n const deletePromises = duplicateDocIds.map(async (docId) => {\n try {\n const doc = await this.remoteDB.get(docId);\n await this.writeDB.remove(doc);\n log(`Successfully removed duplicate review: ${docId}`);\n } catch (error) {\n log(`Failed to remove duplicate review ${docId}: ${error}`);\n }\n });\n\n await Promise.all(deletePromises);\n log(`Deduplication complete. Processed ${duplicateDocIds.length} duplicates`);\n } else {\n log('No duplicate reviews found');\n }\n } catch (error) {\n log(`Error during review deduplication: ${error}`);\n if (error && typeof error === 'object' && 'status' in error && error.status === 404) {\n log(\n `Database not found (404) during review deduplication. Database: ${this.remoteDB.name || 'unknown'}`\n );\n log(\n `This might indicate the user database doesn't exist or the reviewCards view isn't available`\n );\n }\n // Log full error details for debugging\n if (error && typeof error === 'object') {\n log(`Full error details: ${JSON.stringify(error)}`);\n }\n }\n }\n\n /**\n * Returns a promise of the card IDs that the user has\n * encountered in the past.\n *\n * @param course_id optional specification of individual course\n */\n async getSeenCards(course_id?: string) {\n // Doc IDs follow the pattern: cardH-{courseId}-{cardId}\n // (see getCardHistoryID in core/util)\n const basePrefix = DocTypePrefixes[DocType.CARDRECORD];\n let filterPrefix = basePrefix;\n if (course_id) {\n filterPrefix += `-${course_id}-`;\n }\n const docs = await filterAllDocsByPrefix(this.localDB, filterPrefix, {\n include_docs: false,\n });\n const ret: PouchDB.Core.DocumentId[] = [];\n docs.rows.forEach((row) => {\n if (row.id.startsWith(filterPrefix)) {\n // Strip the full prefix to return bare cardId\n ret.push(row.id.substr(filterPrefix.length));\n }\n });\n return ret;\n }\n\n /**\n *\n * @returns A promise of the cards that the user has seen in the past.\n */\n async getHistory() {\n const cards = await filterAllDocsByPrefix<CardHistory<CardRecord>>(\n this.remoteDB,\n DocTypePrefixes[DocType.CARDRECORD],\n {\n include_docs: true,\n attachments: false,\n }\n );\n return cards.rows.map((r) => r.doc);\n }\n\n async updateCourseSettings(course_id: string, settings: UserCourseSetting[]) {\n void this.getCourseRegistrationsDoc().then((doc) => {\n const crs = doc.courses.find((c) => c.courseID === course_id);\n if (crs) {\n if (crs.settings === null || crs.settings === undefined) {\n crs.settings = {};\n }\n settings.forEach((setting) => {\n crs!.settings![setting.key] = setting.value;\n });\n }\n\n return this.localDB.put(doc);\n });\n }\n async getCourseSettings(course_id: string) {\n const regDoc = await this.getCourseRegistrationsDoc();\n const crsDoc = regDoc.courses.find((c) => c.courseID === course_id);\n\n if (crsDoc) {\n return crsDoc.settings;\n } else {\n throw new Error(`getCourseSettings Failed:\n User is not registered for course ${course_id}`);\n }\n }\n\n private async getOrCreateClassroomRegistrationsDoc(): Promise<\n ClassroomRegistrationDoc & PouchDB.Core.IdMeta & PouchDB.Core.GetMeta\n > {\n let ret;\n\n try {\n ret = await this.remoteDB.get<ClassroomRegistrationDoc>(\n BaseUser.DOC_IDS.CLASSROOM_REGISTRATIONS\n );\n } catch (e) {\n const err = e as PouchError;\n\n if (err.status === 404) {\n // doc does not exist. Create it and then run this fcn again.\n await this.writeDB.put<ClassroomRegistrationDoc>({\n _id: BaseUser.DOC_IDS.CLASSROOM_REGISTRATIONS,\n registrations: [],\n });\n ret = await this.getOrCreateClassroomRegistrationsDoc();\n } else {\n // Properly serialize error information\n const errorDetails = {\n name: err.name,\n status: err.status,\n message: err.message,\n reason: err.reason,\n error: err.error,\n };\n\n logger.error(\n 'Database error in getOrCreateClassroomRegistrationsDoc (private method):',\n errorDetails\n );\n\n throw new Error(\n `Database error accessing classroom registrations: ${err.message || err.name || 'Unknown error'} (status: ${err.status})`\n );\n }\n }\n\n logger.debug(`Returning classroom registrations doc: ${JSON.stringify(ret)}`);\n return ret;\n }\n\n /**\n * Retrieves the list of active classroom IDs where the user is registered as a student.\n *\n * @returns Promise<string[]> - Array of classroom IDs, or empty array if classroom\n * registration document is unavailable due to database errors\n *\n * @description This method gracefully handles database connectivity issues by returning\n * an empty array when the classroom registrations document cannot be accessed.\n * This ensures that users can still access other application features even\n * when classroom functionality is temporarily unavailable.\n */\n public async getActiveClasses(): Promise<string[]> {\n try {\n return (await this.getOrCreateClassroomRegistrationsDoc()).registrations\n .filter((c) => c.registeredAs === 'student')\n .map((c) => c.classID);\n } catch (error) {\n logger.warn(\n 'Failed to load classroom registrations, continuing without classroom data:',\n error\n );\n // Return empty array so user can still access other features\n return [];\n }\n }\n\n public async scheduleCardReview(review: {\n user: string;\n course_id: string;\n card_id: PouchDB.Core.DocumentId;\n time: Moment;\n scheduledFor: ScheduledCard['scheduledFor'];\n schedulingAgentId: ScheduledCard['schedulingAgentId'];\n }) {\n return scheduleCardReviewLocal(this.writeDB, review);\n }\n public async removeScheduledCardReview(reviewId: string): Promise<void> {\n return removeScheduledCardReviewLocal(this.writeDB, reviewId);\n }\n\n public async registerForClassroom(\n _classId: string,\n _registerAs: 'student' | 'teacher' | 'aide' | 'admin'\n ): Promise<PouchDB.Core.Response> {\n return registerUserForClassroom(this._username, _classId, _registerAs);\n }\n\n public async dropFromClassroom(classId: string): Promise<PouchDB.Core.Response> {\n return dropUserFromClassroom(this._username, classId);\n }\n public async getUserClassrooms(): Promise<ClassroomRegistrationDoc> {\n return getUserClassrooms(this._username);\n }\n\n public async updateUserElo(courseId: string, elo: CourseElo): Promise<PouchDB.Core.Response> {\n return updateUserElo(this._username, courseId, elo);\n }\n\n public async getStrategyState<T>(courseId: string, strategyKey: string): Promise<T | null> {\n const docId = buildStrategyStateId(courseId, strategyKey);\n try {\n const doc = await this.localDB.get<StrategyStateDoc<T>>(docId);\n return doc.data;\n } catch (e) {\n const err = e as PouchError;\n if (err.status === 404) {\n // `null` here means \"this user has no such state\" — a first-run signal\n // consumers act on. When the mirror is untrusted we cannot honestly say\n // that, so fail instead of reporting an established user as new.\n if (!this.canMaterializeDefaults()) {\n throw new Error(\n `Cannot read strategy state '${strategyKey}' for ${this._username}: the local mirror ` +\n `is unavailable (hydration state '${this._hydration.state}').`\n );\n }\n return null;\n }\n throw e;\n }\n }\n\n public async putStrategyState<T>(courseId: string, strategyKey: string, data: T): Promise<void> {\n const docId = buildStrategyStateId(courseId, strategyKey);\n let existingRev: string | undefined;\n\n try {\n const existing = await this.localDB.get<StrategyStateDoc<T>>(docId);\n existingRev = existing._rev;\n } catch (e) {\n const err = e as PouchError;\n if (err.status !== 404) {\n throw e;\n }\n }\n\n const doc: StrategyStateDoc<T> = {\n _id: docId,\n _rev: existingRev,\n docType: DocType.STRATEGY_STATE,\n courseId,\n strategyKey,\n data,\n updatedAt: new Date().toISOString(),\n };\n\n await this.localDB.put(doc);\n }\n\n /**\n * Open and close write the same `_id`, so the 409 path is the expected\n * route for the second write, not an error case.\n */\n public async putStudySession(doc: StudySessionDoc): Promise<void> {\n try {\n await this.localDB.put(doc);\n } catch (err: any) {\n if (err.status === 409) {\n const existing = await this.localDB.get(doc._id);\n await this.localDB.put({ ...doc, _rev: existing._rev });\n } else {\n throw err;\n }\n }\n }\n\n public async getStudySessions(courseId?: string): Promise<StudySessionDoc[]> {\n const prefix = courseId\n ? `${DocTypePrefixes[DocType.STUDY_SESSION]}::${courseId}::`\n : `${DocTypePrefixes[DocType.STUDY_SESSION]}::`;\n const keys = getStartAndEndKeys(prefix);\n\n const res = await this.localDB.allDocs<StudySessionDoc>({\n startkey: keys.startkey,\n endkey: keys.endkey,\n include_docs: true,\n });\n\n return res.rows\n .map((r) => r.doc)\n .filter((d): d is StudySessionDoc & PouchDB.Core.RevisionIdMeta => !!d)\n .sort((a, b) => b.startTime.localeCompare(a.startTime));\n }\n\n public async putUserOutcome(record: UserOutcomeRecord): Promise<void> {\n try {\n await this.localDB.put(record);\n } catch (err: any) {\n if (err.status === 409) {\n // Overwrite if exists\n const existing = await this.localDB.get(record._id);\n (record as any)._rev = existing._rev;\n await this.localDB.put(record);\n } else {\n throw err;\n }\n }\n }\n\n public async deleteStrategyState(courseId: string, strategyKey: string): Promise<void> {\n const docId = buildStrategyStateId(courseId, strategyKey);\n try {\n const doc = await this.localDB.get(docId);\n await this.localDB.remove(doc);\n } catch (e) {\n const err = e as PouchError;\n if (err.status === 404) {\n return;\n }\n throw e;\n }\n }\n}\n\nexport function accomodateGuest(): {\n username: string;\n firstVisit: boolean;\n} {\n logger.log('[funnel] accomodateGuest() called');\n\n // Check if localStorage is available (browser environment)\n if (typeof localStorage === 'undefined') {\n logger.log(\n '[funnel] localStorage not available (Node.js environment), returning default guest'\n );\n return {\n username: GuestUsername + 'nodejs-test',\n firstVisit: true,\n };\n }\n\n const dbUUID = 'sk-guest-uuid';\n let firstVisit: boolean;\n\n const existingUUID = localStorage.getItem(dbUUID);\n logger.log('[funnel] Checking localStorage for key:', dbUUID);\n logger.log('[funnel] Existing UUID value:', existingUUID);\n logger.log('[funnel] existingUUID !== null:', existingUUID !== null);\n\n if (existingUUID !== null) {\n firstVisit = false;\n logger.log(`[funnel] Returning guest ${existingUUID} \"logging in\".`);\n } else {\n firstVisit = true;\n logger.log('[funnel] No existing UUID, generating new one...');\n const uuid = generateUUID();\n logger.log('[funnel] Generated UUID:', uuid);\n logger.log('[funnel] UUID length:', uuid.length);\n\n try {\n localStorage.setItem(dbUUID, uuid);\n logger.log('[funnel] Successfully stored UUID in localStorage');\n const verification = localStorage.getItem(dbUUID);\n logger.log('[funnel] Verification read from localStorage:', verification);\n } catch (e) {\n logger.error('[funnel] ERROR storing UUID:', e);\n }\n\n logger.log(`[funnel] Accommodating a new guest with account: ${uuid}`);\n }\n\n const finalUUID = localStorage.getItem(dbUUID);\n const finalUsername = GuestUsername + finalUUID;\n logger.log('[funnel] Final UUID from localStorage:', finalUUID);\n logger.log('[funnel] GuestUsername constant:', GuestUsername);\n logger.log('[funnel] Final username to return:', finalUsername);\n\n return {\n username: finalUsername,\n firstVisit: firstVisit,\n };\n\n // Use cryptographically secure UUID generation\n function generateUUID() {\n logger.log('[funnel] Inside generateUUID()');\n\n // Use crypto.randomUUID() if available (Node 14.17+ / modern browsers)\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n const uuid = crypto.randomUUID();\n logger.log('[funnel] Generated UUID using crypto.randomUUID():', uuid);\n return uuid;\n }\n\n // Fallback for older environments: use crypto.getRandomValues()\n if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n\n // Set version (4) and variant bits according to RFC 4122\n bytes[6] = (bytes[6] & 0x0f) | 0x40; // Version 4\n bytes[8] = (bytes[8] & 0x3f) | 0x80; // Variant 10\n\n const uuid = [\n Array.from(bytes.slice(0, 4))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join(''),\n Array.from(bytes.slice(4, 6))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join(''),\n Array.from(bytes.slice(6, 8))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join(''),\n Array.from(bytes.slice(8, 10))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join(''),\n Array.from(bytes.slice(10, 16))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join(''),\n ].join('-');\n\n logger.log('[funnel] Generated UUID using crypto.getRandomValues():', uuid);\n return uuid;\n }\n\n // Last resort fallback (should never happen in modern environments)\n logger.warn('[funnel] crypto API not available, using timestamp-based UUID (NOT SECURE)');\n let d = new Date().getTime();\n if (typeof performance !== 'undefined' && typeof performance.now === 'function') {\n d += performance.now();\n }\n const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (d + Math.random() * 16) % 16 | 0;\n d = Math.floor(d / 16);\n return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);\n });\n logger.log('[funnel] Generated UUID (fallback):', uuid);\n return uuid;\n }\n}\n\nconst userCoursesDoc = 'CourseRegistrations';\nconst userClassroomsDoc = 'ClassroomRegistrations';\n\nasync function getOrCreateClassroomRegistrationsDoc(\n user: string\n): Promise<ClassroomRegistrationDoc & PouchDB.Core.IdMeta & PouchDB.Core.GetMeta> {\n let ret;\n\n try {\n ret = await getLocalUserDB(user).get<ClassroomRegistrationDoc>(userClassroomsDoc);\n } catch (e) {\n const err = e as PouchError;\n\n if (err.status === 404) {\n // doc does not exist. Create it and then run this fcn again.\n await getLocalUserDB(user).put<ClassroomRegistrationDoc>({\n _id: userClassroomsDoc,\n registrations: [],\n });\n ret = await getOrCreateClassroomRegistrationsDoc(user);\n } else {\n // Properly serialize error information\n const errorDetails = {\n name: err.name,\n status: err.status,\n message: err.message,\n reason: err.reason,\n error: err.error,\n };\n\n logger.error(\n 'Database error in getOrCreateClassroomRegistrationsDoc (standalone function):',\n errorDetails\n );\n\n throw new Error(\n `Database error accessing classroom registrations: ${err.message || err.name || 'Unknown error'} (status: ${err.status})`\n );\n }\n }\n\n return ret;\n}\n\nasync function getOrCreateCourseRegistrationsDoc(\n user: string\n): Promise<CourseRegistrationDoc & PouchDB.Core.IdMeta & PouchDB.Core.GetMeta> {\n let ret;\n\n try {\n ret = await getLocalUserDB(user).get<CourseRegistrationDoc>(userCoursesDoc);\n } catch (e) {\n const err = e as PouchError;\n if (err.status === 404) {\n // doc does not exist. Create it and then run this fcn again.\n await getLocalUserDB(user).put<CourseRegistrationDoc>({\n _id: userCoursesDoc,\n courses: [],\n studyWeight: {},\n });\n ret = await getOrCreateCourseRegistrationsDoc(user);\n } else {\n throw new Error(\n `Unexpected error ${JSON.stringify(e)} in getOrCreateCourseRegistrationDoc...`\n );\n }\n }\n\n return ret;\n}\n\nexport async function updateUserElo(user: string, course_id: string, elo: CourseElo) {\n const regDoc = await getOrCreateCourseRegistrationsDoc(user);\n const course = regDoc.courses.find((c) => c.courseID === course_id)!;\n course.elo = elo;\n return getLocalUserDB(user).put(regDoc);\n}\n\nexport async function registerUserForClassroom(\n user: string,\n classID: string,\n registerAs: 'student' | 'teacher' | 'aide' | 'admin'\n) {\n log(`Registering user: ${user} in course: ${classID}`);\n return getOrCreateClassroomRegistrationsDoc(user).then((doc) => {\n const regItem = {\n classID: classID,\n registeredAs: registerAs,\n };\n\n if (\n doc.registrations.filter((reg) => {\n return reg.classID === regItem.classID && reg.registeredAs === regItem.registeredAs;\n }).length === 0\n ) {\n doc.registrations.push(regItem);\n } else {\n log(`User ${user} is already registered for class ${classID}`);\n }\n\n return getLocalUserDB(user).put(doc);\n });\n}\n\nexport async function dropUserFromClassroom(user: string, classID: string) {\n return getOrCreateClassroomRegistrationsDoc(user).then((doc) => {\n let index: number = -1;\n\n for (let i = 0; i < doc.registrations.length; i++) {\n if (doc.registrations[i].classID === classID) {\n index = i;\n }\n }\n\n if (index !== -1) {\n doc.registrations.splice(index, 1);\n }\n return getLocalUserDB(user).put(doc);\n });\n}\n\nexport async function getUserClassrooms(user: string) {\n return getOrCreateClassroomRegistrationsDoc(user);\n}\n"],"mappings":";;;;;;;;;;;;;;;AA6CA,MAAM,OAAO,MAAW;AACtB,QAAO,KAAK,EAAE;;;;;;;;AAoBhB,MAAM,uBAAuB;;;;;;;AAQ7B,SAAS,YAAe,GAAe,IAAY,OAA2B;CAC5E,IAAI;AAEJ,QAAO,QAAQ,KAAK,CAClB,GACA,IAAI,SAAgB,UAAU,WAAW;AACvC,UAAQ,iBAAiB,uBAAO,IAAI,MAAM,GAAG,MAAM,mBAAmB,GAAG,IAAI,CAAC,EAAE,GAAG;GACnF,CACH,CAAC,CAAC,cAAc;AACf,MAAI,UAAU,KAAA,EACZ,cAAa,MAAM;GAErB;;;;;;AAOJ,IAAa,WAAb,MAAa,SAAqD;CAChE,OAAe;CACf,OAAe,eAAwB;CAEvC,OAAc,MAAM,cAAsC;AACxD,SAAO,IAAI,SAAS,MAAM,aAAa;;CAGzC,OAAgB,UAAU;EACxB,QAAQ;EACR,sBAAsB;EACtB,yBAAyB;EAC1B;CAGD;CACA;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,iBAA+C;AAI1D,MAAI;AACF,SAAM,KAA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,49 @@
1
+ import "../../_virtual/_rolldown/runtime.mjs";
2
+ import { logger } from "../../util/logger.mjs";
3
+ import pouchdb_setup_default from "../couch/pouchdb-setup.mjs";
4
+ import { makeScheduledCardId } from "./userDBKeys.mjs";
5
+ import { getDbPath } from "../../util/dataDirectory.mjs";
6
+ import moment from "moment";
7
+ //#region src/impl/common/userDBHelpers.ts
8
+ const log = (s) => {
9
+ logger.info(s);
10
+ };
11
+ /**
12
+ * Get local user database with appropriate adapter for environment
13
+ */
14
+ function getLocalUserDB(username) {
15
+ const dbName = `userdb-${username}`;
16
+ if (typeof window === "undefined") return new pouchdb_setup_default(getDbPath(dbName), {});
17
+ else return new pouchdb_setup_default(dbName, {});
18
+ }
19
+ /**
20
+ * Schedule a card review (strategy-agnostic version)
21
+ */
22
+ function scheduleCardReviewLocal(userDB, review) {
23
+ const now = moment.utc();
24
+ logger.info(`Scheduling for review in: ${review.time.diff(now, "h") / 24} days`);
25
+ userDB.put({
26
+ _id: makeScheduledCardId(review.time),
27
+ cardId: review.card_id,
28
+ reviewTime: review.time.toISOString(),
29
+ courseId: review.course_id,
30
+ scheduledAt: now.toISOString(),
31
+ scheduledFor: review.scheduledFor,
32
+ schedulingAgentId: review.schedulingAgentId
33
+ });
34
+ }
35
+ /**
36
+ * Remove a scheduled card review (strategy-agnostic version)
37
+ */
38
+ async function removeScheduledCardReviewLocal(userDB, reviewDocID) {
39
+ const reviewDoc = await userDB.get(reviewDocID);
40
+ userDB.remove(reviewDoc).then((res) => {
41
+ if (res.ok) log(`Removed Review Doc: ${reviewDocID}`);
42
+ }).catch((err) => {
43
+ log(`Failed to remove Review Doc: ${reviewDocID},\n${JSON.stringify(err)}`);
44
+ });
45
+ }
46
+ //#endregion
47
+ export { getLocalUserDB, removeScheduledCardReviewLocal, scheduleCardReviewLocal };
48
+
49
+ //# sourceMappingURL=userDBHelpers.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"userDBHelpers.mjs","names":["pouch"],"sources":["../../../src/impl/common/userDBHelpers.ts"],"sourcesContent":["// packages/db/src/impl/common/userDBHelpers.ts\n\nimport moment from 'moment';\nimport { logger } from '../../util/logger';\nimport { ScheduledCard } from '@db/core/types/user';\nimport pouch from '../couch/pouchdb-setup';\nimport { getDbPath } from '../../util/dataDirectory';\nimport { makeScheduledCardId } from './userDBKeys';\n\n// PouchDB-backed helpers. The PouchDB-free ones (ids, key ranges) are in\n// userDBKeys.ts.\n\nconst log = (s: any) => {\n logger.info(s);\n};\n\nexport function updateGuestAccountExpirationDate(guestDB: PouchDB.Database<object>) {\n const currentTime = moment.utc();\n const expirationDate: string = currentTime.add(2, 'months').toISOString();\n const expiryDocID: string = 'GuestAccountExpirationDate';\n\n void guestDB\n .get(expiryDocID)\n .then((doc) => {\n return guestDB.put({\n _id: expiryDocID,\n _rev: doc._rev,\n date: expirationDate,\n });\n })\n .catch(() => {\n return guestDB.put({\n _id: expiryDocID,\n date: expirationDate,\n });\n });\n}\n\n/**\n * Get local user database with appropriate adapter for environment\n */\nexport function getLocalUserDB(username: string): PouchDB.Database {\n // // Choose adapter based on environment\n //\n // Not certain of this is required. Let's let pouch's auto detection\n // handle it until we specifically know we need to intervene.\n //\n // let adapter: string;\n // if (typeof window !== 'undefined') {\n // // Browser environment - use IndexedDB\n // adapter = 'idb';\n // } else {\n // // Node.js environment (tests) - use memory adapter\n // adapter = 'memory';\n // }\n\n const dbName = `userdb-${username}`;\n \n // Use proper data directory in Node.js, browser will use IndexedDB\n if (typeof window === 'undefined') {\n // Node.js environment - use filesystem with proper app data directory\n return new pouch(getDbPath(dbName), {});\n } else {\n // Browser environment - use default (IndexedDB)\n return new pouch(dbName, {});\n }\n}\n\n/**\n * Schedule a card review (strategy-agnostic version)\n */\nexport function scheduleCardReviewLocal(\n userDB: PouchDB.Database,\n review: {\n card_id: PouchDB.Core.DocumentId;\n time: moment.Moment;\n course_id: string;\n scheduledFor: ScheduledCard['scheduledFor'];\n schedulingAgentId: ScheduledCard['schedulingAgentId'];\n }\n) {\n const now = moment.utc();\n logger.info(`Scheduling for review in: ${review.time.diff(now, 'h') / 24} days`);\n void userDB.put<ScheduledCard>({\n _id: makeScheduledCardId(review.time),\n cardId: review.card_id,\n reviewTime: review.time.toISOString(),\n courseId: review.course_id,\n scheduledAt: now.toISOString(),\n scheduledFor: review.scheduledFor,\n schedulingAgentId: review.schedulingAgentId,\n });\n}\n\n/**\n * Remove a scheduled card review (strategy-agnostic version)\n */\nexport async function removeScheduledCardReviewLocal(\n userDB: PouchDB.Database,\n reviewDocID: string\n) {\n const reviewDoc = await userDB.get(reviewDocID);\n userDB\n .remove(reviewDoc)\n .then((res) => {\n if (res.ok) {\n log(`Removed Review Doc: ${reviewDocID}`);\n }\n })\n .catch((err) => {\n log(`Failed to remove Review Doc: ${reviewDocID},\\n${JSON.stringify(err)}`);\n });\n}\n"],"mappings":";;;;;;;AAYA,MAAM,OAAO,MAAW;AACtB,QAAO,KAAK,EAAE;;;;;AA4BhB,SAAgB,eAAe,UAAoC;CAejE,MAAM,SAAS,UAAU;AAGzB,KAAI,OAAO,WAAW,YAEpB,QAAO,IAAIA,sBAAM,UAAU,OAAO,EAAE,EAAE,CAAC;KAGvC,QAAO,IAAIA,sBAAM,QAAQ,EAAE,CAAC;;;;;AAOhC,SAAgB,wBACd,QACA,QAOA;CACA,MAAM,MAAM,OAAO,KAAK;AACxB,QAAO,KAAK,6BAA6B,OAAO,KAAK,KAAK,KAAK,IAAI,GAAG,GAAG,OAAO;AAC3E,QAAO,IAAmB;EAC7B,KAAK,oBAAoB,OAAO,KAAK;EACrC,QAAQ,OAAO;EACf,YAAY,OAAO,KAAK,aAAa;EACrC,UAAU,OAAO;EACjB,aAAa,IAAI,aAAa;EAC9B,cAAc,OAAO;EACrB,mBAAmB,OAAO;EAC3B,CAAC;;;;;AAMJ,eAAsB,+BACpB,QACA,aACA;CACA,MAAM,YAAY,MAAM,OAAO,IAAI,YAAY;AAC/C,QACG,OAAO,UAAU,CACjB,MAAM,QAAQ;AACb,MAAI,IAAI,GACN,KAAI,uBAAuB,cAAc;GAE3C,CACD,OAAO,QAAQ;AACd,MAAI,gCAAgC,YAAY,KAAK,KAAK,UAAU,IAAI,GAAG;GAC3E"}
@@ -0,0 +1,45 @@
1
+ import "../../_virtual/_rolldown/runtime.mjs";
2
+ import { DocType, DocTypePrefixes } from "../../core/types/types-legacy.mjs";
3
+ import moment from "moment";
4
+ //#region src/impl/common/userDBKeys.ts
5
+ const REVIEW_TIME_FORMAT = "YYYY-MM-DD--kk:mm:ss-SSS";
6
+ /**
7
+ * Build a ScheduledCard `_id` for the given review time.
8
+ *
9
+ * The id suffix is not a mere uniquifier: `getReviewstoDate` PARSES the id
10
+ * (with {@link REVIEW_TIME_FORMAT}) to decide due-ness, so the id is the
11
+ * datum. Anything that writes or rewrites scheduled-card docs (scheduling,
12
+ * user-state snapshot rebasing) must construct ids through this helper —
13
+ * a hand-rolled formatter will get moment's `kk` token (01-24 hours) wrong.
14
+ */
15
+ function makeScheduledCardId(reviewTime) {
16
+ return DocTypePrefixes[DocType.SCHEDULED_CARD] + moment.utc(reviewTime).format(REVIEW_TIME_FORMAT);
17
+ }
18
+ function hexEncode(str) {
19
+ let hex;
20
+ let returnStr = "";
21
+ for (let i = 0; i < str.length; i++) {
22
+ hex = str.charCodeAt(i).toString(16);
23
+ returnStr += ("000" + hex).slice(3);
24
+ }
25
+ return returnStr;
26
+ }
27
+ function filterAllDocsByPrefix(db, prefix, opts) {
28
+ const options = {
29
+ startkey: prefix,
30
+ endkey: prefix + "￰",
31
+ include_docs: true
32
+ };
33
+ if (opts) Object.assign(options, opts);
34
+ return db.allDocs(options);
35
+ }
36
+ function getStartAndEndKeys(key) {
37
+ return {
38
+ startkey: key,
39
+ endkey: key + "￰"
40
+ };
41
+ }
42
+ //#endregion
43
+ export { REVIEW_TIME_FORMAT, filterAllDocsByPrefix, getStartAndEndKeys, hexEncode, makeScheduledCardId };
44
+
45
+ //# sourceMappingURL=userDBKeys.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"userDBKeys.mjs","names":[],"sources":["../../../src/impl/common/userDBKeys.ts"],"sourcesContent":["// packages/db/src/impl/common/userDBKeys.ts\n//\n// Doc-id and key-range helpers for the user DB. Kept apart from\n// userDBHelpers.ts, which imports pouchdb-setup: importing one of these must\n// not pull PouchDB into a consumer's bundle.\n\nimport moment from 'moment';\nimport { DocType, DocTypePrefixes } from '../../core/types/types-legacy';\n\nexport const REVIEW_TIME_FORMAT: string = 'YYYY-MM-DD--kk:mm:ss-SSS';\n\n/**\n * Build a ScheduledCard `_id` for the given review time.\n *\n * The id suffix is not a mere uniquifier: `getReviewstoDate` PARSES the id\n * (with {@link REVIEW_TIME_FORMAT}) to decide due-ness, so the id is the\n * datum. Anything that writes or rewrites scheduled-card docs (scheduling,\n * user-state snapshot rebasing) must construct ids through this helper —\n * a hand-rolled formatter will get moment's `kk` token (01-24 hours) wrong.\n */\nexport function makeScheduledCardId(reviewTime: string | Date | moment.Moment): string {\n return DocTypePrefixes[DocType.SCHEDULED_CARD] + moment.utc(reviewTime).format(REVIEW_TIME_FORMAT);\n}\n\nexport function hexEncode(str: string): string {\n let hex: string;\n let returnStr: string = '';\n\n for (let i = 0; i < str.length; i++) {\n hex = str.charCodeAt(i).toString(16);\n returnStr += ('000' + hex).slice(3);\n }\n\n return returnStr;\n}\n\nexport function filterAllDocsByPrefix<T>(\n db: PouchDB.Database,\n prefix: string,\n opts?: PouchDB.Core.AllDocsOptions\n) {\n // see couchdb docs 6.2.2:\n // Guide to Views -> Views Collation -> String Ranges\n const options: PouchDB.Core.AllDocsWithinRangeOptions = {\n startkey: prefix,\n endkey: prefix + '￰',\n include_docs: true,\n };\n\n if (opts) {\n Object.assign(options, opts);\n }\n return db.allDocs<T>(options);\n}\n\nexport function getStartAndEndKeys(key: string): {\n startkey: string;\n endkey: string;\n} {\n return {\n startkey: key,\n endkey: key + '￰',\n };\n}\n"],"mappings":";;;;AASA,MAAa,qBAA6B;;;;;;;;;;AAW1C,SAAgB,oBAAoB,YAAmD;AACrF,QAAO,gBAAgB,QAAQ,kBAAkB,OAAO,IAAI,WAAW,CAAC,OAAO,mBAAmB;;AAGpG,SAAgB,UAAU,KAAqB;CAC7C,IAAI;CACJ,IAAI,YAAoB;AAExB,MAAK,IAAI,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,QAAM,IAAI,WAAW,EAAE,CAAC,SAAS,GAAG;AACpC,gBAAc,QAAQ,KAAK,MAAM,EAAE;;AAGrC,QAAO;;AAGT,SAAgB,sBACd,IACA,QACA,MACA;CAGA,MAAM,UAAkD;EACtD,UAAU;EACV,QAAQ,SAAS;EACjB,cAAc;EACf;AAED,KAAI,KACF,QAAO,OAAO,SAAS,KAAK;AAE9B,QAAO,GAAG,QAAW,QAAQ;;AAG/B,SAAgB,mBAAmB,KAGjC;AACA,QAAO;EACL,UAAU;EACV,QAAQ,MAAM;EACf"}
@@ -0,0 +1,272 @@
1
+ import "../../_virtual/_rolldown/runtime.mjs";
2
+ import { logger } from "../../util/logger.mjs";
3
+ import { ENV } from "../../factory.mjs";
4
+ import pouchdb_setup_default from "./pouchdb-setup.mjs";
5
+ import { GuestUsername } from "../../core/types/types-legacy.mjs";
6
+ import { hexEncode } from "../common/userDBKeys.mjs";
7
+ import { getLocalUserDB } from "../common/userDBHelpers.mjs";
8
+ import { accomodateGuest } from "../common/BaseUserDB.mjs";
9
+ import { getLoggedInUsername } from "./auth.mjs";
10
+ import { createPouchDBConfig } from "./index.mjs";
11
+ import { Status } from "@vue-skuilder/common";
12
+ //#region src/impl/couch/CouchDBSyncStrategy.ts
13
+ const log = (s) => {
14
+ logger.info(s);
15
+ };
16
+ /**
17
+ * Sync strategy that implements full CouchDB remote synchronization
18
+ * Handles account creation, authentication, and live sync with remote CouchDB server
19
+ */
20
+ var CouchDBSyncStrategy = class {
21
+ syncHandle;
22
+ /** In-flight one-shot hydration pull, so a timed-out pull can be abandoned. */
23
+ hydrationHandle;
24
+ setupRemoteDB(username) {
25
+ if (username === "sk-guest-" || username.startsWith("sk-guest-")) return getLocalUserDB(username);
26
+ else return this.getUserDB(username);
27
+ }
28
+ getWriteDB(username) {
29
+ if (username === "sk-guest-" || username.startsWith("sk-guest-")) return getLocalUserDB(username);
30
+ else return this.getUserDB(username);
31
+ }
32
+ /**
33
+ * One-shot remote → local pull. Resolves once the local mirror is caught up.
34
+ *
35
+ * Pull only: pushing here would upload whatever the local DB happens to hold
36
+ * before we know what the remote already has, which is the conflict-leaf
37
+ * problem hydration exists to avoid. Local changes go up when startSync()
38
+ * takes over.
39
+ *
40
+ * Into an EMPTY local DB this skips deleted documents, because a mirror that
41
+ * never held a document does not need to be told it was removed. That
42
+ * matters more than it sounds: scheduled reviews (`card_review_*`) are
43
+ * created and deleted once per review completed, so the changes feed is
44
+ * dominated by tombstones and grows without bound, while the durable record
45
+ * lives in card history. One real account measured 385 live documents behind
46
+ * 8,370 deletions — an unfiltered pull moved 9,520 documents and took ~20s,
47
+ * blowing the hydration timeout on a phone; filtered, the same pull moves
48
+ * 404 and takes ~2s, reaching a byte-identical local state.
49
+ *
50
+ * The filter runs server-side, so `last_seq` still reports the source's true
51
+ * sequence. Returning it lets startSync() begin the live pull from there
52
+ * instead of re-walking the same history in the background — without that,
53
+ * the cost is merely deferred, not removed.
54
+ */
55
+ async hydrate(localDB, remoteDB) {
56
+ const pristine = (await localDB.info()).doc_count === 0;
57
+ const replication = pouchdb_setup_default.replicate(remoteDB, localDB, pristine ? { selector: { _deleted: { $exists: false } } } : {});
58
+ this.hydrationHandle = replication;
59
+ try {
60
+ const info = await replication;
61
+ return {
62
+ docsWritten: info.docs_written,
63
+ lastSeq: pristine ? info.last_seq : void 0
64
+ };
65
+ } finally {
66
+ this.hydrationHandle = void 0;
67
+ }
68
+ }
69
+ startSync(localDB, remoteDB, since) {
70
+ if (localDB.name !== remoteDB.name) this.syncHandle = pouchdb_setup_default.sync(localDB, remoteDB, {
71
+ live: true,
72
+ retry: true,
73
+ ...since !== void 0 ? { pull: { since } } : {}
74
+ });
75
+ }
76
+ stopSync() {
77
+ if (this.hydrationHandle) {
78
+ try {
79
+ this.hydrationHandle.cancel();
80
+ } catch (e) {
81
+ logger.warn(`Failed to cancel hydration pull (continuing anyway): ${e}`);
82
+ }
83
+ this.hydrationHandle = void 0;
84
+ }
85
+ if (this.syncHandle) {
86
+ try {
87
+ this.syncHandle.cancel();
88
+ } catch (e) {
89
+ logger.warn(`Failed to cancel user sync (continuing anyway): ${e}`);
90
+ }
91
+ this.syncHandle = void 0;
92
+ }
93
+ }
94
+ canCreateAccount() {
95
+ return true;
96
+ }
97
+ canAuthenticate() {
98
+ return true;
99
+ }
100
+ async createAccount(username, password) {
101
+ const funnelUsername = await this.getCurrentUsername();
102
+ const isFunnelAccount = funnelUsername.startsWith(GuestUsername);
103
+ if (isFunnelAccount) logger.info(`Creating account for funnel user ${funnelUsername} -> ${username}`);
104
+ try {
105
+ const signupRequest = await this.getRemoteCouchRootDB().signUp(username, password);
106
+ if (signupRequest.ok) {
107
+ log(`CREATEACCOUNT: Successfully created account for ${username}`);
108
+ try {
109
+ log(`CREATEACCOUNT: logged out: ${(await this.getRemoteCouchRootDB().logOut()).ok}`);
110
+ } catch {}
111
+ const loginResult = await this.getRemoteCouchRootDB().logIn(username, password);
112
+ log(`CREATEACCOUNT: logged in as new user: ${loginResult.ok}`);
113
+ if (loginResult.ok) {
114
+ if (isFunnelAccount) {
115
+ logger.info(`Migrating data from funnel account ${funnelUsername} to ${username}`);
116
+ const migrationResult = await this.migrateFunnelData(funnelUsername, username);
117
+ if (!migrationResult.success) logger.warn(`Migration failed: ${migrationResult.error}`);
118
+ }
119
+ return {
120
+ status: Status.ok,
121
+ error: void 0
122
+ };
123
+ } else return {
124
+ status: Status.error,
125
+ error: "Failed to log in after account creation"
126
+ };
127
+ } else {
128
+ logger.warn(`Signup not OK: ${JSON.stringify(signupRequest)}`);
129
+ return {
130
+ status: Status.error,
131
+ error: "Account creation failed"
132
+ };
133
+ }
134
+ } catch (e) {
135
+ if (e.reason === "Document update conflict.") return {
136
+ status: Status.error,
137
+ error: "This username is taken!"
138
+ };
139
+ logger.error(`Error on signup: ${JSON.stringify(e)}`);
140
+ return {
141
+ status: Status.error,
142
+ error: e.message || "Unknown error during account creation"
143
+ };
144
+ }
145
+ }
146
+ async authenticate(username, password) {
147
+ try {
148
+ if ((await this.getRemoteCouchRootDB().logIn(username, password)).ok) {
149
+ log(`Successfully logged in as ${username}`);
150
+ return { ok: true };
151
+ } else {
152
+ log(`Login failed for ${username}`);
153
+ return {
154
+ ok: false,
155
+ error: "Invalid username or password"
156
+ };
157
+ }
158
+ } catch (error) {
159
+ logger.error(`Authentication error for ${username}:`, error);
160
+ return {
161
+ ok: false,
162
+ error: error.message || "Authentication failed"
163
+ };
164
+ }
165
+ }
166
+ async adoptSession(migrateFromGuest) {
167
+ let username;
168
+ try {
169
+ username = await getLoggedInUsername();
170
+ } catch {
171
+ return {
172
+ ok: false,
173
+ error: "No session to adopt"
174
+ };
175
+ }
176
+ if (migrateFromGuest?.startsWith("sk-guest-")) {
177
+ logger.info(`Migrating data from funnel account ${migrateFromGuest} to ${username}`);
178
+ const migrationResult = await this.migrateFunnelData(migrateFromGuest, username);
179
+ if (!migrationResult.success) logger.warn(`Migration failed: ${migrationResult.error}`);
180
+ }
181
+ return {
182
+ ok: true,
183
+ username
184
+ };
185
+ }
186
+ async logout() {
187
+ try {
188
+ const result = await this.getRemoteCouchRootDB().logOut();
189
+ return {
190
+ ok: result.ok,
191
+ error: result.ok ? void 0 : "Logout failed"
192
+ };
193
+ } catch (error) {
194
+ logger.error("Logout error:", error);
195
+ return {
196
+ ok: false,
197
+ error: error.message || "Logout failed"
198
+ };
199
+ }
200
+ }
201
+ async getCurrentUsername() {
202
+ logger.log("[funnel] CouchDBSyncStrategy.getCurrentUsername() called");
203
+ try {
204
+ const loggedInUsername = await getLoggedInUsername();
205
+ logger.log("[funnel] getLoggedInUsername() returned:", loggedInUsername);
206
+ return loggedInUsername;
207
+ } catch (e) {
208
+ logger.log("[funnel] getLoggedInUsername() failed, calling accomodateGuest()");
209
+ logger.log("[funnel] Error was:", e);
210
+ const guestInfo = accomodateGuest();
211
+ logger.log("[funnel] accomodateGuest() returned:", guestInfo);
212
+ return guestInfo.username;
213
+ }
214
+ }
215
+ /**
216
+ * Migrate data from funnel account to real account
217
+ */
218
+ async migrateFunnelData(oldUsername, newUsername) {
219
+ try {
220
+ logger.info(`Starting data migration from ${oldUsername} to ${newUsername}`);
221
+ const oldLocalDB = getLocalUserDB(oldUsername);
222
+ const newLocalDB = getLocalUserDB(newUsername);
223
+ const allDocs = await oldLocalDB.allDocs({ include_docs: true });
224
+ logger.info(`Found ${allDocs.rows.length} documents in funnel account`);
225
+ const docsToMigrate = allDocs.rows.filter((row) => !row.id.startsWith("_design/")).map((row) => ({
226
+ ...row.doc,
227
+ _rev: void 0
228
+ }));
229
+ if (docsToMigrate.length > 0) {
230
+ await newLocalDB.bulkDocs(docsToMigrate);
231
+ logger.info(`Successfully migrated ${docsToMigrate.length} documents from ${oldUsername} to ${newUsername}`);
232
+ } else logger.info("No documents to migrate from funnel account");
233
+ try {
234
+ await oldLocalDB.destroy();
235
+ logger.info(`Destroyed consumed guest DB for ${oldUsername}`);
236
+ } catch (destroyErr) {
237
+ logger.warn(`Failed to destroy consumed guest DB for ${oldUsername} (non-fatal): ${destroyErr instanceof Error ? destroyErr.message : String(destroyErr)}`);
238
+ }
239
+ return { success: true };
240
+ } catch (error) {
241
+ logger.error("Migration failed:", error);
242
+ return {
243
+ success: false,
244
+ error: error instanceof Error ? error.message : "Unknown error"
245
+ };
246
+ }
247
+ }
248
+ /**
249
+ * Get remote CouchDB root database for authentication operations
250
+ */
251
+ getRemoteCouchRootDB() {
252
+ const remoteStr = ENV.COUCHDB_SERVER_PROTOCOL + "://" + ENV.COUCHDB_SERVER_URL + "skuilder";
253
+ try {
254
+ return new pouchdb_setup_default(remoteStr, { skip_setup: true });
255
+ } catch (error) {
256
+ logger.error("Failed to initialize remote CouchDB connection:", error);
257
+ throw new Error(`Failed to initialize CouchDB: ${JSON.stringify(error)}`);
258
+ }
259
+ }
260
+ /**
261
+ * Get remote user database for a specific user
262
+ */
263
+ getUserDB(username) {
264
+ const dbName = `userdb-${hexEncode(username)}`;
265
+ log(`Fetching user database: ${dbName} (${username})`);
266
+ return new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL + "://" + ENV.COUCHDB_SERVER_URL + dbName, createPouchDBConfig());
267
+ }
268
+ };
269
+ //#endregion
270
+ export { CouchDBSyncStrategy };
271
+
272
+ //# sourceMappingURL=CouchDBSyncStrategy.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CouchDBSyncStrategy.mjs","names":["pouch"],"sources":["../../../src/impl/couch/CouchDBSyncStrategy.ts"],"sourcesContent":["// packages/db/src/impl/couch/CouchDBSyncStrategy.ts\n\nimport { ENV } from '@db/factory';\nimport { GuestUsername } from '../../core/types/types-legacy';\nimport { logger } from '../../util/logger';\nimport { Status } from '@vue-skuilder/common';\nimport type { SyncStrategy } from '../common/SyncStrategy';\nimport type {\n AccountCreationResult,\n AdoptSessionResult,\n AuthenticationResult,\n} from '../common/types';\nimport { getLocalUserDB, hexEncode, updateGuestAccountExpirationDate, accomodateGuest } from '../common';\nimport pouch from './pouchdb-setup';\nimport { createPouchDBConfig } from './index';\nimport { getLoggedInUsername } from './auth';\n\nconst log = (s: any) => {\n logger.info(s);\n};\n\n/**\n * Sync strategy that implements full CouchDB remote synchronization\n * Handles account creation, authentication, and live sync with remote CouchDB server\n */\nexport class CouchDBSyncStrategy implements SyncStrategy {\n private syncHandle?: any; // Handle to cancel sync if needed\n /** In-flight one-shot hydration pull, so a timed-out pull can be abandoned. */\n private hydrationHandle?: PouchDB.Replication.Replication<object>;\n\n setupRemoteDB(username: string): PouchDB.Database {\n if (username === GuestUsername || username.startsWith(GuestUsername)) {\n // For guest users, remote is same as local (no remote sync)\n return getLocalUserDB(username);\n } else {\n // For real users, connect to remote CouchDB\n return this.getUserDB(username);\n }\n }\n\n getWriteDB(username: string): PouchDB.Database {\n if (username === GuestUsername || username.startsWith(GuestUsername)) {\n // Guest users write to local database\n return getLocalUserDB(username);\n } else {\n // Authenticated users write to remote (which will sync to local)\n return this.getUserDB(username);\n }\n }\n\n /**\n * One-shot remote → local pull. Resolves once the local mirror is caught up.\n *\n * Pull only: pushing here would upload whatever the local DB happens to hold\n * before we know what the remote already has, which is the conflict-leaf\n * problem hydration exists to avoid. Local changes go up when startSync()\n * takes over.\n *\n * Into an EMPTY local DB this skips deleted documents, because a mirror that\n * never held a document does not need to be told it was removed. That\n * matters more than it sounds: scheduled reviews (`card_review_*`) are\n * created and deleted once per review completed, so the changes feed is\n * dominated by tombstones and grows without bound, while the durable record\n * lives in card history. One real account measured 385 live documents behind\n * 8,370 deletions — an unfiltered pull moved 9,520 documents and took ~20s,\n * blowing the hydration timeout on a phone; filtered, the same pull moves\n * 404 and takes ~2s, reaching a byte-identical local state.\n *\n * The filter runs server-side, so `last_seq` still reports the source's true\n * sequence. Returning it lets startSync() begin the live pull from there\n * instead of re-walking the same history in the background — without that,\n * the cost is merely deferred, not removed.\n */\n async hydrate(\n localDB: PouchDB.Database,\n remoteDB: PouchDB.Database\n ): Promise<{ docsWritten: number; lastSeq?: string | number }> {\n // Skipping tombstones is only sound when there is nothing local for a\n // missed deletion to strand. A non-empty local DB here means a previous\n // hydration failed partway (no marker was written, so we are retrying) and\n // may hold documents the remote has since deleted — take the slow, honest\n // path and let the full changes feed reconcile them.\n const pristine = (await localDB.info()).doc_count === 0;\n\n // A one-shot Replication is itself a promise of the completed result, so\n // it can be awaited directly — the handle is retained only so a pull that\n // outlives its timeout can be cancelled.\n const replication = pouch.replicate(\n remoteDB,\n localDB,\n pristine ? { selector: { _deleted: { $exists: false } } } : {}\n );\n this.hydrationHandle = replication;\n\n try {\n const info = await replication;\n return {\n docsWritten: info.docs_written,\n // Only a pristine pull is a trustworthy starting point for the live\n // sync; otherwise leave startSync() to its own checkpoint.\n lastSeq: pristine ? info.last_seq : undefined,\n };\n } finally {\n this.hydrationHandle = undefined;\n }\n }\n\n startSync(\n localDB: PouchDB.Database,\n remoteDB: PouchDB.Database,\n since?: string | number\n ): void {\n // Compare by NAME, not object identity. In guest mode setupRemoteDB()\n // returns getLocalUserDB(username) — the same database as localDB — but\n // getLocalUserDB() constructs a fresh PouchDB handle on every call rather\n // than caching, so `localDB !== remoteDB` was always true and guests ran a\n // live sync of a database against itself. Names are unambiguous here:\n // local DBs are named `userdb-<username>` (or a filesystem path in Node),\n // remote ones are a full `protocol://host/userdb-<hex>` URL.\n if (localDB.name !== remoteDB.name) {\n this.syncHandle = pouch.sync(localDB, remoteDB, {\n live: true,\n retry: true,\n // `since` applies to the pull only, and only when hydrate() just\n // established that local matches remote at that sequence. Without it,\n // a filtered hydration leaves the pull with no usable checkpoint (the\n // filter changes the replication id), so it restarts from zero and\n // re-walks in the background exactly the tombstone history hydration\n // just skipped — same work, now competing with the study session.\n //\n // Deliberately NOT persisted across launches: on later boots hydration\n // is skipped and the pull's own checkpoint is the correct resume\n // point, so a stored sequence could only be stale. If the app dies\n // before that first checkpoint is written, the next launch simply\n // walks the full feed once.\n ...(since !== undefined ? { pull: { since } } : {}),\n });\n }\n // If they're the same DB (guest mode), no sync needed\n }\n\n stopSync?(): void {\n if (this.hydrationHandle) {\n try {\n this.hydrationHandle.cancel();\n } catch (e) {\n logger.warn(`Failed to cancel hydration pull (continuing anyway): ${e}`);\n }\n this.hydrationHandle = undefined;\n }\n\n if (this.syncHandle) {\n // Called from BaseUser.init(), which is on the app boot path — a throw\n // here would leave BaseUser._initialized false forever, and\n // BaseUser.instance() polls that flag. Drop the handle regardless.\n try {\n this.syncHandle.cancel();\n } catch (e) {\n logger.warn(`Failed to cancel user sync (continuing anyway): ${e}`);\n }\n this.syncHandle = undefined;\n }\n }\n\n canCreateAccount(): boolean {\n return true;\n }\n\n canAuthenticate(): boolean {\n return true;\n }\n\n async createAccount(username: string, password: string): Promise<AccountCreationResult> {\n // IMPORTANT: Capture funnel username BEFORE any operations that might change session state\n const funnelUsername = await this.getCurrentUsername();\n const isFunnelAccount = funnelUsername.startsWith(GuestUsername);\n\n if (isFunnelAccount) {\n logger.info(`Creating account for funnel user ${funnelUsername} -> ${username}`);\n }\n\n try {\n const signupRequest = await this.getRemoteCouchRootDB().signUp(username, password);\n\n if (signupRequest.ok) {\n log(`CREATEACCOUNT: Successfully created account for ${username}`);\n\n // Log out any existing session\n try {\n const logoutResult = await this.getRemoteCouchRootDB().logOut();\n log(`CREATEACCOUNT: logged out: ${logoutResult.ok}`);\n } catch {\n // Ignore logout errors - might not be logged in\n }\n\n // Log in as the new user\n const loginResult = await this.getRemoteCouchRootDB().logIn(username, password);\n log(`CREATEACCOUNT: logged in as new user: ${loginResult.ok}`);\n\n if (loginResult.ok) {\n // Migrate funnel account data if applicable\n if (isFunnelAccount) {\n logger.info(`Migrating data from funnel account ${funnelUsername} to ${username}`);\n const migrationResult = await this.migrateFunnelData(funnelUsername, username);\n if (!migrationResult.success) {\n logger.warn(`Migration failed: ${migrationResult.error}`);\n // Continue anyway - don't block account creation\n }\n }\n\n return {\n status: Status.ok,\n error: undefined,\n };\n } else {\n return {\n status: Status.error,\n error: 'Failed to log in after account creation',\n };\n }\n } else {\n logger.warn(`Signup not OK: ${JSON.stringify(signupRequest)}`);\n return {\n status: Status.error,\n error: 'Account creation failed',\n };\n }\n } catch (e: any) {\n if (e.reason === 'Document update conflict.') {\n return {\n status: Status.error,\n error: 'This username is taken!',\n };\n }\n logger.error(`Error on signup: ${JSON.stringify(e)}`);\n return {\n status: Status.error,\n error: e.message || 'Unknown error during account creation',\n };\n }\n }\n\n async authenticate(username: string, password: string): Promise<AuthenticationResult> {\n try {\n const loginResult = await this.getRemoteCouchRootDB().logIn(username, password);\n\n if (loginResult.ok) {\n log(`Successfully logged in as ${username}`);\n return {\n ok: true,\n };\n } else {\n log(`Login failed for ${username}`);\n return {\n ok: false,\n error: 'Invalid username or password',\n };\n }\n } catch (error: any) {\n logger.error(`Authentication error for ${username}:`, error);\n return {\n ok: false,\n error: error.message || 'Authentication failed',\n };\n }\n }\n\n async adoptSession(migrateFromGuest?: string): Promise<AdoptSessionResult> {\n let username: string;\n try {\n username = await getLoggedInUsername();\n } catch {\n return { ok: false, error: 'No session to adopt' };\n }\n\n if (migrateFromGuest?.startsWith(GuestUsername)) {\n logger.info(`Migrating data from funnel account ${migrateFromGuest} to ${username}`);\n const migrationResult = await this.migrateFunnelData(migrateFromGuest, username);\n if (!migrationResult.success) {\n logger.warn(`Migration failed: ${migrationResult.error}`);\n // Continue anyway - don't block the login\n }\n }\n\n return { ok: true, username };\n }\n\n async logout(): Promise<AuthenticationResult> {\n try {\n const result = await this.getRemoteCouchRootDB().logOut();\n return {\n ok: result.ok,\n error: result.ok ? undefined : 'Logout failed',\n };\n } catch (error: any) {\n logger.error('Logout error:', error);\n return {\n ok: false,\n error: error.message || 'Logout failed',\n };\n }\n }\n\n async getCurrentUsername(): Promise<string> {\n logger.log('[funnel] CouchDBSyncStrategy.getCurrentUsername() called');\n try {\n const loggedInUsername = await getLoggedInUsername();\n logger.log('[funnel] getLoggedInUsername() returned:', loggedInUsername);\n return loggedInUsername;\n } catch (e) {\n // Not logged in - return unique guest account\n logger.log('[funnel] getLoggedInUsername() failed, calling accomodateGuest()');\n logger.log('[funnel] Error was:', e);\n const guestInfo = accomodateGuest();\n logger.log('[funnel] accomodateGuest() returned:', guestInfo);\n return guestInfo.username;\n }\n }\n\n /**\n * Migrate data from funnel account to real account\n */\n private async migrateFunnelData(\n oldUsername: string,\n newUsername: string\n ): Promise<{ success: boolean; error?: string }> {\n try {\n logger.info(`Starting data migration from ${oldUsername} to ${newUsername}`);\n\n const oldLocalDB = getLocalUserDB(oldUsername);\n const newLocalDB = getLocalUserDB(newUsername);\n\n // Get all docs from funnel account\n const allDocs = await oldLocalDB.allDocs({ include_docs: true });\n\n logger.info(`Found ${allDocs.rows.length} documents in funnel account`);\n\n // Filter out design docs and prepare for migration\n const docsToMigrate = allDocs.rows\n .filter(row => !row.id.startsWith('_design/'))\n .map(row => ({\n ...row.doc,\n _rev: undefined, // Remove rev to insert as new\n }));\n\n if (docsToMigrate.length > 0) {\n await newLocalDB.bulkDocs(docsToMigrate);\n logger.info(`Successfully migrated ${docsToMigrate.length} documents from ${oldUsername} to ${newUsername}`);\n } else {\n logger.info('No documents to migrate from funnel account');\n }\n\n // Destroy the consumed guest DB so it can never be re-migrated into a\n // future account. Without this, an orphaned userdb-sk-guest-<uuid> lingers\n // in IndexedDB indefinitely; if its stale identity is later re-adopted\n // (e.g. on logout via a surviving sk-guest-uuid), its progress bleeds into\n // the next new account. Best-effort: migration has already succeeded, so a\n // teardown failure must not fail account creation.\n try {\n await oldLocalDB.destroy();\n logger.info(`Destroyed consumed guest DB for ${oldUsername}`);\n } catch (destroyErr) {\n logger.warn(\n `Failed to destroy consumed guest DB for ${oldUsername} (non-fatal): ${\n destroyErr instanceof Error ? destroyErr.message : String(destroyErr)\n }`\n );\n }\n\n return { success: true };\n } catch (error) {\n logger.error('Migration failed:', error);\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error'\n };\n }\n }\n\n /**\n * Get remote CouchDB root database for authentication operations\n */\n private getRemoteCouchRootDB(): PouchDB.Database {\n const remoteStr: string =\n ENV.COUCHDB_SERVER_PROTOCOL + '://' + ENV.COUCHDB_SERVER_URL + 'skuilder';\n\n try {\n return new pouch(remoteStr, {\n skip_setup: true,\n });\n } catch (error) {\n logger.error('Failed to initialize remote CouchDB connection:', error);\n throw new Error(`Failed to initialize CouchDB: ${JSON.stringify(error)}`);\n }\n }\n\n /**\n * Get remote user database for a specific user\n */\n private getUserDB(username: string): PouchDB.Database {\n const guestAccount: boolean = false;\n\n const hexName = hexEncode(username);\n const dbName = `userdb-${hexName}`;\n log(`Fetching user database: ${dbName} (${username})`);\n\n // Odd construction here the result of a bug in the\n // interaction between pouch, pouch-auth.\n // see: https://github.com/pouchdb-community/pouchdb-authentication/issues/239\n const ret = new pouch(\n ENV.COUCHDB_SERVER_PROTOCOL + '://' + ENV.COUCHDB_SERVER_URL + dbName,\n createPouchDBConfig()\n );\n\n if (guestAccount) {\n updateGuestAccountExpirationDate(ret);\n }\n\n return ret;\n }\n}\n"],"mappings":";;;;;;;;;;;;AAiBA,MAAM,OAAO,MAAW;AACtB,QAAO,KAAK,EAAE;;;;;;AAOhB,IAAa,sBAAb,MAAyD;CACvD;;CAEA;CAEA,cAAc,UAAoC;AAChD,MAAI,aAAA,eAA8B,SAAS,WAAA,YAAyB,CAElE,QAAO,eAAe,SAAS;MAG/B,QAAO,KAAK,UAAU,SAAS;;CAInC,WAAW,UAAoC;AAC7C,MAAI,aAAA,eAA8B,SAAS,WAAA,YAAyB,CAElE,QAAO,eAAe,SAAS;MAG/B,QAAO,KAAK,UAAU,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;CA2BnC,MAAM,QACJ,SACA,UAC6D;EAM7D,MAAM,YAAY,MAAM,QAAQ,MAAM,EAAE,cAAc;EAKtD,MAAM,cAAcA,sBAAM,UACxB,UACA,SACA,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE,SAAS,OAAO,EAAE,EAAE,GAAG,EAAE,CAC/D;AACD,OAAK,kBAAkB;AAEvB,MAAI;GACF,MAAM,OAAO,MAAM;AACnB,UAAO;IACL,aAAa,KAAK;IAGlB,SAAS,WAAW,KAAK,WAAW,KAAA;IACrC;YACO;AACR,QAAK,kBAAkB,KAAA;;;CAI3B,UACE,SACA,UACA,OACM;AAQN,MAAI,QAAQ,SAAS,SAAS,KAC5B,MAAK,aAAaA,sBAAM,KAAK,SAAS,UAAU;GAC9C,MAAM;GACN,OAAO;GAaP,GAAI,UAAU,KAAA,IAAY,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE;GACnD,CAAC;;CAKN,WAAkB;AAChB,MAAI,KAAK,iBAAiB;AACxB,OAAI;AACF,SAAK,gBAAgB,QAA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