@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,1103 @@
1
+ import "../../_virtual/_rolldown/runtime.mjs";
2
+ import { logger } from "../../util/logger.mjs";
3
+ import { DocType, DocTypePrefixes, GuestUsername } from "../../core/types/types-legacy.mjs";
4
+ import { REVIEW_TIME_FORMAT, filterAllDocsByPrefix, getStartAndEndKeys } from "./userDBKeys.mjs";
5
+ import UpdateQueue from "../couch/updateQueue.mjs";
6
+ import { areQuestionRecords, getCardHistoryID } from "../../core/util/index.mjs";
7
+ import { getLapses, getStreak } from "../../study/SpacedRepetition.mjs";
8
+ import { getLocalUserDB, removeScheduledCardReviewLocal, scheduleCardReviewLocal } from "./userDBHelpers.mjs";
9
+ import { UsrCrsData } from "../couch/user-course-relDB.mjs";
10
+ import { getCredentialledCourseConfig } from "../couch/courseAPI.mjs";
11
+ import { buildStrategyStateId } from "../../core/types/strategyState.mjs";
12
+ import { HYDRATION_MARKER_ID } from "../../core/types/hydration.mjs";
13
+ import moment from "moment";
14
+ import { Status } from "@vue-skuilder/common";
15
+ //#region src/impl/common/BaseUserDB.ts
16
+ const log = (s) => {
17
+ logger.info(s);
18
+ };
19
+ /**
20
+ * Ceiling on the initial pull of a user's data before we give up and report
21
+ * `failed`. Generous relative to the expected payload (a user database is a
22
+ * config doc, registrations, strategy state, and per-card history), so hitting
23
+ * it indicates a genuinely unusable connection rather than a large account.
24
+ */
25
+ const HYDRATION_TIMEOUT_MS = 15e3;
26
+ /**
27
+ * Reject if `p` has not settled within `ms`.
28
+ *
29
+ * Note the underlying work is not cancelled by this — callers that need the
30
+ * operation stopped must do so themselves.
31
+ */
32
+ function withTimeout(p, ms, label) {
33
+ let timer;
34
+ return Promise.race([p, new Promise((_resolve, reject) => {
35
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`${label} timed out after ${ms}ms`)), ms);
36
+ })]).finally(() => {
37
+ if (timer !== void 0) clearTimeout(timer);
38
+ });
39
+ }
40
+ /**
41
+ * Base user database implementation that uses a pluggable sync strategy.
42
+ * Handles local storage operations and delegates sync/remote operations to the strategy.
43
+ */
44
+ var BaseUser = class BaseUser {
45
+ static _instance;
46
+ static _initialized = false;
47
+ static Dummy(syncStrategy) {
48
+ return new BaseUser("Me", syncStrategy);
49
+ }
50
+ static DOC_IDS = {
51
+ CONFIG: "CONFIG",
52
+ COURSE_REGISTRATIONS: "CourseRegistrations",
53
+ CLASSROOM_REGISTRATIONS: "ClassroomRegistrations"
54
+ };
55
+ _username;
56
+ syncStrategy;
57
+ getUsername() {
58
+ return this._username;
59
+ }
60
+ isLoggedIn() {
61
+ return !this._username.startsWith(GuestUsername);
62
+ }
63
+ remote() {
64
+ return this.remoteDB;
65
+ }
66
+ localDB;
67
+ remoteDB;
68
+ writeDB;
69
+ updateQueue;
70
+ _hydration = { state: "not-required" };
71
+ /** In-flight hydration, so concurrent callers can wait for a real answer. */
72
+ _hydrationPromise = null;
73
+ /**
74
+ * Sequence the local mirror was filled to by a hydration that succeeded in
75
+ * THIS init(), handed to startSync() so the live pull can skip history it
76
+ * would otherwise re-walk. Undefined whenever there is no such guarantee —
77
+ * hydration skipped, not required, or failed. Never persisted; see the
78
+ * `since` note in CouchDBSyncStrategy.startSync().
79
+ */
80
+ _hydratedSeq;
81
+ /**
82
+ * How far the local mirror can be trusted, RIGHT NOW. See
83
+ * {@link UserHydrationStatus}.
84
+ *
85
+ * This is a snapshot, and during login it can legitimately read
86
+ * `hydrating` — prefer awaitHydration() anywhere a decision hangs on the
87
+ * answer.
88
+ */
89
+ hydrationStatus() {
90
+ return { ...this._hydration };
91
+ }
92
+ /**
93
+ * The hydration status once it has settled — never `hydrating`.
94
+ *
95
+ * Resolves immediately unless a pull is in flight. Exists for callers that
96
+ * must decide something (a route guard, a first-run branch) and would
97
+ * otherwise sample `hydrating` and guess. Since init() is awaited by both
98
+ * app startup and login(), that only happens when something navigates
99
+ * concurrently with a login still in progress — a window that stretches to
100
+ * HYDRATION_TIMEOUT_MS on a slow connection.
101
+ */
102
+ async awaitHydration() {
103
+ try {
104
+ await this._hydrationPromise;
105
+ } catch {}
106
+ return this.hydrationStatus();
107
+ }
108
+ /**
109
+ * Whether a missing document may be treated as genuinely absent, allowing
110
+ * callers to create it with defaults.
111
+ *
112
+ * False only when hydration failed or is still running: a 404 then may just
113
+ * mean "not pulled down yet", and materializing a default would both lie to
114
+ * the user and, once live sync starts, push a rev-1 document that loses to
115
+ * the real one — silently discarding it.
116
+ */
117
+ canMaterializeDefaults() {
118
+ return this._hydration.state !== "failed" && this._hydration.state !== "hydrating";
119
+ }
120
+ async createAccount(username, password) {
121
+ if (!this.syncStrategy.canCreateAccount()) throw new Error("Account creation not supported by current sync strategy");
122
+ if (!this._username.startsWith("sk-guest-")) throw new Error(`Cannot create a new account while logged in:
123
+ Currently logged-in as ${this._username}.`);
124
+ const result = await this.syncStrategy.createAccount(username, password);
125
+ if (result.status === Status.ok) {
126
+ log(`Account created successfully, updating username to ${username}`);
127
+ this._username = username;
128
+ try {
129
+ localStorage.removeItem("sk-guest-uuid");
130
+ } catch (e) {
131
+ logger.warn("localStorage not available (Node.js environment):", e);
132
+ }
133
+ await this.init();
134
+ }
135
+ return {
136
+ status: result.status,
137
+ error: result.error || ""
138
+ };
139
+ }
140
+ async login(username, password) {
141
+ if (!this.syncStrategy.canAuthenticate()) throw new Error("Authentication not supported by current sync strategy");
142
+ if (!this._username.startsWith("sk-guest-") && this._username != username) {
143
+ if (this._username != username) throw new Error(`Cannot change accounts while logged in.
144
+ Log out of account ${this.getUsername()} before logging in as ${username}.`);
145
+ logger.warn(`User ${this._username} is already logged in, but executing login again.`);
146
+ }
147
+ const loginResult = await this.syncStrategy.authenticate(username, password);
148
+ if (loginResult.ok) {
149
+ log(`Logged in as ${username}`);
150
+ this._username = username;
151
+ try {
152
+ localStorage.removeItem("sk-guest-uuid");
153
+ } catch (e) {
154
+ logger.warn("localStorage not available (Node.js environment):", e);
155
+ }
156
+ await this.init();
157
+ }
158
+ return loginResult;
159
+ }
160
+ /**
161
+ * Adopt a remote session that was established outside this client — e.g. a
162
+ * backend verified a third-party sign-in (Google) and set the session cookie
163
+ * on its response. Afterwards the user is logged in exactly as after
164
+ * login(): username switched, guest pointer cleared, init() re-run.
165
+ *
166
+ * @param opts.migrateGuestData Carry the current guest account's local data
167
+ * into the adopted account. Pass true for a freshly created account (as
168
+ * createAccount() does), false for an existing one (as login() does).
169
+ */
170
+ async adoptSession(opts) {
171
+ if (!this.syncStrategy.canAuthenticate() || !this.syncStrategy.adoptSession) throw new Error("Session adoption not supported by current sync strategy");
172
+ const guestUsername = this._username.startsWith("sk-guest-") ? this._username : void 0;
173
+ if (!guestUsername) throw new Error(`Cannot adopt a session while logged in.
174
+ Log out of account ${this.getUsername()} first.`);
175
+ const result = await this.syncStrategy.adoptSession(opts.migrateGuestData ? guestUsername : void 0);
176
+ if (result.ok && result.username) {
177
+ log(`Adopted session for ${result.username}`);
178
+ this._username = result.username;
179
+ try {
180
+ localStorage.removeItem("sk-guest-uuid");
181
+ } catch (e) {
182
+ logger.warn("localStorage not available (Node.js environment):", e);
183
+ }
184
+ await this.init();
185
+ }
186
+ return result;
187
+ }
188
+ async resetUserData() {
189
+ if (this.syncStrategy.canAuthenticate()) return {
190
+ status: Status.error,
191
+ error: "Reset user data is only available for local-only mode. Use logout instead for remote sync."
192
+ };
193
+ try {
194
+ const localDB = getLocalUserDB(this._username);
195
+ const docsToDelete = (await localDB.allDocs({ include_docs: false })).rows.filter((row) => {
196
+ const id = row.id;
197
+ return id.startsWith(DocTypePrefixes[DocType.CARDRECORD]) || id.startsWith(DocTypePrefixes[DocType.SCHEDULED_CARD]) || id.startsWith(DocTypePrefixes[DocType.STRATEGY_STATE]) || id.startsWith(DocTypePrefixes[DocType.USER_OUTCOME]) || id.startsWith(DocTypePrefixes[DocType.STRATEGY_LEARNING_STATE]) || id === BaseUser.DOC_IDS.COURSE_REGISTRATIONS || id === BaseUser.DOC_IDS.CLASSROOM_REGISTRATIONS || id === BaseUser.DOC_IDS.CONFIG;
198
+ }).map((row) => ({
199
+ _id: row.id,
200
+ _rev: row.value.rev,
201
+ _deleted: true
202
+ }));
203
+ if (docsToDelete.length > 0) await localDB.bulkDocs(docsToDelete);
204
+ await this.init();
205
+ return { status: Status.ok };
206
+ } catch (error) {
207
+ logger.error("Failed to reset user data:", error);
208
+ return {
209
+ status: Status.error,
210
+ error: error instanceof Error ? error.message : "Unknown error during reset"
211
+ };
212
+ }
213
+ }
214
+ async logout() {
215
+ if (!this.syncStrategy.canAuthenticate()) {
216
+ this._username = await this.syncStrategy.getCurrentUsername();
217
+ await this.init();
218
+ return { ok: true };
219
+ }
220
+ const ret = await this.syncStrategy.logout();
221
+ try {
222
+ localStorage.removeItem("sk-guest-uuid");
223
+ } catch (e) {
224
+ logger.warn("localStorage not available (Node.js environment):", e);
225
+ }
226
+ this._username = await this.syncStrategy.getCurrentUsername();
227
+ await this.init();
228
+ return ret;
229
+ }
230
+ async get(id) {
231
+ return this.localDB.get(id);
232
+ }
233
+ update(id, update) {
234
+ return this.updateQueue.update(id, update);
235
+ }
236
+ async getCourseRegistrationsDoc() {
237
+ logger.debug(`Fetching courseRegistrations for ${this.getUsername()}`);
238
+ let ret;
239
+ try {
240
+ return await this.localDB.get(BaseUser.DOC_IDS.COURSE_REGISTRATIONS);
241
+ } catch (e) {
242
+ if (e.status === 404) {
243
+ if (!this.canMaterializeDefaults()) throw new Error(`Cannot read course registrations for ${this._username}: the local mirror is unavailable (hydration state '${this._hydration.state}'). Refusing to create an empty registration doc — that would report an existing user as unregistered, and then lose to their real document once sync resumes.`);
244
+ await this.localDB.put({
245
+ _id: BaseUser.DOC_IDS.COURSE_REGISTRATIONS,
246
+ courses: [],
247
+ studyWeight: {}
248
+ });
249
+ ret = await this.getCourseRegistrationsDoc();
250
+ } else throw new Error(`Unexpected error ${JSON.stringify(e)} in getOrCreateCourseRegistrationDoc...`);
251
+ }
252
+ return ret;
253
+ }
254
+ async getActiveCourses() {
255
+ return (await this.getCourseRegistrationsDoc()).courses.filter((c) => {
256
+ return c.status === void 0 || c.status === "active";
257
+ });
258
+ }
259
+ /**
260
+ * Returns a promise of the card IDs that the user has
261
+ * a scheduled review for.
262
+ *
263
+ */
264
+ async getActiveCards() {
265
+ const keys = getStartAndEndKeys(DocTypePrefixes[DocType.SCHEDULED_CARD]);
266
+ return (await this.remoteDB.allDocs({
267
+ startkey: keys.startkey,
268
+ endkey: keys.endkey,
269
+ include_docs: true
270
+ })).rows.map((r) => {
271
+ return {
272
+ courseID: r.doc.courseId,
273
+ cardID: r.doc.cardId
274
+ };
275
+ });
276
+ }
277
+ async getActivityRecords() {
278
+ try {
279
+ const hist = await this.getHistory();
280
+ const allRecords = [];
281
+ if (!Array.isArray(hist)) {
282
+ logger.error("getHistory did not return an array:", hist);
283
+ return allRecords;
284
+ }
285
+ let sampleCount = 0;
286
+ for (let i = 0; i < hist.length; i++) try {
287
+ if (hist[i] && Array.isArray(hist[i].records)) hist[i].records.forEach((record) => {
288
+ try {
289
+ if (!record.timeStamp) return;
290
+ let timeStamp;
291
+ if (typeof record.timeStamp === "object") if (typeof record.timeStamp.toDate === "function") timeStamp = record.timeStamp.toISOString();
292
+ else if (record.timeStamp instanceof Date) timeStamp = record.timeStamp.toISOString();
293
+ else {
294
+ if (sampleCount < 3) {
295
+ logger.warn("Unknown timestamp object type:", record.timeStamp);
296
+ sampleCount++;
297
+ }
298
+ return;
299
+ }
300
+ else if (typeof record.timeStamp === "string") {
301
+ const date = new Date(record.timeStamp);
302
+ if (isNaN(date.getTime())) return;
303
+ timeStamp = record.timeStamp;
304
+ } else if (typeof record.timeStamp === "number") timeStamp = new Date(record.timeStamp).toISOString();
305
+ else return;
306
+ allRecords.push({
307
+ timeStamp,
308
+ courseID: record.courseID || "unknown",
309
+ cardID: record.cardID || "unknown",
310
+ timeSpent: record.timeSpent || 0,
311
+ type: "card_view"
312
+ });
313
+ } catch (err) {}
314
+ });
315
+ } catch (err) {
316
+ logger.error("Error processing history item:", err);
317
+ }
318
+ logger.debug(`Found ${allRecords.length} activity records`);
319
+ return allRecords;
320
+ } catch (err) {
321
+ logger.error("Error in getActivityRecords:", err);
322
+ return [];
323
+ }
324
+ }
325
+ async getReviewstoDate(targetDate, course_id) {
326
+ const keys = getStartAndEndKeys(DocTypePrefixes[DocType.SCHEDULED_CARD]);
327
+ const reviews = await this.remoteDB.allDocs({
328
+ startkey: keys.startkey,
329
+ endkey: keys.endkey,
330
+ include_docs: true
331
+ });
332
+ log(`Fetching ${this._username}'s scheduled reviews${course_id ? ` for course ${course_id}` : ""}.`);
333
+ return reviews.rows.filter((r) => {
334
+ if (r.id.startsWith(DocTypePrefixes[DocType.SCHEDULED_CARD])) {
335
+ const date = moment.utc(r.id.substr(DocTypePrefixes[DocType.SCHEDULED_CARD].length), REVIEW_TIME_FORMAT);
336
+ if (targetDate.isAfter(date)) {
337
+ if (course_id === void 0 || r.doc.courseId === course_id) return true;
338
+ }
339
+ }
340
+ }).map((r) => r.doc);
341
+ }
342
+ async getReviewsForcast(daysCount, course_id) {
343
+ const time = moment.utc().add(daysCount, "days");
344
+ return this.getReviewstoDate(time, course_id);
345
+ }
346
+ async getPendingReviews(course_id) {
347
+ const now = moment.utc();
348
+ return this.getReviewstoDate(now, course_id);
349
+ }
350
+ async getScheduledReviewCount(course_id) {
351
+ return (await this.getPendingReviews(course_id)).length;
352
+ }
353
+ async getRegisteredCourses() {
354
+ return (await this.getCourseRegistrationsDoc()).courses.filter((c) => {
355
+ return !c.status || c.status === "active" || c.status === "maintenance-mode";
356
+ });
357
+ }
358
+ async getCourseRegDoc(courseID) {
359
+ const ret = (await this.getCourseRegistrationsDoc()).courses.find((c) => c.courseID === courseID);
360
+ if (ret) return ret;
361
+ else throw new Error(`Course registration not found for course ID: ${courseID}`);
362
+ }
363
+ async registerForCourse(course_id, previewMode = false) {
364
+ return this.getCourseRegistrationsDoc().then((doc) => {
365
+ const status = previewMode ? "preview" : "active";
366
+ logger.debug(`Registering for ${course_id} with status: ${status}`);
367
+ const regItem = {
368
+ status,
369
+ courseID: course_id,
370
+ user: true,
371
+ admin: false,
372
+ moderator: false,
373
+ elo: {
374
+ global: {
375
+ score: 1e3,
376
+ count: 0
377
+ },
378
+ tags: {},
379
+ misc: {}
380
+ }
381
+ };
382
+ if (doc.courses.filter((course) => {
383
+ return course.courseID === regItem.courseID;
384
+ }).length === 0) {
385
+ log(`It's a new course registration!`);
386
+ doc.courses.push(regItem);
387
+ doc.studyWeight[course_id] = 1;
388
+ } else doc.courses.forEach((c) => {
389
+ log(`Found the previously registered course!`);
390
+ if (c.courseID === course_id) c.status = status;
391
+ });
392
+ return this.localDB.put(doc);
393
+ }).catch((e) => {
394
+ log(`Registration failed because of: ${JSON.stringify(e)}`);
395
+ throw e;
396
+ });
397
+ }
398
+ async dropCourse(course_id, dropStatus = "dropped") {
399
+ return this.getCourseRegistrationsDoc().then((doc) => {
400
+ let index = -1;
401
+ for (let i = 0; i < doc.courses.length; i++) if (doc.courses[i].courseID === course_id) index = i;
402
+ if (index !== -1) {
403
+ delete doc.studyWeight[course_id];
404
+ doc.courses[index].status = dropStatus;
405
+ } else throw new Error(`User ${this.getUsername()} is not currently registered for course ${course_id}`);
406
+ return this.localDB.put(doc);
407
+ });
408
+ }
409
+ async getCourseInterface(courseId) {
410
+ return new UsrCrsData(this, courseId);
411
+ }
412
+ async getUserEditableCourses() {
413
+ let courseIDs = [];
414
+ const registeredCourses = await this.getCourseRegistrationsDoc();
415
+ courseIDs = courseIDs.concat(registeredCourses.courses.map((course) => {
416
+ return course.courseID;
417
+ }));
418
+ return await Promise.all(courseIDs.map(async (id) => {
419
+ return await getCredentialledCourseConfig(id);
420
+ }));
421
+ }
422
+ async getConfig() {
423
+ const defaultConfig = {
424
+ _id: BaseUser.DOC_IDS.CONFIG,
425
+ darkMode: false,
426
+ likesConfetti: false,
427
+ sessionTimeLimit: 5
428
+ };
429
+ try {
430
+ const cfg = await this.localDB.get(BaseUser.DOC_IDS.CONFIG);
431
+ logger.debug("Raw config from DB:", cfg);
432
+ return cfg;
433
+ } catch (e) {
434
+ const err = e;
435
+ if (err.name && err.name === "not_found") {
436
+ if (!this.canMaterializeDefaults()) throw new Error(`Cannot read config for ${this._username}: the local mirror is unavailable (hydration state '${this._hydration.state}'). Refusing to write a default config over what may be an existing one.`);
437
+ await this.localDB.put(defaultConfig);
438
+ return this.getConfig();
439
+ } else {
440
+ logger.error(`Error setting user default config:`, e);
441
+ throw new Error(`Error returning the user's configuration: ${JSON.stringify(e)}`);
442
+ }
443
+ }
444
+ }
445
+ async setConfig(items) {
446
+ logger.debug(`Setting Config items ${JSON.stringify(items)}`);
447
+ const c = await this.getConfig();
448
+ const put = await this.localDB.put({
449
+ ...c,
450
+ ...items
451
+ });
452
+ if (put.ok) logger.debug(`Config items set: ${JSON.stringify(items)}`);
453
+ else logger.error(`Error setting config items: ${JSON.stringify(put)}`);
454
+ }
455
+ /**
456
+ *
457
+ * This function should be called *only* by the pouchdb datalayer provider
458
+ * auth store.
459
+ *
460
+ *
461
+ * Anyone else seeking the current user should use the auth store's
462
+ * exported `getCurrentUser` method.
463
+ *
464
+ */
465
+ static async instance(syncStrategy, username) {
466
+ if (username) {
467
+ BaseUser._instance = new BaseUser(username, syncStrategy);
468
+ await BaseUser._instance.init();
469
+ return BaseUser._instance;
470
+ } else if (BaseUser._instance && BaseUser._initialized) return BaseUser._instance;
471
+ else if (BaseUser._instance) return new Promise((resolve) => {
472
+ (function waitForUser() {
473
+ if (BaseUser._initialized) return resolve(BaseUser._instance);
474
+ else setTimeout(waitForUser, 50);
475
+ })();
476
+ });
477
+ else {
478
+ BaseUser._instance = new BaseUser(await syncStrategy.getCurrentUsername(), syncStrategy);
479
+ await BaseUser._instance.init();
480
+ return BaseUser._instance;
481
+ }
482
+ }
483
+ constructor(username, syncStrategy) {
484
+ BaseUser._initialized = false;
485
+ this._username = username;
486
+ this.syncStrategy = syncStrategy;
487
+ this.setDBandQ();
488
+ }
489
+ setDBandQ() {
490
+ this.localDB = getLocalUserDB(this._username);
491
+ this.remoteDB = this.syncStrategy.setupRemoteDB(this._username);
492
+ this.writeDB = this.syncStrategy.getWriteDB ? this.syncStrategy.getWriteDB(this._username) : this.localDB;
493
+ this.updateQueue = new UpdateQueue(this.localDB, this.writeDB);
494
+ }
495
+ async init() {
496
+ BaseUser._initialized = false;
497
+ if (this._username === "admin") {
498
+ BaseUser._initialized = true;
499
+ return;
500
+ }
501
+ this.syncStrategy.stopSync?.();
502
+ this.setDBandQ();
503
+ this._hydrationPromise = this.hydrateLocalMirror();
504
+ await this._hydrationPromise;
505
+ this.syncStrategy.startSync(this.localDB, this.remoteDB, this._hydratedSeq);
506
+ this.applyDesignDocs().catch((error) => {
507
+ log(`Error in applyDesignDocs background task: ${error}`);
508
+ if (error && typeof error === "object") log(`Full error details in applyDesignDocs: ${JSON.stringify(error)}`);
509
+ });
510
+ this.deduplicateReviews().catch((error) => {
511
+ log(`Error in deduplicateReviews background task: ${error}`);
512
+ if (error && typeof error === "object") log(`Full error details in background task: ${JSON.stringify(error)}`);
513
+ });
514
+ BaseUser._initialized = true;
515
+ }
516
+ /**
517
+ * Pull this account's documents into the local mirror, if that hasn't
518
+ * happened on this device before.
519
+ *
520
+ * Runs between setDBandQ() and startSync() — after the handles exist, before
521
+ * anything can observe an empty local DB or replicate one upward.
522
+ *
523
+ * Never throws: a failure is recorded as `failed` state and reported through
524
+ * hydrationStatus(), because throwing here would abort init() and leave
525
+ * BaseUser._initialized false forever (BaseUser.instance() polls it with no
526
+ * ceiling). Callers decide what a failure means for them.
527
+ */
528
+ async hydrateLocalMirror() {
529
+ this._hydratedSeq = void 0;
530
+ if (this.localDB.name === this.remoteDB.name || !this.syncStrategy.hydrate) {
531
+ this._hydration = { state: "not-required" };
532
+ return;
533
+ }
534
+ if (await this.hasHydrationMarker()) {
535
+ this._hydration = { state: "stale" };
536
+ return;
537
+ }
538
+ this._hydration = { state: "hydrating" };
539
+ const start = Date.now();
540
+ try {
541
+ const { docsWritten, lastSeq } = await withTimeout(this.syncStrategy.hydrate(this.localDB, this.remoteDB), HYDRATION_TIMEOUT_MS, `Hydration of local mirror for ${this._username}`);
542
+ this._hydratedSeq = lastSeq;
543
+ await this.writeHydrationMarker();
544
+ this._hydration = {
545
+ state: "hydrated",
546
+ docsWritten,
547
+ durationMs: Date.now() - start
548
+ };
549
+ log(`Hydrated local mirror for ${this._username}: ${docsWritten} docs in ${this._hydration.durationMs}ms`);
550
+ } catch (e) {
551
+ this.syncStrategy.stopSync?.();
552
+ this._hydration = {
553
+ state: "failed",
554
+ durationMs: Date.now() - start,
555
+ error: e instanceof Error ? e.message : String(e)
556
+ };
557
+ logger.error(`Failed to hydrate local mirror for ${this._username}:`, e);
558
+ }
559
+ }
560
+ /**
561
+ * Has a full pull completed on this device for the CURRENT account?
562
+ *
563
+ * The marker is a `_local/` document, which never replicates — so its
564
+ * presence describes this device's mirror and cannot arrive from elsewhere.
565
+ */
566
+ async hasHydrationMarker() {
567
+ try {
568
+ return (await this.localDB.get(HYDRATION_MARKER_ID)).username === this._username;
569
+ } catch {
570
+ return false;
571
+ }
572
+ }
573
+ async writeHydrationMarker() {
574
+ try {
575
+ let existingRev;
576
+ try {
577
+ existingRev = (await this.localDB.get(HYDRATION_MARKER_ID))._rev;
578
+ } catch {}
579
+ await this.localDB.put({
580
+ _id: HYDRATION_MARKER_ID,
581
+ _rev: existingRev,
582
+ username: this._username,
583
+ hydratedAt: (/* @__PURE__ */ new Date()).toISOString()
584
+ });
585
+ } catch (e) {
586
+ logger.warn(`Could not write hydration marker for ${this._username}: ${e}`);
587
+ }
588
+ }
589
+ static designDocs = [{
590
+ _id: "_design/reviewCards",
591
+ views: { reviewCards: { map: `function (doc) {
592
+ if (doc._id && doc._id.indexOf('card_review') === 0 && doc.courseId && doc.cardId) {
593
+ emit(doc._id, doc.courseId + '-' + doc.cardId);
594
+ }
595
+ }` } }
596
+ }];
597
+ async applyDesignDocs() {
598
+ log(`Starting applyDesignDocs for user: ${this._username}`);
599
+ log(`Remote DB name: ${this.remoteDB.name || "unknown"}`);
600
+ if (this._username === "admin") {
601
+ log("Skipping design docs for admin user");
602
+ return;
603
+ }
604
+ log(`Applying ${BaseUser.designDocs.length} design docs`);
605
+ for (const doc of BaseUser.designDocs) {
606
+ log(`Applying design doc: ${doc._id}`);
607
+ try {
608
+ try {
609
+ const existingDoc = await this.remoteDB.get(doc._id);
610
+ await this.remoteDB.put({
611
+ ...doc,
612
+ _rev: existingDoc._rev
613
+ });
614
+ } catch (e) {
615
+ if (e?.name === "not_found") await this.remoteDB.put(doc);
616
+ else throw e;
617
+ }
618
+ } catch (error) {
619
+ if (error.name && error.name === "conflict") {
620
+ logger.warn(`Design doc ${doc._id} update conflict - will retry`);
621
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
622
+ await this.applyDesignDoc(doc);
623
+ } else {
624
+ logger.error(`Failed to apply design doc ${doc._id}:`, error);
625
+ throw error;
626
+ }
627
+ }
628
+ }
629
+ }
630
+ async applyDesignDoc(doc, retries = 3) {
631
+ try {
632
+ const existingDoc = await this.remoteDB.get(doc._id);
633
+ await this.remoteDB.put({
634
+ ...doc,
635
+ _rev: existingDoc._rev
636
+ });
637
+ } catch (e) {
638
+ if (e?.name === "conflict" && retries > 0) {
639
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
640
+ return this.applyDesignDoc(doc, retries - 1);
641
+ }
642
+ throw e;
643
+ }
644
+ }
645
+ /**
646
+ * Logs a record of the user's interaction with the card and returns the card's
647
+ * up-to-date history.
648
+ *
649
+ * **Automatic Initialization:**
650
+ * If this is the user's first interaction with the card (CardHistory doesn't exist),
651
+ * this method automatically creates the CardHistory document with initial values
652
+ * (lapses: 0, streak: 0, bestInterval: 0).
653
+ *
654
+ * **Error Handling:**
655
+ * - Handles 404 errors by creating initial CardHistory document
656
+ * - Re-throws all other errors from UpdateQueue
657
+ *
658
+ * // [ ] #db-refactor extract to a smaller scope - eg, UserStudySession
659
+ *
660
+ * @param record - The recent recorded interaction between user and card
661
+ * @returns The updated state of the card's CardHistory data
662
+ * @throws Error if document creation fails or non-404 database error occurs
663
+ */
664
+ async putCardRecord(record) {
665
+ const cardHistoryID = getCardHistoryID(record.courseID, record.cardID);
666
+ record.timeStamp = moment.utc(record.timeStamp).toString();
667
+ try {
668
+ const cardHistory = await this.update(cardHistoryID, function(h) {
669
+ h.records.push(record);
670
+ h.bestInterval = h.bestInterval || 0;
671
+ if (areQuestionRecords(h)) {
672
+ h.lapses = getLapses(h.records);
673
+ h.streak = getStreak(h.records);
674
+ } else {
675
+ h.lapses = h.lapses || 0;
676
+ h.streak = h.streak || 0;
677
+ }
678
+ return h;
679
+ });
680
+ cardHistory.records = cardHistory.records.map((record) => {
681
+ const ret = { ...record };
682
+ ret.timeStamp = moment.utc(record.timeStamp);
683
+ return ret;
684
+ });
685
+ return cardHistory;
686
+ } catch (e) {
687
+ const reason = e;
688
+ if (reason.status === 404) try {
689
+ const initCardHistory = {
690
+ _id: cardHistoryID,
691
+ cardID: record.cardID,
692
+ courseID: record.courseID,
693
+ records: [record],
694
+ lapses: 0,
695
+ streak: 0,
696
+ bestInterval: 0
697
+ };
698
+ const putResult = await this.writeDB.put(initCardHistory);
699
+ return {
700
+ ...initCardHistory,
701
+ _rev: putResult.rev
702
+ };
703
+ } catch (creationError) {
704
+ throw new Error(`Failed to create CardHistory for ${cardHistoryID}. Reason: ${creationError}`);
705
+ }
706
+ else throw new Error(`putCardRecord failed because of:
707
+ name:${reason.name}
708
+ error: ${reason.error}
709
+ message: ${reason.message}`);
710
+ }
711
+ }
712
+ async deduplicateReviews() {
713
+ try {
714
+ log("Starting deduplication of scheduled reviews...");
715
+ log(`Remote DB name: ${this.remoteDB.name || "unknown"}`);
716
+ log(`Write DB name: ${this.writeDB.name || "unknown"}`);
717
+ /**
718
+ * Maps the qualified-id of a scheduled review card to
719
+ * the docId of the same scheduled review.
720
+ *
721
+ * EG: {
722
+ * courseId-cardId: 'card_review_2021-06--17:12:165'
723
+ * }
724
+ */
725
+ const reviewsMap = {};
726
+ const duplicateDocIds = [];
727
+ log(`Attempting to query remoteDB for reviewCards/reviewCards. Database: ${this.remoteDB.name || "unknown"}`);
728
+ const scheduledReviews = await this.remoteDB.query("reviewCards/reviewCards");
729
+ log(`Found ${scheduledReviews.rows.length} scheduled reviews to process`);
730
+ scheduledReviews.rows.forEach((r) => {
731
+ const qualifiedCardId = r.value;
732
+ const docId = r.key;
733
+ if (reviewsMap[qualifiedCardId]) {
734
+ log(`Found duplicate scheduled review for card: ${qualifiedCardId}`);
735
+ log(`Marking earlier review ${reviewsMap[qualifiedCardId]} for deletion, keeping ${docId}`);
736
+ duplicateDocIds.push(reviewsMap[qualifiedCardId]);
737
+ reviewsMap[qualifiedCardId] = docId;
738
+ } else reviewsMap[qualifiedCardId] = docId;
739
+ });
740
+ if (duplicateDocIds.length > 0) {
741
+ log(`Removing ${duplicateDocIds.length} duplicate reviews...`);
742
+ const deletePromises = duplicateDocIds.map(async (docId) => {
743
+ try {
744
+ const doc = await this.remoteDB.get(docId);
745
+ await this.writeDB.remove(doc);
746
+ log(`Successfully removed duplicate review: ${docId}`);
747
+ } catch (error) {
748
+ log(`Failed to remove duplicate review ${docId}: ${error}`);
749
+ }
750
+ });
751
+ await Promise.all(deletePromises);
752
+ log(`Deduplication complete. Processed ${duplicateDocIds.length} duplicates`);
753
+ } else log("No duplicate reviews found");
754
+ } catch (error) {
755
+ log(`Error during review deduplication: ${error}`);
756
+ if (error && typeof error === "object" && "status" in error && error.status === 404) {
757
+ log(`Database not found (404) during review deduplication. Database: ${this.remoteDB.name || "unknown"}`);
758
+ log(`This might indicate the user database doesn't exist or the reviewCards view isn't available`);
759
+ }
760
+ if (error && typeof error === "object") log(`Full error details: ${JSON.stringify(error)}`);
761
+ }
762
+ }
763
+ /**
764
+ * Returns a promise of the card IDs that the user has
765
+ * encountered in the past.
766
+ *
767
+ * @param course_id optional specification of individual course
768
+ */
769
+ async getSeenCards(course_id) {
770
+ let filterPrefix = DocTypePrefixes[DocType.CARDRECORD];
771
+ if (course_id) filterPrefix += `-${course_id}-`;
772
+ const docs = await filterAllDocsByPrefix(this.localDB, filterPrefix, { include_docs: false });
773
+ const ret = [];
774
+ docs.rows.forEach((row) => {
775
+ if (row.id.startsWith(filterPrefix)) ret.push(row.id.substr(filterPrefix.length));
776
+ });
777
+ return ret;
778
+ }
779
+ /**
780
+ *
781
+ * @returns A promise of the cards that the user has seen in the past.
782
+ */
783
+ async getHistory() {
784
+ return (await filterAllDocsByPrefix(this.remoteDB, DocTypePrefixes[DocType.CARDRECORD], {
785
+ include_docs: true,
786
+ attachments: false
787
+ })).rows.map((r) => r.doc);
788
+ }
789
+ async updateCourseSettings(course_id, settings) {
790
+ this.getCourseRegistrationsDoc().then((doc) => {
791
+ const crs = doc.courses.find((c) => c.courseID === course_id);
792
+ if (crs) {
793
+ if (crs.settings === null || crs.settings === void 0) crs.settings = {};
794
+ settings.forEach((setting) => {
795
+ crs.settings[setting.key] = setting.value;
796
+ });
797
+ }
798
+ return this.localDB.put(doc);
799
+ });
800
+ }
801
+ async getCourseSettings(course_id) {
802
+ const crsDoc = (await this.getCourseRegistrationsDoc()).courses.find((c) => c.courseID === course_id);
803
+ if (crsDoc) return crsDoc.settings;
804
+ else throw new Error(`getCourseSettings Failed:
805
+ User is not registered for course ${course_id}`);
806
+ }
807
+ async getOrCreateClassroomRegistrationsDoc() {
808
+ let ret;
809
+ try {
810
+ ret = await this.remoteDB.get(BaseUser.DOC_IDS.CLASSROOM_REGISTRATIONS);
811
+ } catch (e) {
812
+ const err = e;
813
+ if (err.status === 404) {
814
+ await this.writeDB.put({
815
+ _id: BaseUser.DOC_IDS.CLASSROOM_REGISTRATIONS,
816
+ registrations: []
817
+ });
818
+ ret = await this.getOrCreateClassroomRegistrationsDoc();
819
+ } else {
820
+ const errorDetails = {
821
+ name: err.name,
822
+ status: err.status,
823
+ message: err.message,
824
+ reason: err.reason,
825
+ error: err.error
826
+ };
827
+ logger.error("Database error in getOrCreateClassroomRegistrationsDoc (private method):", errorDetails);
828
+ throw new Error(`Database error accessing classroom registrations: ${err.message || err.name || "Unknown error"} (status: ${err.status})`);
829
+ }
830
+ }
831
+ logger.debug(`Returning classroom registrations doc: ${JSON.stringify(ret)}`);
832
+ return ret;
833
+ }
834
+ /**
835
+ * Retrieves the list of active classroom IDs where the user is registered as a student.
836
+ *
837
+ * @returns Promise<string[]> - Array of classroom IDs, or empty array if classroom
838
+ * registration document is unavailable due to database errors
839
+ *
840
+ * @description This method gracefully handles database connectivity issues by returning
841
+ * an empty array when the classroom registrations document cannot be accessed.
842
+ * This ensures that users can still access other application features even
843
+ * when classroom functionality is temporarily unavailable.
844
+ */
845
+ async getActiveClasses() {
846
+ try {
847
+ return (await this.getOrCreateClassroomRegistrationsDoc()).registrations.filter((c) => c.registeredAs === "student").map((c) => c.classID);
848
+ } catch (error) {
849
+ logger.warn("Failed to load classroom registrations, continuing without classroom data:", error);
850
+ return [];
851
+ }
852
+ }
853
+ async scheduleCardReview(review) {
854
+ return scheduleCardReviewLocal(this.writeDB, review);
855
+ }
856
+ async removeScheduledCardReview(reviewId) {
857
+ return removeScheduledCardReviewLocal(this.writeDB, reviewId);
858
+ }
859
+ async registerForClassroom(_classId, _registerAs) {
860
+ return registerUserForClassroom(this._username, _classId, _registerAs);
861
+ }
862
+ async dropFromClassroom(classId) {
863
+ return dropUserFromClassroom(this._username, classId);
864
+ }
865
+ async getUserClassrooms() {
866
+ return getUserClassrooms(this._username);
867
+ }
868
+ async updateUserElo(courseId, elo) {
869
+ return updateUserElo(this._username, courseId, elo);
870
+ }
871
+ async getStrategyState(courseId, strategyKey) {
872
+ const docId = buildStrategyStateId(courseId, strategyKey);
873
+ try {
874
+ return (await this.localDB.get(docId)).data;
875
+ } catch (e) {
876
+ if (e.status === 404) {
877
+ if (!this.canMaterializeDefaults()) throw new Error(`Cannot read strategy state '${strategyKey}' for ${this._username}: the local mirror is unavailable (hydration state '${this._hydration.state}').`);
878
+ return null;
879
+ }
880
+ throw e;
881
+ }
882
+ }
883
+ async putStrategyState(courseId, strategyKey, data) {
884
+ const docId = buildStrategyStateId(courseId, strategyKey);
885
+ let existingRev;
886
+ try {
887
+ existingRev = (await this.localDB.get(docId))._rev;
888
+ } catch (e) {
889
+ if (e.status !== 404) throw e;
890
+ }
891
+ const doc = {
892
+ _id: docId,
893
+ _rev: existingRev,
894
+ docType: DocType.STRATEGY_STATE,
895
+ courseId,
896
+ strategyKey,
897
+ data,
898
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
899
+ };
900
+ await this.localDB.put(doc);
901
+ }
902
+ /**
903
+ * Open and close write the same `_id`, so the 409 path is the expected
904
+ * route for the second write, not an error case.
905
+ */
906
+ async putStudySession(doc) {
907
+ try {
908
+ await this.localDB.put(doc);
909
+ } catch (err) {
910
+ if (err.status === 409) {
911
+ const existing = await this.localDB.get(doc._id);
912
+ await this.localDB.put({
913
+ ...doc,
914
+ _rev: existing._rev
915
+ });
916
+ } else throw err;
917
+ }
918
+ }
919
+ async getStudySessions(courseId) {
920
+ const keys = getStartAndEndKeys(courseId ? `${DocTypePrefixes[DocType.STUDY_SESSION]}::${courseId}::` : `${DocTypePrefixes[DocType.STUDY_SESSION]}::`);
921
+ return (await this.localDB.allDocs({
922
+ startkey: keys.startkey,
923
+ endkey: keys.endkey,
924
+ include_docs: true
925
+ })).rows.map((r) => r.doc).filter((d) => !!d).sort((a, b) => b.startTime.localeCompare(a.startTime));
926
+ }
927
+ async putUserOutcome(record) {
928
+ try {
929
+ await this.localDB.put(record);
930
+ } catch (err) {
931
+ if (err.status === 409) {
932
+ record._rev = (await this.localDB.get(record._id))._rev;
933
+ await this.localDB.put(record);
934
+ } else throw err;
935
+ }
936
+ }
937
+ async deleteStrategyState(courseId, strategyKey) {
938
+ const docId = buildStrategyStateId(courseId, strategyKey);
939
+ try {
940
+ const doc = await this.localDB.get(docId);
941
+ await this.localDB.remove(doc);
942
+ } catch (e) {
943
+ if (e.status === 404) return;
944
+ throw e;
945
+ }
946
+ }
947
+ };
948
+ function accomodateGuest() {
949
+ logger.log("[funnel] accomodateGuest() called");
950
+ if (typeof localStorage === "undefined") {
951
+ logger.log("[funnel] localStorage not available (Node.js environment), returning default guest");
952
+ return {
953
+ username: GuestUsername + "nodejs-test",
954
+ firstVisit: true
955
+ };
956
+ }
957
+ const dbUUID = "sk-guest-uuid";
958
+ let firstVisit;
959
+ const existingUUID = localStorage.getItem(dbUUID);
960
+ logger.log("[funnel] Checking localStorage for key:", dbUUID);
961
+ logger.log("[funnel] Existing UUID value:", existingUUID);
962
+ logger.log("[funnel] existingUUID !== null:", existingUUID !== null);
963
+ if (existingUUID !== null) {
964
+ firstVisit = false;
965
+ logger.log(`[funnel] Returning guest ${existingUUID} "logging in".`);
966
+ } else {
967
+ firstVisit = true;
968
+ logger.log("[funnel] No existing UUID, generating new one...");
969
+ const uuid = generateUUID();
970
+ logger.log("[funnel] Generated UUID:", uuid);
971
+ logger.log("[funnel] UUID length:", uuid.length);
972
+ try {
973
+ localStorage.setItem(dbUUID, uuid);
974
+ logger.log("[funnel] Successfully stored UUID in localStorage");
975
+ const verification = localStorage.getItem(dbUUID);
976
+ logger.log("[funnel] Verification read from localStorage:", verification);
977
+ } catch (e) {
978
+ logger.error("[funnel] ERROR storing UUID:", e);
979
+ }
980
+ logger.log(`[funnel] Accommodating a new guest with account: ${uuid}`);
981
+ }
982
+ const finalUUID = localStorage.getItem(dbUUID);
983
+ const finalUsername = GuestUsername + finalUUID;
984
+ logger.log("[funnel] Final UUID from localStorage:", finalUUID);
985
+ logger.log("[funnel] GuestUsername constant:", GuestUsername);
986
+ logger.log("[funnel] Final username to return:", finalUsername);
987
+ return {
988
+ username: finalUsername,
989
+ firstVisit
990
+ };
991
+ function generateUUID() {
992
+ logger.log("[funnel] Inside generateUUID()");
993
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
994
+ const uuid = crypto.randomUUID();
995
+ logger.log("[funnel] Generated UUID using crypto.randomUUID():", uuid);
996
+ return uuid;
997
+ }
998
+ if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
999
+ const bytes = new Uint8Array(16);
1000
+ crypto.getRandomValues(bytes);
1001
+ bytes[6] = bytes[6] & 15 | 64;
1002
+ bytes[8] = bytes[8] & 63 | 128;
1003
+ const uuid = [
1004
+ Array.from(bytes.slice(0, 4)).map((b) => b.toString(16).padStart(2, "0")).join(""),
1005
+ Array.from(bytes.slice(4, 6)).map((b) => b.toString(16).padStart(2, "0")).join(""),
1006
+ Array.from(bytes.slice(6, 8)).map((b) => b.toString(16).padStart(2, "0")).join(""),
1007
+ Array.from(bytes.slice(8, 10)).map((b) => b.toString(16).padStart(2, "0")).join(""),
1008
+ Array.from(bytes.slice(10, 16)).map((b) => b.toString(16).padStart(2, "0")).join("")
1009
+ ].join("-");
1010
+ logger.log("[funnel] Generated UUID using crypto.getRandomValues():", uuid);
1011
+ return uuid;
1012
+ }
1013
+ logger.warn("[funnel] crypto API not available, using timestamp-based UUID (NOT SECURE)");
1014
+ let d = (/* @__PURE__ */ new Date()).getTime();
1015
+ if (typeof performance !== "undefined" && typeof performance.now === "function") d += performance.now();
1016
+ const uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
1017
+ const r = (d + Math.random() * 16) % 16 | 0;
1018
+ d = Math.floor(d / 16);
1019
+ return (c === "x" ? r : r & 3 | 8).toString(16);
1020
+ });
1021
+ logger.log("[funnel] Generated UUID (fallback):", uuid);
1022
+ return uuid;
1023
+ }
1024
+ }
1025
+ const userCoursesDoc = "CourseRegistrations";
1026
+ const userClassroomsDoc = "ClassroomRegistrations";
1027
+ async function getOrCreateClassroomRegistrationsDoc(user) {
1028
+ let ret;
1029
+ try {
1030
+ ret = await getLocalUserDB(user).get(userClassroomsDoc);
1031
+ } catch (e) {
1032
+ const err = e;
1033
+ if (err.status === 404) {
1034
+ await getLocalUserDB(user).put({
1035
+ _id: userClassroomsDoc,
1036
+ registrations: []
1037
+ });
1038
+ ret = await getOrCreateClassroomRegistrationsDoc(user);
1039
+ } else {
1040
+ const errorDetails = {
1041
+ name: err.name,
1042
+ status: err.status,
1043
+ message: err.message,
1044
+ reason: err.reason,
1045
+ error: err.error
1046
+ };
1047
+ logger.error("Database error in getOrCreateClassroomRegistrationsDoc (standalone function):", errorDetails);
1048
+ throw new Error(`Database error accessing classroom registrations: ${err.message || err.name || "Unknown error"} (status: ${err.status})`);
1049
+ }
1050
+ }
1051
+ return ret;
1052
+ }
1053
+ async function getOrCreateCourseRegistrationsDoc(user) {
1054
+ let ret;
1055
+ try {
1056
+ ret = await getLocalUserDB(user).get(userCoursesDoc);
1057
+ } catch (e) {
1058
+ if (e.status === 404) {
1059
+ await getLocalUserDB(user).put({
1060
+ _id: userCoursesDoc,
1061
+ courses: [],
1062
+ studyWeight: {}
1063
+ });
1064
+ ret = await getOrCreateCourseRegistrationsDoc(user);
1065
+ } else throw new Error(`Unexpected error ${JSON.stringify(e)} in getOrCreateCourseRegistrationDoc...`);
1066
+ }
1067
+ return ret;
1068
+ }
1069
+ async function updateUserElo(user, course_id, elo) {
1070
+ const regDoc = await getOrCreateCourseRegistrationsDoc(user);
1071
+ const course = regDoc.courses.find((c) => c.courseID === course_id);
1072
+ course.elo = elo;
1073
+ return getLocalUserDB(user).put(regDoc);
1074
+ }
1075
+ async function registerUserForClassroom(user, classID, registerAs) {
1076
+ log(`Registering user: ${user} in course: ${classID}`);
1077
+ return getOrCreateClassroomRegistrationsDoc(user).then((doc) => {
1078
+ const regItem = {
1079
+ classID,
1080
+ registeredAs: registerAs
1081
+ };
1082
+ if (doc.registrations.filter((reg) => {
1083
+ return reg.classID === regItem.classID && reg.registeredAs === regItem.registeredAs;
1084
+ }).length === 0) doc.registrations.push(regItem);
1085
+ else log(`User ${user} is already registered for class ${classID}`);
1086
+ return getLocalUserDB(user).put(doc);
1087
+ });
1088
+ }
1089
+ async function dropUserFromClassroom(user, classID) {
1090
+ return getOrCreateClassroomRegistrationsDoc(user).then((doc) => {
1091
+ let index = -1;
1092
+ for (let i = 0; i < doc.registrations.length; i++) if (doc.registrations[i].classID === classID) index = i;
1093
+ if (index !== -1) doc.registrations.splice(index, 1);
1094
+ return getLocalUserDB(user).put(doc);
1095
+ });
1096
+ }
1097
+ async function getUserClassrooms(user) {
1098
+ return getOrCreateClassroomRegistrationsDoc(user);
1099
+ }
1100
+ //#endregion
1101
+ export { BaseUser, accomodateGuest };
1102
+
1103
+ //# sourceMappingURL=BaseUserDB.mjs.map