@vue-skuilder/db 0.2.35 → 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 (258) 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} +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-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 +1103 -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 +242 -0
  108. package/dist/impl/couch/CourseSyncService.mjs.map +1 -0
  109. package/dist/impl/couch/PouchDataLayerProvider.mjs +74 -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 +183 -0
  120. package/dist/impl/couch/courseAPI.mjs.map +1 -0
  121. package/dist/impl/couch/courseDB.mjs +729 -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} +6911 -10367
  126. package/dist/impl/couch/index.cjs.map +1 -0
  127. package/dist/impl/couch/index.d.ts +12 -5
  128. package/dist/impl/couch/index.mjs +134 -12146
  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} +2461 -5992
  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} +14070 -14239
  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/index.ts +9 -3
  216. package/src/factory.ts +10 -1
  217. package/src/impl/common/BaseUserDB.ts +1 -3
  218. package/src/impl/common/index.ts +2 -0
  219. package/src/impl/common/userDBHelpers.ts +4 -58
  220. package/src/impl/common/userDBKeys.ts +64 -0
  221. package/src/impl/couch/courseDB.ts +15 -3
  222. package/src/impl/couch/index.ts +2 -18
  223. package/src/impl/couch/pouchdb-setup.ts +8 -0
  224. package/src/index.ts +1 -1
  225. package/src/study/MixerDebugger.ts +46 -46
  226. package/src/study/SessionDebugger.ts +20 -20
  227. package/src/study/SessionOverlay.ts +4 -4
  228. package/src/util/logger.ts +112 -13
  229. package/tests/core/navigators/eloGenerator.test.ts +36 -0
  230. package/tsup.config.ts +24 -21
  231. package/dist/SyncStrategy-BXliog1m.d.cts +0 -116
  232. package/dist/classroomDB-DLTtLZct.d.cts +0 -86
  233. package/dist/contentSource-FQZcZopC.d.cts +0 -2007
  234. package/dist/core/index.d.cts +0 -521
  235. package/dist/core/index.js.map +0 -1
  236. package/dist/core/index.mjs.map +0 -1
  237. package/dist/dataLayerProvider-3y21KtF-.d.cts +0 -61
  238. package/dist/diagnostics/index.d.cts +0 -561
  239. package/dist/diagnostics/index.mjs.map +0 -1
  240. package/dist/impl/couch/index.d.cts +0 -620
  241. package/dist/impl/couch/index.js.map +0 -1
  242. package/dist/impl/static/index.d.cts +0 -232
  243. package/dist/impl/static/index.js.map +0 -1
  244. package/dist/impl/static/index.mjs.map +0 -1
  245. package/dist/index-BIum9Ue2.d.cts +0 -137
  246. package/dist/index.d.cts +0 -1663
  247. package/dist/index.js.map +0 -1
  248. package/dist/index.mjs.map +0 -1
  249. package/dist/pouch/index.d.cts +0 -1
  250. package/dist/pouch/index.js.map +0 -1
  251. package/dist/pouch/index.mjs.map +0 -1
  252. package/dist/types-BcWVH4ww.d.cts +0 -58
  253. package/dist/types-legacy-DdVjg81H.d.ts +0 -168
  254. package/dist/util/packer/index.d.cts +0 -5
  255. package/dist/util/packer/index.js.map +0 -1
  256. package/dist/util/packer/index.mjs.map +0 -1
  257. package/src/study/getCardDataShape.ts +0 -34
  258. /package/dist/diagnostics/{index.js.map → index.cjs.map} +0 -0
@@ -478,16 +478,16 @@ function formatProvenance(provenance: StrategyContribution[]): string {
478
478
  function printRunSummary(run: PipelineRunReport): void {
479
479
  // eslint-disable-next-line no-console
480
480
  console.group(`🔍 Pipeline Run: ${run.courseId} (${run.courseName || 'unnamed'})`);
481
- logger.info(`Run ID: ${run.runId}`);
482
- logger.info(`Time: ${run.timestamp.toISOString()}`);
483
- logger.info(`User ELO: ${run.userElo ?? 'unknown'}`);
484
- logger.info(`Generator: ${run.generatorName} → ${run.generatedCount} candidates`);
481
+ logger.print(`Run ID: ${run.runId}`);
482
+ logger.print(`Time: ${run.timestamp.toISOString()}`);
483
+ logger.print(`User ELO: ${run.userElo ?? 'unknown'}`);
484
+ logger.print(`Generator: ${run.generatorName} → ${run.generatedCount} candidates`);
485
485
 
486
486
  if (run.generators && run.generators.length > 0) {
487
487
  // eslint-disable-next-line no-console
488
488
  console.group('Generator breakdown:');
489
489
  for (const g of run.generators) {
490
- logger.info(
490
+ logger.print(
491
491
  ` ${g.name}: ${g.cardCount} cards (${g.newCount} new, ${g.reviewCount} reviews, top: ${g.topScore.toFixed(2)})`
492
492
  );
493
493
  }
@@ -499,13 +499,13 @@ function printRunSummary(run: PipelineRunReport): void {
499
499
  // eslint-disable-next-line no-console
500
500
  console.group('Filter impact:');
501
501
  for (const f of run.filters) {
502
- logger.info(` ${f.name}: ↑${f.boosted} ↓${f.penalized} =${f.passed} ✕${f.removed}`);
502
+ logger.print(` ${f.name}: ↑${f.boosted} ↓${f.penalized} =${f.passed} ✕${f.removed}`);
503
503
  }
504
504
  // eslint-disable-next-line no-console
505
505
  console.groupEnd();
506
506
  }
507
507
 
508
- logger.info(
508
+ logger.print(
509
509
  `Result: ${run.finalCount} cards selected (${run.newSelected} new, ${run.reviewsSelected} reviews)`
510
510
  );
511
511
  // eslint-disable-next-line no-console
@@ -805,7 +805,7 @@ export const pipelineDebugAPI = {
805
805
  */
806
806
  showRun(idOrIndex: string | number = 0): void {
807
807
  if (runHistory.length === 0) {
808
- logger.info('[Pipeline Debug] No runs captured yet.');
808
+ logger.print('[Pipeline Debug] No runs captured yet.');
809
809
  return;
810
810
  }
811
811
 
@@ -814,7 +814,7 @@ export const pipelineDebugAPI = {
814
814
  if (typeof idOrIndex === 'number') {
815
815
  run = runHistory[idOrIndex];
816
816
  if (!run) {
817
- logger.info(
817
+ logger.print(
818
818
  `[Pipeline Debug] No run found at index ${idOrIndex}. History length: ${runHistory.length}`
819
819
  );
820
820
  return;
@@ -822,7 +822,7 @@ export const pipelineDebugAPI = {
822
822
  } else {
823
823
  run = runHistory.find((r) => r.runId.endsWith(idOrIndex));
824
824
  if (!run) {
825
- logger.info(`[Pipeline Debug] No run found matching ID '${idOrIndex}'.`);
825
+ logger.print(`[Pipeline Debug] No run found matching ID '${idOrIndex}'.`);
826
826
  return;
827
827
  }
828
828
  }
@@ -846,16 +846,16 @@ export const pipelineDebugAPI = {
846
846
  if (card) {
847
847
  // eslint-disable-next-line no-console
848
848
  console.group(`🎴 Card: ${cardId}`);
849
- logger.info(`Course: ${card.courseId}`);
850
- logger.info(`Origin: ${card.origin}`);
851
- logger.info(`Card ELO: ${card.cardElo ?? 'unknown'} | User ELO: ${run.userElo ?? 'unknown'}`);
852
- logger.info(`Final score: ${card.finalScore.toFixed(3)}`);
853
- logger.info(`Selected: ${card.selected ? 'Yes ✅' : 'No ❌'}`);
849
+ logger.print(`Course: ${card.courseId}`);
850
+ logger.print(`Origin: ${card.origin}`);
851
+ logger.print(`Card ELO: ${card.cardElo ?? 'unknown'} | User ELO: ${run.userElo ?? 'unknown'}`);
852
+ logger.print(`Final score: ${card.finalScore.toFixed(3)}`);
853
+ logger.print(`Selected: ${card.selected ? 'Yes ✅' : 'No ❌'}`);
854
854
  if (card.tags && card.tags.length > 0) {
855
- logger.info(`Tags (${card.tags.length}): ${card.tags.join(', ')}`);
855
+ logger.print(`Tags (${card.tags.length}): ${card.tags.join(', ')}`);
856
856
  }
857
- logger.info('Provenance:');
858
- logger.info(formatProvenance(card.provenance));
857
+ logger.print('Provenance:');
858
+ logger.print(formatProvenance(card.provenance));
859
859
  // eslint-disable-next-line no-console
860
860
  console.groupEnd();
861
861
  return;
@@ -866,13 +866,13 @@ export const pipelineDebugAPI = {
866
866
  // breadcrumb rather than a flat "not found".
867
867
  const runsWithTails = runHistory.filter((r) => r.discardedTail && r.discardedTail.count > 0);
868
868
  if (runsWithTails.length > 0) {
869
- logger.info(
869
+ logger.print(
870
870
  `[Pipeline Debug] Card '${cardId}' not found in retained cards. ` +
871
871
  `${runsWithTails.length} run(s) have discarded tails that were not retained — ` +
872
872
  `the card may have been a low-score candidate. See run.discardedTail for ranges.`
873
873
  );
874
874
  } else {
875
- logger.info(`[Pipeline Debug] Card '${cardId}' not found in recent runs.`);
875
+ logger.print(`[Pipeline Debug] Card '${cardId}' not found in recent runs.`);
876
876
  }
877
877
  },
878
878
 
@@ -881,7 +881,7 @@ export const pipelineDebugAPI = {
881
881
  */
882
882
  explainReviews(): void {
883
883
  if (runHistory.length === 0) {
884
- logger.info('[Pipeline Debug] No runs captured yet.');
884
+ logger.print('[Pipeline Debug] No runs captured yet.');
885
885
  return;
886
886
  }
887
887
 
@@ -896,10 +896,10 @@ export const pipelineDebugAPI = {
896
896
  const selectedReviews = allReviews.filter((c) => c.selected);
897
897
 
898
898
  if (allReviews.length === 0) {
899
- logger.info('❌ No reviews were generated. Check SRS logs for why.');
899
+ logger.print('❌ No reviews were generated. Check SRS logs for why.');
900
900
  } else if (selectedReviews.length === 0) {
901
- logger.info(`⚠️ ${allReviews.length} reviews generated but none selected.`);
902
- logger.info('Possible reasons:');
901
+ logger.print(`⚠️ ${allReviews.length} reviews generated but none selected.`);
902
+ logger.print('Possible reasons:');
903
903
 
904
904
  // Check if new cards scored higher
905
905
  const topNewScore = Math.max(
@@ -909,7 +909,7 @@ export const pipelineDebugAPI = {
909
909
  const topReviewScore = Math.max(...allReviews.map((c) => c.finalScore), 0);
910
910
 
911
911
  if (topReviewScore < topNewScore) {
912
- logger.info(
912
+ logger.print(
913
913
  ` - New cards scored higher (top new: ${topNewScore.toFixed(2)}, top review: ${topReviewScore.toFixed(2)})`
914
914
  );
915
915
  }
@@ -917,15 +917,15 @@ export const pipelineDebugAPI = {
917
917
  // Show top review that didn't make it
918
918
  const topReview = allReviews.sort((a, b) => b.finalScore - a.finalScore)[0];
919
919
  if (topReview) {
920
- logger.info(` - Top review score: ${topReview.finalScore.toFixed(3)}`);
921
- logger.info(' - Its provenance:');
922
- logger.info(formatProvenance(topReview.provenance));
920
+ logger.print(` - Top review score: ${topReview.finalScore.toFixed(3)}`);
921
+ logger.print(' - Its provenance:');
922
+ logger.print(formatProvenance(topReview.provenance));
923
923
  }
924
924
  } else {
925
- logger.info(`✅ ${selectedReviews.length}/${allReviews.length} reviews selected.`);
926
- logger.info('Top selected review:');
925
+ logger.print(`✅ ${selectedReviews.length}/${allReviews.length} reviews selected.`);
926
+ logger.print('Top selected review:');
927
927
  const topSelected = selectedReviews.sort((a, b) => b.finalScore - a.finalScore)[0];
928
- logger.info(formatProvenance(topSelected.provenance));
928
+ logger.print(formatProvenance(topSelected.provenance));
929
929
  }
930
930
 
931
931
  // eslint-disable-next-line no-console
@@ -948,7 +948,7 @@ export const pipelineDebugAPI = {
948
948
  */
949
949
  showPrescribed(groupId?: string): void {
950
950
  if (runHistory.length === 0) {
951
- logger.info('[Pipeline Debug] No runs captured yet.');
951
+ logger.print('[Pipeline Debug] No runs captured yet.');
952
952
  return;
953
953
  }
954
954
 
@@ -961,7 +961,7 @@ export const pipelineDebugAPI = {
961
961
  console.group(`🧭 Prescribed Debug (${run.courseId})`);
962
962
 
963
963
  if (prescribedCards.length === 0) {
964
- logger.info('No prescribed-generated cards were present in the most recent run.');
964
+ logger.print('No prescribed-generated cards were present in the most recent run.');
965
965
  // eslint-disable-next-line no-console
966
966
  console.groupEnd();
967
967
  return;
@@ -1003,7 +1003,7 @@ export const pipelineDebugAPI = {
1003
1003
  .sort((a, b) => Number(b.finalScore) - Number(a.finalScore));
1004
1004
 
1005
1005
  if (rows.length === 0) {
1006
- logger.info(
1006
+ logger.print(
1007
1007
  `[Pipeline Debug] No prescribed cards matched group '${groupId}' in the most recent run.`
1008
1008
  );
1009
1009
  // eslint-disable-next-line no-console
@@ -1042,18 +1042,18 @@ export const pipelineDebugAPI = {
1042
1042
  }
1043
1043
  }
1044
1044
 
1045
- logger.info(`Prescribed cards in run: ${rows.length}`);
1046
- logger.info(`Selected prescribed cards: ${selectedRows.length}`);
1047
- logger.info(
1045
+ logger.print(`Prescribed cards in run: ${rows.length}`);
1046
+ logger.print(`Selected prescribed cards: ${selectedRows.length}`);
1047
+ logger.print(
1048
1048
  `Blocked prescribed targets referenced: ${blockedTargetSet.size > 0 ? [...blockedTargetSet].join(', ') : 'none'}`
1049
1049
  );
1050
- logger.info(
1050
+ logger.print(
1051
1051
  `Resolved support tags referenced: ${supportTagSet.size > 0 ? [...supportTagSet].join(', ') : 'none'}`
1052
1052
  );
1053
- logger.info(
1053
+ logger.print(
1054
1054
  `Authored support cards emitted: ${authoredSupportSet.size > 0 ? [...authoredSupportSet].join(', ') : 'none'}`
1055
1055
  );
1056
- logger.info(
1056
+ logger.print(
1057
1057
  `Discovered support cards emitted: ${discoveredSupportSet.size > 0 ? [...discoveredSupportSet].join(', ') : 'none'}`
1058
1058
  );
1059
1059
 
@@ -1066,7 +1066,7 @@ export const pipelineDebugAPI = {
1066
1066
  */
1067
1067
  listRuns(): void {
1068
1068
  if (runHistory.length === 0) {
1069
- logger.info('[Pipeline Debug] No runs captured yet.');
1069
+ logger.print('[Pipeline Debug] No runs captured yet.');
1070
1070
  return;
1071
1071
  }
1072
1072
 
@@ -1089,8 +1089,8 @@ export const pipelineDebugAPI = {
1089
1089
  */
1090
1090
  export(): string {
1091
1091
  const json = JSON.stringify(runHistory, null, 2);
1092
- logger.info('[Pipeline Debug] Run history exported. Copy the returned string or use:');
1093
- logger.info(' copy(window.skuilder.pipeline.export())');
1092
+ logger.print('[Pipeline Debug] Run history exported. Copy the returned string or use:');
1093
+ logger.print(' copy(window.skuilder.pipeline.export())');
1094
1094
  return json;
1095
1095
  },
1096
1096
 
@@ -1099,7 +1099,7 @@ export const pipelineDebugAPI = {
1099
1099
  */
1100
1100
  clear(): void {
1101
1101
  runHistory.length = 0;
1102
- logger.info('[Pipeline Debug] Run history cleared.');
1102
+ logger.print('[Pipeline Debug] Run history cleared.');
1103
1103
  },
1104
1104
 
1105
1105
  /**
@@ -1111,7 +1111,7 @@ export const pipelineDebugAPI = {
1111
1111
  showRegistry(): void {
1112
1112
  const names = getRegisteredNavigatorNames();
1113
1113
  if (names.length === 0) {
1114
- logger.info('[Pipeline Debug] Navigator registry is empty.');
1114
+ logger.print('[Pipeline Debug] Navigator registry is empty.');
1115
1115
  return;
1116
1116
  }
1117
1117
 
@@ -1147,26 +1147,26 @@ export const pipelineDebugAPI = {
1147
1147
  this.showRegistry();
1148
1148
 
1149
1149
  if (runHistory.length === 0) {
1150
- logger.info('[Pipeline Debug] No pipeline runs captured yet — cannot show strategy doc mapping.');
1150
+ logger.print('[Pipeline Debug] No pipeline runs captured yet — cannot show strategy doc mapping.');
1151
1151
  return;
1152
1152
  }
1153
1153
 
1154
1154
  const run = runHistory[0];
1155
1155
  // eslint-disable-next-line no-console
1156
1156
  console.group('🔌 Pipeline Strategy Mapping (last run)');
1157
- logger.info(`Generator: ${run.generatorName}`);
1157
+ logger.print(`Generator: ${run.generatorName}`);
1158
1158
  if (run.generators && run.generators.length > 0) {
1159
1159
  for (const g of run.generators) {
1160
- logger.info(` 📥 ${g.name}: ${g.cardCount} cards (${g.newCount} new, ${g.reviewCount} reviews)`);
1160
+ logger.print(` 📥 ${g.name}: ${g.cardCount} cards (${g.newCount} new, ${g.reviewCount} reviews)`);
1161
1161
  }
1162
1162
  }
1163
1163
  if (run.filters.length > 0) {
1164
- logger.info('Filters:');
1164
+ logger.print('Filters:');
1165
1165
  for (const f of run.filters) {
1166
- logger.info(` 🔸 ${f.name}: ↑${f.boosted} ↓${f.penalized} =${f.passed} ✕${f.removed}`);
1166
+ logger.print(` 🔸 ${f.name}: ↑${f.boosted} ↓${f.penalized} =${f.passed} ✕${f.removed}`);
1167
1167
  }
1168
1168
  } else {
1169
- logger.info('Filters: (none)');
1169
+ logger.print('Filters: (none)');
1170
1170
  }
1171
1171
  // eslint-disable-next-line no-console
1172
1172
  console.groupEnd();
@@ -1182,7 +1182,7 @@ export const pipelineDebugAPI = {
1182
1182
  */
1183
1183
  async diagnoseCardSpace(threshold?: number): Promise<CardSpaceDiagnosis | null> {
1184
1184
  if (!_activePipeline) {
1185
- logger.info('[Pipeline Debug] No active pipeline. Run a session first.');
1185
+ logger.print('[Pipeline Debug] No active pipeline. Run a session first.');
1186
1186
  return null;
1187
1187
  }
1188
1188
  return _activePipeline.diagnoseCardSpace({ threshold });
@@ -1196,13 +1196,13 @@ export const pipelineDebugAPI = {
1196
1196
  */
1197
1197
  async showTagElo(tagFilter?: string | string[]): Promise<void> {
1198
1198
  if (!_activePipeline) {
1199
- logger.info('[Pipeline Debug] No active pipeline. Run a session first.');
1199
+ logger.print('[Pipeline Debug] No active pipeline. Run a session first.');
1200
1200
  return;
1201
1201
  }
1202
1202
  const status = await _activePipeline.getTagEloStatus(tagFilter);
1203
1203
  const entries = Object.entries(status).sort(([a], [b]) => a.localeCompare(b));
1204
1204
  if (entries.length === 0) {
1205
- logger.info(`[Pipeline Debug] No tag ELO data found${tagFilter ? ` for pattern: ${tagFilter}` : ''}.`);
1205
+ logger.print(`[Pipeline Debug] No tag ELO data found${tagFilter ? ` for pattern: ${tagFilter}` : ''}.`);
1206
1206
  return;
1207
1207
  }
1208
1208
  // eslint-disable-next-line no-console
@@ -1304,7 +1304,7 @@ export const pipelineDebugAPI = {
1304
1304
  * Show help.
1305
1305
  */
1306
1306
  help(): void {
1307
- logger.info(`
1307
+ logger.print(`
1308
1308
  🔧 Pipeline Debug API
1309
1309
 
1310
1310
  Commands:
@@ -159,7 +159,7 @@ export function mountMultiDimEloToggle(): void {
159
159
  } catch (e) {
160
160
  logger.warn(`[EloDistance] multiDimElo not persisted (localStorage unavailable): ${e}`);
161
161
  }
162
- logger.info(
162
+ logger.print(
163
163
  `[EloDistance] multiDimElo ${multiDimElo ? 'on: tag-aware' : 'off: per strategy config'}` +
164
164
  ' ELO distance from the next replan'
165
165
  );
@@ -83,9 +83,13 @@ export default class ELONavigator extends ContentNavigator implements CardGenera
83
83
  ]);
84
84
  const notNew = new Set([...activeCards.map((ac) => ac.cardID), ...seenCards]);
85
85
  // const tActive = performance.now(); // [perf] parked
86
+ // Centre the window on this generator's user's ELO, passed explicitly:
87
+ // `elo: 'user'` would have the course DB resolve its own notion of the
88
+ // current user, which isn't necessarily the user this pipeline runs for
89
+ // (e.g. an admin running a learner's pipeline read-only).
86
90
  const newCards = (
87
91
  await this.course.getCardsCenteredAtELO(
88
- { limit, elo: 'user' },
92
+ { limit, elo: userGlobalElo },
89
93
  (c: QualifiedCardID) => !notNew.has(c.cardID)
90
94
  )
91
95
  ).map((c) => ({ ...c, status: 'new' as const }));
@@ -619,13 +619,19 @@ export abstract class ContentNavigator implements StudyContentSource {
619
619
 
620
620
  let NavigatorImpl;
621
621
 
622
+ // Specifiers built at runtime, never template literals: bundlers expand
623
+ // `import(`./generators/${x}`)` into a glob over the directory, which in a
624
+ // per-module dist matches .map and .d.ts files and breaks the app's build.
625
+ // This fallback only resolves from source (no '.mjs' variation).
626
+ const load = (specifier: string) => import(/* @vite-ignore */ specifier);
627
+
622
628
  // Try different extension variations
623
629
  const variations = ['.ts', '.js', ''];
624
630
 
625
631
  for (const ext of variations) {
626
632
  // Try generators directory
627
633
  try {
628
- const module = await import(`./generators/${implementingClass}${ext}`);
634
+ const module = await load(`./generators/${implementingClass}${ext}`);
629
635
  NavigatorImpl = module.default;
630
636
  if (NavigatorImpl) break;
631
637
  } catch (e) {
@@ -634,7 +640,7 @@ export abstract class ContentNavigator implements StudyContentSource {
634
640
 
635
641
  // Try filters directory
636
642
  try {
637
- const module = await import(`./filters/${implementingClass}${ext}`);
643
+ const module = await load(`./filters/${implementingClass}${ext}`);
638
644
  NavigatorImpl = module.default;
639
645
  if (NavigatorImpl) break;
640
646
  } catch (e) {
@@ -643,7 +649,7 @@ export abstract class ContentNavigator implements StudyContentSource {
643
649
 
644
650
  // Try current directory (legacy)
645
651
  try {
646
- const module = await import(`./${implementingClass}${ext}`);
652
+ const module = await load(`./${implementingClass}${ext}`);
647
653
  NavigatorImpl = module.default;
648
654
  if (NavigatorImpl) break;
649
655
  } catch (e) {
package/src/factory.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  // db/src/factory.ts
2
2
 
3
3
  import { DataLayerProvider } from './core/interfaces';
4
- import { BaseUser } from './impl/common';
5
4
  import { logger } from './util/logger';
6
5
  import { StaticCourseManifest } from './util/packer/types';
7
6
  import { initializeNavigatorRegistry } from './core/navigators';
@@ -103,6 +102,9 @@ export async function initializeDataLayer(config: DataLayerConfig): Promise<Data
103
102
  // Create a sync strategy instance and authenticate
104
103
  const syncStrategy = new CouchDBSyncStrategy();
105
104
 
105
+ // Lazy, like the imports around it: a static import pulls moment and
106
+ // PouchDB into every app's boot.
107
+ const { BaseUser } = await import('./impl/common/BaseUserDB');
106
108
  const user = await BaseUser.instance(syncStrategy, config.options.COUCHDB_USERNAME);
107
109
  const authResult = await user.login(
108
110
  config.options.COUCHDB_USERNAME,
@@ -127,6 +129,13 @@ export async function initializeDataLayer(config: DataLayerConfig): Promise<Data
127
129
  }
128
130
 
129
131
  await dataLayerInstance.initialize();
132
+
133
+ // Console tool (window.skuilder.userdb). Lazy so it, and moment, stay out of
134
+ // apps' boot bundles; it needs the data layer anyway.
135
+ if (typeof window !== 'undefined') {
136
+ void import('./core/UserDBDebugger').then((m) => m.mountUserDBDebugger());
137
+ }
138
+
130
139
  return dataLayerInstance;
131
140
  }
132
141
 
@@ -31,10 +31,8 @@ import { CardHistory, CardRecord } from '../../core/types/types-legacy';
31
31
  import { UserOutcomeRecord } from '../../core/types/userOutcome';
32
32
  import { StudySessionDoc } from '../../core/types/studySession';
33
33
  import type { SyncStrategy } from './SyncStrategy';
34
+ import { filterAllDocsByPrefix, getStartAndEndKeys, REVIEW_TIME_FORMAT } from './userDBKeys';
34
35
  import {
35
- filterAllDocsByPrefix,
36
- getStartAndEndKeys,
37
- REVIEW_TIME_FORMAT,
38
36
  getLocalUserDB,
39
37
  scheduleCardReviewLocal,
40
38
  removeScheduledCardReviewLocal,
@@ -16,6 +16,8 @@ export {
16
16
  hexEncode,
17
17
  filterAllDocsByPrefix,
18
18
  getStartAndEndKeys,
19
+ } from './userDBKeys';
20
+ export {
19
21
  updateGuestAccountExpirationDate,
20
22
  getLocalUserDB,
21
23
  scheduleCardReviewLocal,
@@ -1,73 +1,19 @@
1
1
  // packages/db/src/impl/common/userDBHelpers.ts
2
2
 
3
3
  import moment from 'moment';
4
- import { DocType, DocTypePrefixes } from '@db/core';
5
4
  import { logger } from '../../util/logger';
6
5
  import { ScheduledCard } from '@db/core/types/user';
7
-
8
- export const REVIEW_TIME_FORMAT: string = 'YYYY-MM-DD--kk:mm:ss-SSS';
9
-
10
- /**
11
- * Build a ScheduledCard `_id` for the given review time.
12
- *
13
- * The id suffix is not a mere uniquifier: `getReviewstoDate` PARSES the id
14
- * (with {@link REVIEW_TIME_FORMAT}) to decide due-ness, so the id is the
15
- * datum. Anything that writes or rewrites scheduled-card docs (scheduling,
16
- * user-state snapshot rebasing) must construct ids through this helper —
17
- * a hand-rolled formatter will get moment's `kk` token (01-24 hours) wrong.
18
- */
19
- export function makeScheduledCardId(reviewTime: string | Date | moment.Moment): string {
20
- return DocTypePrefixes[DocType.SCHEDULED_CARD] + moment.utc(reviewTime).format(REVIEW_TIME_FORMAT);
21
- }
22
-
23
6
  import pouch from '../couch/pouchdb-setup';
24
7
  import { getDbPath } from '../../util/dataDirectory';
8
+ import { makeScheduledCardId } from './userDBKeys';
9
+
10
+ // PouchDB-backed helpers. The PouchDB-free ones (ids, key ranges) are in
11
+ // userDBKeys.ts.
25
12
 
26
13
  const log = (s: any) => {
27
14
  logger.info(s);
28
15
  };
29
16
 
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
- }
41
-
42
- export function filterAllDocsByPrefix<T>(
43
- db: PouchDB.Database,
44
- prefix: string,
45
- opts?: PouchDB.Core.AllDocsOptions
46
- ) {
47
- // see couchdb docs 6.2.2:
48
- // Guide to Views -> Views Collation -> String Ranges
49
- const options: PouchDB.Core.AllDocsWithinRangeOptions = {
50
- startkey: prefix,
51
- endkey: prefix + '\ufff0',
52
- include_docs: true,
53
- };
54
-
55
- if (opts) {
56
- Object.assign(options, opts);
57
- }
58
- return db.allDocs<T>(options);
59
- }
60
-
61
- export function getStartAndEndKeys(key: string): {
62
- startkey: string;
63
- endkey: string;
64
- } {
65
- return {
66
- startkey: key,
67
- endkey: key + '\ufff0',
68
- };
69
- }
70
-
71
17
  export function updateGuestAccountExpirationDate(guestDB: PouchDB.Database<object>) {
72
18
  const currentTime = moment.utc();
73
19
  const expirationDate: string = currentTime.add(2, 'months').toISOString();
@@ -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
+ }
@@ -690,8 +690,16 @@ above:\n${above.rows.map((r) => `\t${r.id}-${r.key}\n`)}`;
690
690
  private _eloPoolCache: {
691
691
  rows: (QualifiedCardID & { elo?: number })[];
692
692
  fetchedAt: number;
693
+ /** The ELO the pool was fetched around. */
694
+ centerElo: number;
693
695
  } | null = null;
694
696
  private readonly _eloPoolTtlMs = 5 * 60 * 1000;
697
+ /**
698
+ * How far the target may move from the pool's centre before the pool is
699
+ * refetched. Well above a learner's in-session roam; a different learner (or
700
+ * a far-off explicit ELO) on the same CourseDB gets a pool of their own.
701
+ */
702
+ private readonly _eloPoolMaxDrift = 200;
695
703
 
696
704
  /**
697
705
  * Cached assembled navigator (Pipeline). createNavigator() reads strategy
@@ -827,14 +835,18 @@ above:\n${above.rows.map((r) => `\t${r.id}-${r.key}\n`)}`;
827
835
  const nowMs = Date.now();
828
836
  let cacheStatus: 'hit' | 'miss' | 'refresh' = 'hit';
829
837
 
830
- if (!this._eloPoolCache || nowMs - this._eloPoolCache.fetchedAt > this._eloPoolTtlMs) {
838
+ if (
839
+ !this._eloPoolCache ||
840
+ nowMs - this._eloPoolCache.fetchedAt > this._eloPoolTtlMs ||
841
+ Math.abs(targetElo - this._eloPoolCache.centerElo) > this._eloPoolMaxDrift
842
+ ) {
831
843
  // MISS: pay the (reindexing) view query once, then cache the raw pool.
832
844
  // Guard: never cache an EMPTY pool. A cold-DB-open or sync-race fetch can
833
845
  // transiently return [], and caching it would starve the session for the
834
846
  // whole TTL. Leaving the cache untouched lets the next call retry.
835
847
  const fetched = await this.getCardsByELO(targetElo, POOL_SIZE);
836
848
  if (fetched.length > 0) {
837
- this._eloPoolCache = { rows: fetched, fetchedAt: nowMs };
849
+ this._eloPoolCache = { rows: fetched, fetchedAt: nowMs, centerElo: targetElo };
838
850
  }
839
851
  cacheStatus = 'miss';
840
852
  }
@@ -863,7 +875,7 @@ above:\n${above.rows.map((r) => `\t${r.id}-${r.key}\n`)}`;
863
875
  if (cards.length < options.limit && (cacheStatus === 'hit' || !this._eloPoolCache)) {
864
876
  const fetched = await this.getCardsByELO(targetElo, POOL_SIZE);
865
877
  if (fetched.length > 0) {
866
- this._eloPoolCache = { rows: fetched, fetchedAt: nowMs };
878
+ this._eloPoolCache = { rows: fetched, fetchedAt: nowMs, centerElo: targetElo };
867
879
  }
868
880
  cards = rankAgainstCurrentElo();
869
881
  cacheStatus = 'refresh';
@@ -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';
@@ -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);