@vue-skuilder/db 0.2.35 → 0.2.37

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 (263) 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-BteiDpxH.d.ts → contentSource-D_E7JaxR.d.ts} +1 -1
  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} +6413 -7738
  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 +694 -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-C_QWzHf-.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} +1 -1
  87. package/dist/diagnostics/index.d.ts +3 -3
  88. package/dist/diagnostics/index.mjs +7 -1042
  89. package/dist/diagnostics/loader.mjs +151 -0
  90. package/dist/diagnostics/loader.mjs.map +1 -0
  91. package/dist/diagnostics/pipeline.mjs +161 -0
  92. package/dist/diagnostics/pipeline.mjs.map +1 -0
  93. package/dist/diagnostics/tagElo.mjs +177 -0
  94. package/dist/diagnostics/tagElo.mjs.map +1 -0
  95. package/dist/diagnostics/text.mjs +174 -0
  96. package/dist/diagnostics/text.mjs.map +1 -0
  97. package/dist/factory.mjs +70 -0
  98. package/dist/factory.mjs.map +1 -0
  99. package/dist/impl/common/BaseUserDB.mjs +1115 -0
  100. package/dist/impl/common/BaseUserDB.mjs.map +1 -0
  101. package/dist/impl/common/userDBHelpers.mjs +49 -0
  102. package/dist/impl/common/userDBHelpers.mjs.map +1 -0
  103. package/dist/impl/common/userDBKeys.mjs +45 -0
  104. package/dist/impl/common/userDBKeys.mjs.map +1 -0
  105. package/dist/impl/couch/CouchDBSyncStrategy.mjs +272 -0
  106. package/dist/impl/couch/CouchDBSyncStrategy.mjs.map +1 -0
  107. package/dist/impl/couch/CourseSyncService.mjs +320 -0
  108. package/dist/impl/couch/CourseSyncService.mjs.map +1 -0
  109. package/dist/impl/couch/PouchDataLayerProvider.mjs +89 -0
  110. package/dist/impl/couch/PouchDataLayerProvider.mjs.map +1 -0
  111. package/dist/impl/couch/adminDB.mjs +61 -0
  112. package/dist/impl/couch/adminDB.mjs.map +1 -0
  113. package/dist/impl/couch/auth.mjs +33 -0
  114. package/dist/impl/couch/auth.mjs.map +1 -0
  115. package/dist/impl/couch/classroomDB.mjs +227 -0
  116. package/dist/impl/couch/classroomDB.mjs.map +1 -0
  117. package/dist/impl/couch/clientCache.mjs +15 -0
  118. package/dist/impl/couch/clientCache.mjs.map +1 -0
  119. package/dist/impl/couch/courseAPI.mjs +197 -0
  120. package/dist/impl/couch/courseAPI.mjs.map +1 -0
  121. package/dist/impl/couch/courseDB.mjs +735 -0
  122. package/dist/impl/couch/courseDB.mjs.map +1 -0
  123. package/dist/impl/couch/courseLookupDB.mjs +94 -0
  124. package/dist/impl/couch/courseLookupDB.mjs.map +1 -0
  125. package/dist/impl/couch/{index.js → index.cjs} +7003 -10358
  126. package/dist/impl/couch/index.cjs.map +1 -0
  127. package/dist/impl/couch/index.d.ts +33 -5
  128. package/dist/impl/couch/index.mjs +152 -12147
  129. package/dist/impl/couch/index.mjs.map +1 -1
  130. package/dist/impl/couch/pouchdb-setup.mjs +15 -0
  131. package/dist/impl/couch/pouchdb-setup.mjs.map +1 -0
  132. package/dist/impl/couch/updateQueue.mjs +101 -0
  133. package/dist/impl/couch/updateQueue.mjs.map +1 -0
  134. package/dist/impl/couch/user-course-relDB.mjs +55 -0
  135. package/dist/impl/couch/user-course-relDB.mjs.map +1 -0
  136. package/dist/impl/static/NoOpSyncStrategy.mjs +49 -0
  137. package/dist/impl/static/NoOpSyncStrategy.mjs.map +1 -0
  138. package/dist/impl/static/StaticDataLayerProvider.mjs +94 -0
  139. package/dist/impl/static/StaticDataLayerProvider.mjs.map +1 -0
  140. package/dist/impl/static/StaticDataUnpacker.mjs +311 -0
  141. package/dist/impl/static/StaticDataUnpacker.mjs.map +1 -0
  142. package/dist/impl/static/courseDB.mjs +368 -0
  143. package/dist/impl/static/courseDB.mjs.map +1 -0
  144. package/dist/impl/static/coursesDB.mjs +38 -0
  145. package/dist/impl/static/coursesDB.mjs.map +1 -0
  146. package/dist/impl/static/{index.js → index.cjs} +2486 -5993
  147. package/dist/impl/static/index.cjs.map +1 -0
  148. package/dist/impl/static/index.d.ts +4 -4
  149. package/dist/impl/static/index.mjs +6 -10741
  150. package/dist/{index-C745YB_6.d.ts → index-BLDpFYG3.d.ts} +1 -1
  151. package/dist/{index.js → index.cjs} +14190 -14249
  152. package/dist/index.cjs.map +1 -0
  153. package/dist/index.d.ts +12 -23
  154. package/dist/index.mjs +38 -16937
  155. package/dist/pouch/{index.js → index.cjs} +5 -1
  156. package/dist/pouch/index.cjs.map +1 -0
  157. package/dist/pouch/index.mjs +2 -19
  158. package/dist/study/ItemQueue.mjs +95 -0
  159. package/dist/study/ItemQueue.mjs.map +1 -0
  160. package/dist/study/MixerDebugger.mjs +303 -0
  161. package/dist/study/MixerDebugger.mjs.map +1 -0
  162. package/dist/study/SessionController.mjs +1187 -0
  163. package/dist/study/SessionController.mjs.map +1 -0
  164. package/dist/study/SessionDebugger.mjs +271 -0
  165. package/dist/study/SessionDebugger.mjs.map +1 -0
  166. package/dist/study/SessionOverlay.mjs +407 -0
  167. package/dist/study/SessionOverlay.mjs.map +1 -0
  168. package/dist/study/SourceMixer.mjs +45 -0
  169. package/dist/study/SourceMixer.mjs.map +1 -0
  170. package/dist/study/SpacedRepetition.mjs +108 -0
  171. package/dist/study/SpacedRepetition.mjs.map +1 -0
  172. package/dist/study/TagFilteredContentSource.mjs +136 -0
  173. package/dist/study/TagFilteredContentSource.mjs.map +1 -0
  174. package/dist/study/services/CardHydrationService.mjs +172 -0
  175. package/dist/study/services/CardHydrationService.mjs.map +1 -0
  176. package/dist/study/services/EloService.mjs +217 -0
  177. package/dist/study/services/EloService.mjs.map +1 -0
  178. package/dist/study/services/ResponseProcessor.mjs +190 -0
  179. package/dist/study/services/ResponseProcessor.mjs.map +1 -0
  180. package/dist/study/services/SrsService.mjs +49 -0
  181. package/dist/study/services/SrsService.mjs.map +1 -0
  182. package/dist/study/services/tagRecent.mjs +65 -0
  183. package/dist/study/services/tagRecent.mjs.map +1 -0
  184. package/dist/{types-DF0JuPbs.d.ts → types-DChCz22D.d.ts} +1 -1
  185. package/dist/{types-legacy-DdVjg81H.d.cts → types-legacy-fT5Y1Wuy.d.ts} +1 -1
  186. package/dist/userDBKeys-ne1g4Xuq.d.ts +16 -0
  187. package/dist/util/Loggable.mjs +14 -0
  188. package/dist/util/Loggable.mjs.map +1 -0
  189. package/dist/util/dataDirectory.mjs +47 -0
  190. package/dist/util/dataDirectory.mjs.map +1 -0
  191. package/dist/util/logger.mjs +86 -0
  192. package/dist/util/logger.mjs.map +1 -0
  193. package/dist/util/migrator/FileSystemAdapter.mjs +18 -0
  194. package/dist/util/migrator/FileSystemAdapter.mjs.map +1 -0
  195. package/dist/util/migrator/StaticToCouchDBMigrator.mjs +428 -0
  196. package/dist/util/migrator/StaticToCouchDBMigrator.mjs.map +1 -0
  197. package/dist/util/migrator/types.mjs +11 -0
  198. package/dist/util/migrator/types.mjs.map +1 -0
  199. package/dist/util/migrator/validation.mjs +334 -0
  200. package/dist/util/migrator/validation.mjs.map +1 -0
  201. package/dist/util/packer/CouchDBToStaticPacker.mjs +438 -0
  202. package/dist/util/packer/CouchDBToStaticPacker.mjs.map +1 -0
  203. package/dist/util/packer/{index.js → index.cjs} +73 -9
  204. package/dist/util/packer/index.cjs.map +1 -0
  205. package/dist/util/packer/index.d.ts +3 -3
  206. package/dist/util/packer/index.mjs +2 -537
  207. package/eslint.config.mjs +9 -1
  208. package/package.json +25 -13
  209. package/rolldown.config.mjs +44 -0
  210. package/src/core/UserDBDebugger.ts +47 -46
  211. package/src/core/navigators/Pipeline.ts +10 -10
  212. package/src/core/navigators/PipelineDebugger.ts +55 -55
  213. package/src/core/navigators/filters/eloDistance.ts +1 -1
  214. package/src/core/navigators/generators/elo.ts +5 -1
  215. package/src/core/navigators/generators/prescribed.ts +42 -16
  216. package/src/core/navigators/index.ts +9 -3
  217. package/src/factory.ts +10 -1
  218. package/src/impl/common/BaseUserDB.ts +16 -5
  219. package/src/impl/common/index.ts +2 -0
  220. package/src/impl/common/userDBHelpers.ts +4 -58
  221. package/src/impl/common/userDBKeys.ts +64 -0
  222. package/src/impl/couch/CourseSyncService.ts +130 -20
  223. package/src/impl/couch/PouchDataLayerProvider.ts +14 -1
  224. package/src/impl/couch/courseAPI.ts +26 -12
  225. package/src/impl/couch/courseDB.ts +35 -15
  226. package/src/impl/couch/index.ts +18 -23
  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/tests/impl/courseSync.test.ts +139 -0
  235. package/tsup.config.ts +24 -21
  236. package/dist/SyncStrategy-BXliog1m.d.cts +0 -116
  237. package/dist/classroomDB-DLTtLZct.d.cts +0 -86
  238. package/dist/contentSource-FQZcZopC.d.cts +0 -2007
  239. package/dist/core/index.d.cts +0 -521
  240. package/dist/core/index.js.map +0 -1
  241. package/dist/core/index.mjs.map +0 -1
  242. package/dist/dataLayerProvider-3y21KtF-.d.cts +0 -61
  243. package/dist/diagnostics/index.d.cts +0 -561
  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-BIum9Ue2.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-BcWVH4ww.d.cts +0 -58
  258. package/dist/types-legacy-DdVjg81H.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
  263. /package/dist/diagnostics/{index.js.map → index.cjs.map} +0 -0
@@ -0,0 +1,64 @@
1
+ // packages/db/src/impl/common/userDBKeys.ts
2
+ //
3
+ // Doc-id and key-range helpers for the user DB. Kept apart from
4
+ // userDBHelpers.ts, which imports pouchdb-setup: importing one of these must
5
+ // not pull PouchDB into a consumer's bundle.
6
+
7
+ import moment from 'moment';
8
+ import { DocType, DocTypePrefixes } from '../../core/types/types-legacy';
9
+
10
+ export const REVIEW_TIME_FORMAT: string = 'YYYY-MM-DD--kk:mm:ss-SSS';
11
+
12
+ /**
13
+ * Build a ScheduledCard `_id` for the given review time.
14
+ *
15
+ * The id suffix is not a mere uniquifier: `getReviewstoDate` PARSES the id
16
+ * (with {@link REVIEW_TIME_FORMAT}) to decide due-ness, so the id is the
17
+ * datum. Anything that writes or rewrites scheduled-card docs (scheduling,
18
+ * user-state snapshot rebasing) must construct ids through this helper —
19
+ * a hand-rolled formatter will get moment's `kk` token (01-24 hours) wrong.
20
+ */
21
+ export function makeScheduledCardId(reviewTime: string | Date | moment.Moment): string {
22
+ return DocTypePrefixes[DocType.SCHEDULED_CARD] + moment.utc(reviewTime).format(REVIEW_TIME_FORMAT);
23
+ }
24
+
25
+ export function hexEncode(str: string): string {
26
+ let hex: string;
27
+ let returnStr: string = '';
28
+
29
+ for (let i = 0; i < str.length; i++) {
30
+ hex = str.charCodeAt(i).toString(16);
31
+ returnStr += ('000' + hex).slice(3);
32
+ }
33
+
34
+ return returnStr;
35
+ }
36
+
37
+ export function filterAllDocsByPrefix<T>(
38
+ db: PouchDB.Database,
39
+ prefix: string,
40
+ opts?: PouchDB.Core.AllDocsOptions
41
+ ) {
42
+ // see couchdb docs 6.2.2:
43
+ // Guide to Views -> Views Collation -> String Ranges
44
+ const options: PouchDB.Core.AllDocsWithinRangeOptions = {
45
+ startkey: prefix,
46
+ endkey: prefix + '￰',
47
+ include_docs: true,
48
+ };
49
+
50
+ if (opts) {
51
+ Object.assign(options, opts);
52
+ }
53
+ return db.allDocs<T>(options);
54
+ }
55
+
56
+ export function getStartAndEndKeys(key: string): {
57
+ startkey: string;
58
+ endkey: string;
59
+ } {
60
+ return {
61
+ startkey: key,
62
+ endkey: key + '￰',
63
+ };
64
+ }
@@ -23,6 +23,15 @@ import type { CourseConfig } from '@vue-skuilder/common';
23
23
  // This avoids propagating per-interaction ELO write noise to every syncing
24
24
  // client. Each client's local snapshot refreshes on the next page load.
25
25
  //
26
+ // A replica that completed a sync on an earlier page load carries a
27
+ // `_local/` marker, and is handed out as ready immediately; its refresh
28
+ // (epoch check, incremental pull, view warming) runs in the background, into
29
+ // the same DB. Sessions may therefore start on the previous visit's data and
30
+ // catch up seconds later. If that refresh finds the remote DB recreated (an
31
+ // epoch change), the replica is NOT destroyed under running readers: the
32
+ // marker is dropped, this page keeps the outdated copy, and the next page
33
+ // load rebuilds it from scratch (the path a device without a replica takes).
34
+ //
26
35
  // Live replication is intentionally NOT supported. The remote course DB
27
36
  // receives high-frequency ELO updates from all concurrent users — live
28
37
  // sync would cause constant re-indexing of local PouchDB views.
@@ -41,6 +50,12 @@ export type CourseSyncState =
41
50
  | 'disabled'
42
51
  | 'error';
43
52
 
53
+ /**
54
+ * Written into the local replica when a sync completes. `_local/` docs don't
55
+ * replicate, so it describes this device's copy.
56
+ */
57
+ const SYNC_MARKER_ID = '_local/sk-course-sync-complete';
58
+
44
59
  /**
45
60
  * Detailed sync status for observability.
46
61
  */
@@ -178,26 +193,11 @@ export class CourseSyncService {
178
193
  async ensureSynced(courseId: string, forceEnabled?: boolean): Promise<void> {
179
194
  const existing = this.entries.get(courseId);
180
195
 
181
- // Already synced — but check if the remote DB has been recreated
182
- // (e.g., after a dev reseed). The seed script writes a `db-epoch`
183
- // doc; if the remote epoch differs from our local copy, the local
184
- // replica is stale and must be destroyed before re-syncing.
196
+ // Ready on this page load. Its epoch was checked on the way (by
197
+ // performSync, or by the background refresh, which keeps an outdated
198
+ // replica rather than destroy it under running sessions).
185
199
  if (existing?.status.state === 'ready' && existing.localDB) {
186
- const stale = await this.isLocalEpochStale(courseId, existing.localDB);
187
- if (!stale) {
188
- return;
189
- }
190
- logger.info(
191
- `[CourseSyncService] Remote DB epoch changed for course ${courseId} — destroying stale local replica`
192
- );
193
- try {
194
- await existing.localDB.destroy();
195
- } catch {
196
- // Ignore cleanup errors
197
- }
198
- existing.localDB = null;
199
- existing.readyPromise = null;
200
- // Fall through to start a fresh sync
200
+ return;
201
201
  }
202
202
 
203
203
  // Already disabled
@@ -218,10 +218,118 @@ export class CourseSyncService {
218
218
  };
219
219
  this.entries.set(courseId, entry);
220
220
 
221
- entry.readyPromise = this.performSync(courseId, entry, forceEnabled);
221
+ entry.readyPromise = this.startSync(courseId, entry, forceEnabled);
222
222
  return entry.readyPromise;
223
223
  }
224
224
 
225
+ /**
226
+ * A replica completed on an earlier page load is ready now, refreshed in the
227
+ * background; anything else goes through a full performSync.
228
+ */
229
+ private async startSync(
230
+ courseId: string,
231
+ entry: SyncEntry,
232
+ forceEnabled?: boolean
233
+ ): Promise<void> {
234
+ const localDB = new pouch(this.localDBName(courseId));
235
+ if (await this.hasSyncMarker(localDB)) {
236
+ entry.localDB = localDB;
237
+ entry.status = { state: 'ready' };
238
+ entry.readyPromise = null;
239
+ logger.info(
240
+ `[CourseSyncService] Using this device's replica of course ${courseId}; refreshing in the background`
241
+ );
242
+ void this.refreshInBackground(courseId, entry, forceEnabled);
243
+ return;
244
+ }
245
+ return this.performSync(courseId, entry, forceEnabled);
246
+ }
247
+
248
+ /**
249
+ * Bring a ready replica up to date without taking it away from readers.
250
+ * Failures leave it ready (and outdated).
251
+ */
252
+ private async refreshInBackground(
253
+ courseId: string,
254
+ entry: SyncEntry,
255
+ forceEnabled?: boolean
256
+ ): Promise<void> {
257
+ const localDB = entry.localDB!;
258
+ try {
259
+ if (!forceEnabled && !(await this.checkLocalSyncEnabled(courseId))) {
260
+ await this.clearSyncMarker(localDB);
261
+ logger.info(
262
+ `[CourseSyncService] Local sync no longer enabled for course ${courseId}; replica kept for this page only`
263
+ );
264
+ return;
265
+ }
266
+
267
+ if (await this.isLocalEpochStale(courseId, localDB)) {
268
+ await this.clearSyncMarker(localDB);
269
+ logger.info(
270
+ `[CourseSyncService] Remote DB recreated for course ${courseId}: keeping the outdated replica ` +
271
+ `for this page; it is rebuilt on the next page load`
272
+ );
273
+ return;
274
+ }
275
+
276
+ const start = Date.now();
277
+ const result = await this.replicate(this.getRemoteDB(courseId), localDB);
278
+ const syncTimeMs = Date.now() - start;
279
+ const warmStart = Date.now();
280
+ await this.warmViewIndices(localDB);
281
+ const viewWarmTimeMs = Date.now() - warmStart;
282
+ await this.writeSyncMarker(localDB);
283
+ entry.status = {
284
+ state: 'ready',
285
+ docsReplicated: result.docs_written,
286
+ syncTimeMs,
287
+ viewWarmTimeMs,
288
+ };
289
+ logger.info(
290
+ `[CourseSyncService] Background refresh of course ${courseId}: ` +
291
+ `${result.docs_written} docs in ${syncTimeMs}ms, views ${viewWarmTimeMs}ms`
292
+ );
293
+ } catch (e) {
294
+ logger.warn(
295
+ `[CourseSyncService] Background refresh of course ${courseId} failed; replica kept as is: ${e}`
296
+ );
297
+ }
298
+ }
299
+
300
+ private async hasSyncMarker(localDB: PouchDB.Database): Promise<boolean> {
301
+ try {
302
+ await localDB.get(SYNC_MARKER_ID);
303
+ return true;
304
+ } catch {
305
+ return false;
306
+ }
307
+ }
308
+
309
+ private async writeSyncMarker(localDB: PouchDB.Database): Promise<void> {
310
+ try {
311
+ let _rev: string | undefined;
312
+ try {
313
+ _rev = (await localDB.get(SYNC_MARKER_ID))._rev;
314
+ } catch {
315
+ // First completion on this device.
316
+ }
317
+ await localDB.put({ _id: SYNC_MARKER_ID, _rev, completedAt: new Date().toISOString() });
318
+ } catch (e) {
319
+ // Costs the next page load the full-sync path, not correctness.
320
+ logger.warn(`[CourseSyncService] Could not write sync marker: ${e}`);
321
+ }
322
+ }
323
+
324
+ private async clearSyncMarker(localDB: PouchDB.Database): Promise<void> {
325
+ try {
326
+ const marker = await localDB.get(SYNC_MARKER_ID);
327
+ await localDB.remove(marker);
328
+ } catch {
329
+ // Absent already.
330
+ }
331
+ }
332
+
225
333
  /**
226
334
  * Get the local PouchDB for a course, or null if not available.
227
335
  *
@@ -328,6 +436,8 @@ export class CourseSyncService {
328
436
  `[CourseSyncService] View indices warmed for course ${courseId} in ${viewWarmTimeMs}ms`
329
437
  );
330
438
 
439
+ await this.writeSyncMarker(localDB);
440
+
331
441
  // Done
332
442
  entry.status = {
333
443
  state: 'ready',
@@ -28,6 +28,14 @@ export class CouchDataLayerProvider implements DataLayerProvider {
28
28
  // or group of courses
29
29
  private _courseIDs: string[] = [];
30
30
 
31
+ /**
32
+ * One CourseDB per course, so its caches (navigator, ELO pool, tags) last
33
+ * across sessions and card hydration. Rebuilt when the local replica it reads
34
+ * from changes (becomes ready, or is replaced); a session keeps the instance
35
+ * it started with.
36
+ */
37
+ private _courseDBs = new Map<string, { db: CourseDB; localDB: PouchDB.Database | null }>();
38
+
31
39
  constructor(coursIDs?: string[]) {
32
40
  if (coursIDs) {
33
41
  this._courseIDs = coursIDs;
@@ -75,7 +83,12 @@ export class CouchDataLayerProvider implements DataLayerProvider {
75
83
  // pass it to CourseDB so reads (pipeline, card hydration) run locally.
76
84
  // Writes always go to the remote DB (handled inside CourseDB).
77
85
  const localDB = CourseSyncService.getInstance().getLocalDB(courseId);
78
- return new CourseDB(courseId, async () => this.getUserDB(), localDB ?? undefined);
86
+ const cached = this._courseDBs.get(courseId);
87
+ if (cached && cached.localDB === localDB) return cached.db;
88
+
89
+ const db = new CourseDB(courseId, async () => this.getUserDB(), localDB ?? undefined);
90
+ this._courseDBs.set(courseId, { db, localDB });
91
+ return db;
79
92
  }
80
93
 
81
94
  /**
@@ -1,6 +1,4 @@
1
- import pouch from './pouchdb-setup';
2
- import { createPouchDBConfig } from '.';
3
- import { ENV } from '@db/factory';
1
+ import { getCourseDB } from '.';
4
2
  // import { DataShape } from '../..base-course/Interfaces/DataShape';
5
3
  import { NameSpacer, ShapeDescriptor } from '@vue-skuilder/common';
6
4
  import { CourseConfig, DataShape } from '@vue-skuilder/common';
@@ -171,14 +169,37 @@ async function addCard(
171
169
  return card;
172
170
  }
173
171
 
172
+ /**
173
+ * CourseConfig reads, cached per course for a few minutes: a study session reads
174
+ * it several times per pipeline run and per card. An edit made elsewhere shows
175
+ * up after the TTL (or a reload); writes through this client invalidate.
176
+ */
177
+ const COURSE_CONFIG_TTL_MS = 5 * 60 * 1000;
178
+ const courseConfigCache = new Map<string, { at: number; config: Promise<CourseConfig> }>();
179
+
180
+ export function invalidateCourseConfigCache(courseID: string): void {
181
+ courseConfigCache.delete(courseID);
182
+ }
183
+
174
184
  export async function getCredentialledCourseConfig(courseID: string): Promise<CourseConfig> {
175
- try {
185
+ const hit = courseConfigCache.get(courseID);
186
+ if (hit && Date.now() - hit.at < COURSE_CONFIG_TTL_MS) {
187
+ // A copy: callers mutate configs (e.g. before writing them back).
188
+ return structuredClone(await hit.config);
189
+ }
190
+
191
+ const config = (async () => {
176
192
  const db = getCourseDB(courseID);
177
193
  const ret = await db.get<CourseConfig>('CourseConfig');
178
194
  ret.courseID = courseID;
179
- logger.info(`Returning course config: ${JSON.stringify(ret)}`);
195
+ logger.debug(`Fetched course config for ${courseID}`);
180
196
  return ret;
197
+ })();
198
+ courseConfigCache.set(courseID, { at: Date.now(), config });
199
+ try {
200
+ return structuredClone(await config);
181
201
  } catch (e) {
202
+ courseConfigCache.delete(courseID);
182
203
  logger.error(`Error fetching config for ${courseID}:`, e);
183
204
  throw e;
184
205
  }
@@ -275,10 +296,3 @@ export function getTagID(tagName: string): string {
275
296
  }
276
297
  }
277
298
 
278
- export function getCourseDB(courseID: string): PouchDB.Database {
279
- const dbName = `coursedb-${courseID}`;
280
- return new pouch(
281
- ENV.COUCHDB_SERVER_PROTOCOL + '://' + ENV.COUCHDB_SERVER_URL + dbName,
282
- createPouchDBConfig()
283
- );
284
- }
@@ -25,7 +25,13 @@ import {
25
25
  } from '../../core/types/types-legacy';
26
26
  import { logger } from '../../util/logger';
27
27
  import { GET_CACHED } from './clientCache';
28
- import { addNote55, addTagToCard, getCredentialledCourseConfig, getTagID } from './courseAPI';
28
+ import {
29
+ addNote55,
30
+ addTagToCard,
31
+ getCredentialledCourseConfig,
32
+ getTagID,
33
+ invalidateCourseConfigCache,
34
+ } from './courseAPI';
29
35
  import { DataLayerResult } from '@db/core/types/db';
30
36
  import { PouchError } from './types';
31
37
  import CourseLookup from './courseLookupDB';
@@ -401,12 +407,8 @@ above:\n${above.rows.map((r) => `\t${r.id}-${r.key}\n`)}`;
401
407
  }
402
408
 
403
409
  async getAppliedTags(cardId: string): Promise<PouchDB.Query.Response<TagStub>> {
404
- const ret = await getAppliedTags(this.id, cardId);
405
- if (ret) {
406
- return ret;
407
- } else {
408
- throw new Error(`Failed to find tags for card ${this.id}-${cardId}`);
409
- }
410
+ // this.db: the local replica when one is ready (the module function is remote).
411
+ return this.db.query<TagStub>('getTags', { startkey: cardId, endkey: cardId });
410
412
  }
411
413
 
412
414
  async getAppliedTagsBatch(cardIds: string[]): Promise<Map<string, string[]>> {
@@ -491,7 +493,8 @@ above:\n${above.rows.map((r) => `\t${r.id}-${r.key}\n`)}`;
491
493
  }
492
494
 
493
495
  async getCourseTagStubs(): Promise<PouchDB.Core.AllDocsResponse<Tag>> {
494
- return getCourseTagStubs(this.id);
496
+ // this.db: the local replica when one is ready (the module function is remote).
497
+ return filterAllDocsByPrefix<Tag>(this.db, DocType.TAG.valueOf() + '-');
495
498
  }
496
499
 
497
500
  async addNote(
@@ -690,8 +693,16 @@ above:\n${above.rows.map((r) => `\t${r.id}-${r.key}\n`)}`;
690
693
  private _eloPoolCache: {
691
694
  rows: (QualifiedCardID & { elo?: number })[];
692
695
  fetchedAt: number;
696
+ /** The ELO the pool was fetched around. */
697
+ centerElo: number;
693
698
  } | null = null;
694
699
  private readonly _eloPoolTtlMs = 5 * 60 * 1000;
700
+ /**
701
+ * How far the target may move from the pool's centre before the pool is
702
+ * refetched. Well above a learner's in-session roam; a different learner (or
703
+ * a far-off explicit ELO) on the same CourseDB gets a pool of their own.
704
+ */
705
+ private readonly _eloPoolMaxDrift = 200;
695
706
 
696
707
  /**
697
708
  * Cached assembled navigator (Pipeline). createNavigator() reads strategy
@@ -827,14 +838,18 @@ above:\n${above.rows.map((r) => `\t${r.id}-${r.key}\n`)}`;
827
838
  const nowMs = Date.now();
828
839
  let cacheStatus: 'hit' | 'miss' | 'refresh' = 'hit';
829
840
 
830
- if (!this._eloPoolCache || nowMs - this._eloPoolCache.fetchedAt > this._eloPoolTtlMs) {
841
+ if (
842
+ !this._eloPoolCache ||
843
+ nowMs - this._eloPoolCache.fetchedAt > this._eloPoolTtlMs ||
844
+ Math.abs(targetElo - this._eloPoolCache.centerElo) > this._eloPoolMaxDrift
845
+ ) {
831
846
  // MISS: pay the (reindexing) view query once, then cache the raw pool.
832
847
  // Guard: never cache an EMPTY pool. A cold-DB-open or sync-race fetch can
833
848
  // transiently return [], and caching it would starve the session for the
834
849
  // whole TTL. Leaving the cache untouched lets the next call retry.
835
850
  const fetched = await this.getCardsByELO(targetElo, POOL_SIZE);
836
851
  if (fetched.length > 0) {
837
- this._eloPoolCache = { rows: fetched, fetchedAt: nowMs };
852
+ this._eloPoolCache = { rows: fetched, fetchedAt: nowMs, centerElo: targetElo };
838
853
  }
839
854
  cacheStatus = 'miss';
840
855
  }
@@ -863,7 +878,7 @@ above:\n${above.rows.map((r) => `\t${r.id}-${r.key}\n`)}`;
863
878
  if (cards.length < options.limit && (cacheStatus === 'hit' || !this._eloPoolCache)) {
864
879
  const fetched = await this.getCardsByELO(targetElo, POOL_SIZE);
865
880
  if (fetched.length > 0) {
866
- this._eloPoolCache = { rows: fetched, fetchedAt: nowMs };
881
+ this._eloPoolCache = { rows: fetched, fetchedAt: nowMs, centerElo: targetElo };
867
882
  }
868
883
  cards = rankAgainstCurrentElo();
869
884
  cacheStatus = 'refresh';
@@ -1149,12 +1164,17 @@ ${JSON.stringify(config)}
1149
1164
  `);
1150
1165
 
1151
1166
  const db = getCourseDB(courseID);
1167
+ invalidateCourseConfigCache(courseID);
1152
1168
  const old = await getCredentialledCourseConfig(courseID);
1153
1169
 
1154
- return await db.put<CourseConfig>({
1155
- ...config,
1156
- _rev: (old as any)._rev,
1157
- });
1170
+ try {
1171
+ return await db.put<CourseConfig>({
1172
+ ...config,
1173
+ _rev: (old as any)._rev,
1174
+ });
1175
+ } finally {
1176
+ invalidateCourseConfigCache(courseID);
1177
+ }
1158
1178
  }
1159
1179
 
1160
1180
  function isSuccessRow<T>(
@@ -12,32 +12,16 @@ import moment, { Moment } from 'moment';
12
12
  import { logger } from '@db/util/logger';
13
13
 
14
14
  import pouch from './pouchdb-setup';
15
+ import { hexEncode } from '../common/userDBKeys';
15
16
 
16
17
  import { ScheduledCard } from '@db/core/types/user';
17
- import process from 'process';
18
-
19
- const isBrowser = typeof window !== 'undefined';
20
-
21
- if (isBrowser) {
22
- (window as any).process = process; // required as a fix for pouchdb - see #18
23
- }
24
18
 
25
19
  const expiryDocID: string = 'GuestAccountExpirationDate';
26
20
 
27
21
  const GUEST_LOCAL_DB = `userdb-${GuestUsername}`;
28
22
  export const localUserDB: PouchDB.Database = new pouch(GUEST_LOCAL_DB);
29
23
 
30
- export function hexEncode(str: string): string {
31
- let hex: string;
32
- let returnStr: string = '';
33
-
34
- for (let i = 0; i < str.length; i++) {
35
- hex = str.charCodeAt(i).toString(16);
36
- returnStr += ('000' + hex).slice(3);
37
- }
38
-
39
- return returnStr;
40
- }
24
+ export { hexEncode };
41
25
  const pouchDBincludeCredentialsConfig: PouchDB.Configuration.RemoteDatabaseConfiguration = {
42
26
  fetch(url: string | Request, opts: RequestInit): Promise<Response> {
43
27
  opts.credentials = 'include';
@@ -85,12 +69,23 @@ function getCouchDB(dbName: string): PouchDB.Database {
85
69
  );
86
70
  }
87
71
 
72
+ const courseDBHandles = new Map<string, PouchDB.Database>();
73
+
74
+ /**
75
+ * The remote course DB, one handle per URL for the page's lifetime.
76
+ *
77
+ * `skip_setup`: a fresh handle otherwise checks the DB exists (and would try to
78
+ * create it) before its first request: one extra round trip per handle. Course
79
+ * DBs are only created server-side (express), never through this handle.
80
+ */
88
81
  export function getCourseDB(courseID: string): PouchDB.Database {
89
- // todo: keep a cache of opened courseDBs? need to benchmark this somehow
90
- return new pouch(
91
- ENV.COUCHDB_SERVER_PROTOCOL + '://' + ENV.COUCHDB_SERVER_URL + 'coursedb-' + courseID,
92
- createPouchDBConfig()
93
- );
82
+ const url = ENV.COUCHDB_SERVER_PROTOCOL + '://' + ENV.COUCHDB_SERVER_URL + 'coursedb-' + courseID;
83
+ let db = courseDBHandles.get(url);
84
+ if (!db) {
85
+ db = new pouch(url, { ...createPouchDBConfig(), skip_setup: true });
86
+ courseDBHandles.set(url, db);
87
+ }
88
+ return db;
94
89
  }
95
90
 
96
91
  export async function getLatestVersion() {
@@ -1,6 +1,14 @@
1
1
  import PouchDB from 'pouchdb';
2
2
  import PouchDBFind from 'pouchdb-find';
3
3
  import PouchDBAuth from '@nilock2/pouchdb-authentication';
4
+ import process from 'process';
5
+
6
+ // PouchDB expects a global `process` in browsers (#18). Set here, beside the
7
+ // plugin registration, so every path to PouchDB gets it. (This module is in
8
+ // package.json's "sideEffects".)
9
+ if (typeof window !== 'undefined') {
10
+ (window as unknown as { process: unknown }).process = process;
11
+ }
4
12
 
5
13
  // Register plugins
6
14
  PouchDB.plugin(PouchDBFind);
package/src/index.ts CHANGED
@@ -17,7 +17,7 @@ export * from './factory';
17
17
  // by the due-review read path, so out-of-tree writers (e.g. user-state
18
18
  // snapshot rebasing) must build ids with this rather than reimplementing the
19
19
  // moment format.
20
- export { REVIEW_TIME_FORMAT, makeScheduledCardId } from './impl/common/userDBHelpers';
20
+ export { REVIEW_TIME_FORMAT, makeScheduledCardId } from './impl/common/userDBKeys';
21
21
 
22
22
  // Export CouchDB user types for use in Express backend
23
23
  export type {