@vue-skuilder/platform-ui 0.2.31 → 0.2.33

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 (98) hide show
  1. package/dist/assets/{About-B8hGg4uI.js → About-CY4NnmeV.js} +2 -2
  2. package/dist/assets/{About-B8hGg4uI.js.map → About-CY4NnmeV.js.map} +1 -1
  3. package/dist/assets/{AdminDashboard-CokJ3Dt8.js → AdminDashboard-edtEM5Dr.js} +2 -2
  4. package/dist/assets/{AdminDashboard-CokJ3Dt8.js.map → AdminDashboard-edtEM5Dr.js.map} +1 -1
  5. package/dist/assets/{AdminLearner-F1fWIyBA.js → AdminLearner-C6hRjA7u.js} +2 -2
  6. package/dist/assets/{AdminLearner-F1fWIyBA.js.map → AdminLearner-C6hRjA7u.js.map} +1 -1
  7. package/dist/assets/{ClassroomCtrlPanel-DYlMFipO.js → ClassroomCtrlPanel-f00317Ni.js} +2 -2
  8. package/dist/assets/{ClassroomCtrlPanel-DYlMFipO.js.map → ClassroomCtrlPanel-f00317Ni.js.map} +1 -1
  9. package/dist/assets/{Classrooms-BUaIYSBb.js → Classrooms-BP_TJvHC.js} +2 -2
  10. package/dist/assets/{Classrooms-BUaIYSBb.js.map → Classrooms-BP_TJvHC.js.map} +1 -1
  11. package/dist/assets/{CourseRouter-D3xYcL-n.js → CourseRouter-5CJuVkbz.js} +2 -2
  12. package/dist/assets/{CourseRouter-D3xYcL-n.js.map → CourseRouter-5CJuVkbz.js.map} +1 -1
  13. package/dist/assets/{CourseWare-BTFRjgBR-D5fSKikf.js → CourseWare-BTFRjgBR-txRZaFyG.js} +3 -3
  14. package/dist/assets/{CourseWare-BTFRjgBR-D5fSKikf.js.map → CourseWare-BTFRjgBR-txRZaFyG.js.map} +1 -1
  15. package/dist/assets/{Courses-DV_EXjCG.js → Courses-wSvIO8Rg.js} +2 -2
  16. package/dist/assets/{Courses-DV_EXjCG.js.map → Courses-wSvIO8Rg.js.map} +1 -1
  17. package/dist/assets/{EloModeration-CoCPYveS.js → EloModeration-yATO4B6I.js} +2 -2
  18. package/dist/assets/{EloModeration-CoCPYveS.js.map → EloModeration-yATO4B6I.js.map} +1 -1
  19. package/dist/assets/{JoinCode-CyJvlujW.js → JoinCode-DFcgKzlI.js} +2 -2
  20. package/dist/assets/{JoinCode-CyJvlujW.js.map → JoinCode-DFcgKzlI.js.map} +1 -1
  21. package/dist/assets/{NewCourseDialog-aLeJlDNm.js → NewCourseDialog-cILRsF-N.js} +2 -2
  22. package/dist/assets/{NewCourseDialog-aLeJlDNm.js.map → NewCourseDialog-cILRsF-N.js.map} +1 -1
  23. package/dist/assets/{ReleaseNotes-C6dmS8yw.js → ReleaseNotes-Df_Z_Xd5.js} +2 -2
  24. package/dist/assets/{ReleaseNotes-C6dmS8yw.js.map → ReleaseNotes-Df_Z_Xd5.js.map} +1 -1
  25. package/dist/assets/{RequestPasswordReset-K_iLC-Iz.js → RequestPasswordReset-CWqaKKWa.js} +2 -2
  26. package/dist/assets/{RequestPasswordReset-K_iLC-Iz.js.map → RequestPasswordReset-CWqaKKWa.js.map} +1 -1
  27. package/dist/assets/{ResetPassword-DzftY2p0.js → ResetPassword-BABsccxZ.js} +2 -2
  28. package/dist/assets/{ResetPassword-DzftY2p0.js.map → ResetPassword-BABsccxZ.js.map} +1 -1
  29. package/dist/assets/{Study-_hXuTqGs.js → Study-C6l9pTN8.js} +2 -2
  30. package/dist/assets/{Study-_hXuTqGs.js.map → Study-C6l9pTN8.js.map} +1 -1
  31. package/dist/assets/{TagInformation-Du_SXj1u.js → TagInformation-CL152sE4.js} +2 -2
  32. package/dist/assets/{TagInformation-Du_SXj1u.js.map → TagInformation-CL152sE4.js.map} +1 -1
  33. package/dist/assets/{User-BEBHCSY8.js → User-B5voU-tp.js} +2 -2
  34. package/dist/assets/{User-BEBHCSY8.js.map → User-B5voU-tp.js.map} +1 -1
  35. package/dist/assets/{UserStats-BU5bp1WJ.js → UserStats-BWq1QP_t.js} +2 -2
  36. package/dist/assets/{UserStats-BU5bp1WJ.js.map → UserStats-BWq1QP_t.js.map} +1 -1
  37. package/dist/assets/{VerifyEmail-BHua2U9A.js → VerifyEmail-rdrqVTaX.js} +2 -2
  38. package/dist/assets/{VerifyEmail-BHua2U9A.js.map → VerifyEmail-rdrqVTaX.js.map} +1 -1
  39. package/dist/assets/{admin-7qdAJswS.css → admin-Cfzt4Vei.css} +1 -1
  40. package/dist/assets/admin-CpMRYlmB.js +4 -0
  41. package/dist/assets/admin-CpMRYlmB.js.map +1 -0
  42. package/dist/assets/{chess-E2uOAyQS-BxlZRhDQ.js → chess-E2uOAyQS-BQUHPZw0.js} +2 -2
  43. package/dist/assets/{chess-E2uOAyQS-BxlZRhDQ.js.map → chess-E2uOAyQS-BQUHPZw0.js.map} +1 -1
  44. package/dist/assets/chess-Lfm7Fsvs-CkwKAarN.js +1 -0
  45. package/dist/assets/{common-ui.es-DA_s8IG6.js → common-ui.es-BYENpnRV.js} +4 -4
  46. package/dist/assets/{common-ui.es-DA_s8IG6.js.map → common-ui.es-BYENpnRV.js.map} +1 -1
  47. package/dist/assets/{common-ui.es-DgKeG5TP.js → common-ui.es-BxteqHlD.js} +1 -1
  48. package/dist/assets/{dist-sk9QmPBI.js → dist-Cyq221IF.js} +15 -14
  49. package/dist/assets/{dist-sk9QmPBI.js.map → dist-Cyq221IF.js.map} +1 -1
  50. package/dist/assets/{dist-Cr-5eJ0-.js → dist-DJXXY69e.js} +3 -3
  51. package/dist/assets/{dist-Cr-5eJ0-.js.map → dist-DJXXY69e.js.map} +1 -1
  52. package/dist/assets/dist-DSfQApVT.js +1 -0
  53. package/dist/assets/dist-HeqUKzar.js +1 -0
  54. package/dist/assets/{edit-ui.es-BvU22nW8.js → edit-ui.es-66x2BkHZ.js} +2 -2
  55. package/dist/assets/{edit-ui.es-BvU22nW8.js.map → edit-ui.es-66x2BkHZ.js.map} +1 -1
  56. package/dist/assets/edit-ui.es-Crq2fLxh.js +1 -0
  57. package/dist/assets/{french-Dk7YG8Td-DkIlocR5.js → french-Dk7YG8Td-C40XF0ei.js} +2 -2
  58. package/dist/assets/{french-Dk7YG8Td-DkIlocR5.js.map → french-Dk7YG8Td-C40XF0ei.js.map} +1 -1
  59. package/dist/assets/french-evUMlbbq-BoXkYpPj.js +1 -0
  60. package/dist/assets/{index-DmF2uBY0.js → index-Ct8brwnw.js} +4 -4
  61. package/dist/assets/{index-DmF2uBY0.js.map → index-Ct8brwnw.js.map} +1 -1
  62. package/dist/assets/{math-B4HbgYf6-CyzXvPAn.js → math-B4HbgYf6-BiH88C2B.js} +2 -2
  63. package/dist/assets/{math-B4HbgYf6-CyzXvPAn.js.map → math-B4HbgYf6-BiH88C2B.js.map} +1 -1
  64. package/dist/assets/math-DYni7rRl-BacgHd33.js +1 -0
  65. package/dist/assets/piano-BN5Btq91-DawaTkt6.js +1 -0
  66. package/dist/assets/{piano-DF1g6yaX-CjTAtRkn.js → piano-DF1g6yaX-Cm7rgAiB.js} +2 -2
  67. package/dist/assets/{piano-DF1g6yaX-CjTAtRkn.js.map → piano-DF1g6yaX-Cm7rgAiB.js.map} +1 -1
  68. package/dist/assets/{pitch-CgGJFkZ1-BFmwOAVB.js → pitch-CgGJFkZ1-raMdOfKL.js} +2 -2
  69. package/dist/assets/{pitch-CgGJFkZ1-BFmwOAVB.js.map → pitch-CgGJFkZ1-raMdOfKL.js.map} +1 -1
  70. package/dist/assets/pitch-Dn0iNqiS-ChxLq3C2.js +1 -0
  71. package/dist/assets/{server-OcZCCXA0.js → server-Cp2grk3h.js} +2 -2
  72. package/dist/assets/{server-OcZCCXA0.js.map → server-Cp2grk3h.js.map} +1 -1
  73. package/dist/assets/{sightsing-BFQ7HRig-vWVPlu1j.js → sightsing-BFQ7HRig-a5hh4s6b.js} +2 -2
  74. package/dist/assets/{sightsing-BFQ7HRig-vWVPlu1j.js.map → sightsing-BFQ7HRig-a5hh4s6b.js.map} +1 -1
  75. package/dist/assets/sightsing-CJX3k0Fd-BumMPKrl.js +1 -0
  76. package/dist/assets/{typing-BevtfWlp-CyxWSAtY.js → typing-BevtfWlp-DPWCOdqa.js} +2 -2
  77. package/dist/assets/{typing-BevtfWlp-CyxWSAtY.js.map → typing-BevtfWlp-DPWCOdqa.js.map} +1 -1
  78. package/dist/assets/typing-k-ojjO7G-CNZkfRKK.js +1 -0
  79. package/dist/assets/{word-work-BOnRlZgd-B91Toruk.js → word-work-BOnRlZgd-CUfVid6n.js} +2 -2
  80. package/dist/assets/{word-work-BOnRlZgd-B91Toruk.js.map → word-work-BOnRlZgd-CUfVid6n.js.map} +1 -1
  81. package/dist/assets/word-work-Dd6tIKrt-BEWb3uQV.js +1 -0
  82. package/dist/index.html +3 -3
  83. package/dist/sw.js +1 -1
  84. package/dist/sw.js.map +1 -1
  85. package/package.json +7 -7
  86. package/dist/assets/admin-ua4_RK2L.js +0 -4
  87. package/dist/assets/admin-ua4_RK2L.js.map +0 -1
  88. package/dist/assets/chess-Lfm7Fsvs-DFvvUWcF.js +0 -1
  89. package/dist/assets/dist-DV3iQBZl.js +0 -1
  90. package/dist/assets/dist-Ubbhh-gm.js +0 -1
  91. package/dist/assets/edit-ui.es-CBp3tHSA.js +0 -1
  92. package/dist/assets/french-evUMlbbq-D1l1sbHC.js +0 -1
  93. package/dist/assets/math-DYni7rRl-xBXi71Kr.js +0 -1
  94. package/dist/assets/piano-BN5Btq91-Df2sweTl.js +0 -1
  95. package/dist/assets/pitch-Dn0iNqiS-ZPelvu11.js +0 -1
  96. package/dist/assets/sightsing-CJX3k0Fd-pCqMHic0.js +0 -1
  97. package/dist/assets/typing-k-ojjO7G-Cjd9r06R.js +0 -1
  98. package/dist/assets/word-work-Dd6tIKrt-B_YDaaSy.js +0 -1
@@ -251,7 +251,8 @@ Example:
251
251
  Generator: ${e.name}
252
252
  Filters:${n}`)}function logTagHydration(e,t){let n=Array.from(t.values()).reduce((e,t)=>e+t.length,0),r=Array.from(t.values()).filter(e=>e.length>0).length;logger.debug(`[Pipeline] Tag hydration: ${e.length} cards, ${r} have tags (${n} total tags) - single batch query`)}function logExecutionSummary(e,t,n,r,a,o){let s=a.length>0?a.map(e=>e.toFixed(2)).join(`, `):`none`,c=``;o.length>0&&(c=`
253
253
  Filter impact: ${o.map(e=>{let t=[];return e.boosted>0&&t.push(`+${e.boosted}`),e.penalized>0&&t.push(`-${e.penalized}`),e.passed>0&&t.push(`=${e.passed}`),`${e.name}: ${t.join(`/`)}`}).join(`, `)}`),logger.info(`[Pipeline] Execution: ${e} produced ${t} \u2192 ${n} filters \u2192 ${r} results (top scores: ${s})`+c+`
254
- 💡 Inspect: window.skuilder.pipeline`)}function logResultCards(e){if(!(!VERBOSE_RESULTS||e.length===0)){logger.info(`[Pipeline] Results (${e.length} cards):`);for(let t=0;t<e.length;t++){let n=e[t],r=n.tags?.slice(0,3).join(`, `)||``,a=n.provenance.filter(e=>e.strategy===`hierarchyDefinition`||e.strategy===`priorityDefinition`||e.strategy===`interferenceFilter`||e.strategy===`letterGating`||e.strategy===`ephemeralHint`||e.strategy===`diversityRerank`).map(e=>{let t=e.action===`boosted`?`↑`:e.action===`penalized`?`↓`:`=`;return`${e.strategyName}${t}${e.score.toFixed(2)}`}).join(` | `);logger.info(`[Pipeline] ${String(t+1).padStart(2)}. ${n.score.toFixed(4)} ${n.cardId} [${r}]${a?` {${a}}`:``}`)}}}function logCardProvenance(e,t=3){let n=e.slice(0,t);logger.debug(`[Pipeline] Provenance for top ${n.length} cards:`);for(let e of n){logger.debug(`[Pipeline] ${e.cardId} (final score: ${e.score.toFixed(3)}):`);for(let t of e.provenance){let e=t.score.toFixed(3),n=t.action.padEnd(9);logger.debug(`[Pipeline] ${n} ${e} - ${t.strategyName}: ${t.reason}`)}}}var VERBOSE_RESULTS,Pipeline,init_Pipeline=__esm({"src/core/navigators/Pipeline.ts"(){init_navigators(),init_logger(),init_orchestration(),init_PipelineDebugger(),init_diversityRerank(),init_regulators(),init_SrsDebugger(),VERBOSE_RESULTS=!0,Pipeline=class extends ContentNavigator{constructor(e,t,n,r){super(),_defineProperty(this,`generator`,void 0),_defineProperty(this,`filters`,void 0),_defineProperty(this,`_cachedOrchestration`,null),_defineProperty(this,`_tagCache`,new Map),_defineProperty(this,`_ephemeralHints`,null),_defineProperty(this,`_intakeClock`,null),_defineProperty(this,`_intakeClockWrite`,Promise.resolve()),this.generator=e,this.filters=t,this.user=n,this.course=r,r.getCourseConfig().then(e=>{logger.debug(`[pipeline] Crated pipeline for ${e.name}`)}).catch(e=>{logger.error(`[pipeline] Failed to lookup courseCfg: ${e}`)}),logPipelineConfig(e,t),registerPipelineForDebug(this)}setEphemeralHints(e){this._ephemeralHints=e,logger.info(`[Pipeline] Ephemeral hints set: ${JSON.stringify(e)}`)}async getWeightedCards(e){let t=performance.now(),n=await this.buildContext(),r=performance.now(),a=500;logger.debug(`[Pipeline] Fetching 500 candidates from generator '${this.generator.name}'`);let o=await this.generator.getWeightedCards(500,n),s=o.cards,c=performance.now(),l=s.length;this._ephemeralHints=mergeHints2([this._ephemeralHints,o.hints])??null;let u;if(this.generator.generators){let e=new Map;for(let t of s){let n=t.provenance[0];if(n){let r=n.strategyName;e.has(r)||e.set(r,{cards:[]}),e.get(r).cards.push(t)}}u=Array.from(e.entries()).map(([e,t])=>{let n=t.cards.filter(e=>e.reviewID).length;return{name:e,cardCount:t.cards.length,newCount:t.cards.length-n,reviewCount:n,topScore:Math.max(...t.cards.map(e=>e.score),0)}})}logger.debug(`[Pipeline] Generator returned ${l} candidates`),s=await this.hydrateTags(s);let d=performance.now(),p=[...s],m=this._ephemeralHints;if(m?.requireCards?.length){let e=new Set(p.map(e=>e.cardId)),t=m.requireCards.filter(t=>!t.includes(`*`)&&!e.has(t));if(t.length>0){let e=await this.course.getAppliedTagsBatch(t),n=this.course.getCourseID();for(let r of t)p.push({cardId:r,courseId:n,score:1,tags:e.get(r)??[],provenance:[]});logger.info(`[Pipeline] Pre-fetched ${t.length} required card(s) into pool: ${t.join(`, `)}`)}}let g=new Set(s.filter(e=>e.provenance.some(e=>e.strategy===`prescribed`)).map(e=>e.cardId)),_=[],v=new Map(s.map(e=>[e.cardId,e.score])),y=new Set;for(let e of this.filters){let t=s.length,r=new Map(s.map(e=>[e.cardId,e.score]));s=await e.transform(s,n);let a=0,o=0,c=0,l=t-s.length,u=e.kind??`gate`;for(let e of s){let t=r.get(e.cardId)??0;e.score>t?a++:e.score<t?(o++,u===`gate`&&y.add(e.cardId)):c++}if(_.push({name:e.name,kind:u,boosted:a,penalized:o,passed:c,removed:l}),g.size>0){let t=new Set(s.map(e=>e.cardId)),n=[...g].filter(e=>!t.has(e)),r=s.filter(e=>g.has(e.cardId)&&e.score===0).map(e=>e.cardId);(n.length>0||r.length>0)&&(logger.info(`[Pipeline] Filter '${e.name}' impact on prescribed cards: `+(n.length>0?`removed=[${n.join(`, `)}] `:``)+(r.length>0?`zeroed=[${r.join(`, `)}]`:``)),n.forEach(e=>g.delete(e)))}logger.debug(`[Pipeline] Filter '${e.name}': ${r.size} \u2192 ${s.length} cards (\u2191${a} \u2193${o} =${c})`)}let b=s;s=s.filter(e=>e.score>0);let x=await this.regulate(s,v,y),S=this._ephemeralHints;S&&(this._ephemeralHints=null,s=this.applyHints(s,S,p)),s=diversityRerank(s),s.sort((e,t)=>t.score-e.score);let C=performance.now(),w=s.slice(0,e);logger.info(`[Pipeline:timing] total=${(C-t).toFixed(0)}ms (context=${(r-t).toFixed(0)} generate=${(c-r).toFixed(0)} hydrate=${(d-c).toFixed(0)} filter=${(C-d).toFixed(0)})`);let T=w.slice(0,3).map(e=>e.score);logExecutionSummary(this.generator.name,l,this.filters.length,w.length,T,_),logResultCards(w),logCardProvenance(w,3);try{let e=await this.course?.getCourseConfig().then(e=>e.name).catch(()=>void 0);captureRun(buildRunReport(this.course?.getCourseID()||`unknown`,e,this.generator.name,u,l,_,s,w,n.userElo,S??void 0,b,x))}catch(e){logger.debug(`[Pipeline] Failed to capture debug run: ${e}`)}return{cards:w}}async hydrateTags(e){if(e.length===0)return e;let t=[];for(let n of e)this._tagCache.has(n.cardId)||t.push(n.cardId);if(t.length>0){let e=await this.course.getAppliedTagsBatch(t);for(let[t,n]of e)this._tagCache.set(t,n)}let n=new Map;for(let t of e)n.set(t.cardId,this._tagCache.get(t.cardId)??[]);return logTagHydration(e,n),e.map(e=>({...e,tags:this._tagCache.get(e.cardId)??[]}))}applyHints(e,t,n){let r=e.length;if(t.excludeCards?.length&&(e=e.filter(e=>!t.excludeCards.some(t=>globMatch(e.cardId,t)))),t.excludeTags?.length&&(e=e.filter(e=>!t.excludeTags.some(t=>cardMatchesTagPattern(e,t)))),t.boostTags)for(let[n,r]of Object.entries(t.boostTags))for(let a of e)cardMatchesTagPattern(a,n)&&(a.score*=r,a.provenance.push({strategy:`ephemeralHint`,strategyId:`ephemeral-hint`,strategyName:t._label?`Replan Hint (${t._label})`:`Replan Hint`,action:`boosted`,score:a.score,reason:`boostTag ${n} \xD7${r}`}));if(t.boostCards)for(let[n,r]of Object.entries(t.boostCards))for(let a of e)globMatch(a.cardId,n)&&(a.score*=r,a.provenance.push({strategy:`ephemeralHint`,strategyId:`ephemeral-hint`,strategyName:t._label?`Replan Hint (${t._label})`:`Replan Hint`,action:`boosted`,score:a.score,reason:`boostCard ${n} \xD7${r}`}));let a=new Set(e.map(e=>e.cardId)),o=new Map(e.map(e=>[e.cardId,e])),s=t._label?`Replan Hint (${t._label})`:`Replan Hint`,applyRequirement=(t,n)=>{let r=1/0,c=o.get(t.cardId);c?c.score<r&&(c.score=r,c.provenance.push({strategy:`ephemeralHint`,strategyId:`ephemeral-hint`,strategyName:s,action:`boosted`,score:r,reason:`${n} (upgrade to mandatory score)`})):(e.push({...t,score:r,provenance:[...t.provenance,{strategy:`ephemeralHint`,strategyId:`ephemeral-hint`,strategyName:s,action:`boosted`,score:r,reason:n}]}),a.add(t.cardId),o.set(t.cardId,e[e.length-1]))};if(t.requireCards?.length)for(let e of t.requireCards){for(let t of a)globMatch(t,e)&&applyRequirement(o.get(t),`requireCard ${e}`);for(let t of n)globMatch(t.cardId,e)&&applyRequirement(t,`requireCard ${e}`)}if(t.requireTags?.length)for(let e of t.requireTags){for(let t of a){let n=o.get(t);cardMatchesTagPattern(n,e)&&applyRequirement(n,`requireTag ${e}`)}for(let t of n)cardMatchesTagPattern(t,e)&&applyRequirement(t,`requireTag ${e}`)}return logger.info(`[Pipeline] Hints applied: ${r} \u2192 ${e.length} cards`),e}async regulate(e,t,n){let r=DEFAULT_REGULATOR_CONFIG,a=e.filter(e=>e.reviewID),o=e.filter(e=>!e.reviewID),s=o.filter(e=>!n.has(e.cardId)),c=reviewMassReading(a,t,r.reviewMass);applyReading(a,c),noteReviewPressure(this.course.getCourseID(),{mass:c.urgency,healthyMass:r.reviewMass.healthyMass,rate:r.reviewMass.rate,multiplier:c.multiplier});let l=Date.now(),u=await this.loadIntakeClock(l),d=stepIntakeClock(u,l,s.length);d!==u&&this.saveIntakeClock(d);let p=intakeReading(d,l,{eligibleNew:s.length,newCandidates:o.length},r.intake);return applyReading(s,p),logger.info(`[Pipeline:regulators] review mass ${c.urgency.toFixed(1)} over ${a.length} due \u2192 \xD7${c.multiplier.toFixed(2)}; intake ${p.urgency.toFixed(1)}h, ${s.length}/${o.length} new eligible \u2192 \xD7${p.multiplier.toFixed(2)}`),[c,p]}notePresented(e){e.status!==`new`||e.courseId!==this.course?.getCourseID()||this.saveIntakeClock(resetIntakeClock(Date.now()))}async loadIntakeClock(e){if(this._intakeClock)return this._intakeClock;let t=null;try{t=await this.user.getStrategyState(this.course.getCourseID(),INTAKE_CLOCK_KEY)}catch(e){logger.warn(`[Pipeline:regulators] Could not read the intake clock: ${e}`)}return t?this._intakeClock=t:this.saveIntakeClock(resetIntakeClock(e)),this._intakeClock}saveIntakeClock(e){this._intakeClock=e;let t=this.course.getCourseID();this._intakeClockWrite=this._intakeClockWrite.then(()=>this.user.putStrategyState(t,INTAKE_CLOCK_KEY,e)).catch(e=>logger.warn(`[Pipeline:regulators] Could not save the intake clock: ${e}`))}async buildContext(){let e=1e3,t;try{t=toCourseElo((await this.user.getCourseRegDoc(this.course.getCourseID())).elo),e=t.global.score}catch(e){logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`)}this._cachedOrchestration||(this._cachedOrchestration=await createOrchestrationContext(this.user,this.course));let n=this._cachedOrchestration;return{user:this.user,course:this.course,userElo:e,...t?{userCourseElo:t}:{},orchestration:n}}getCourseID(){return this.course.getCourseID()}async getOrchestrationContext(){return createOrchestrationContext(this.user,this.course)}getStrategyIds(){let e=[],extractId=e=>e.strategyId?e.strategyId:null,t=extractId(this.generator);t&&e.push(t),this.generator.generators&&Array.isArray(this.generator.generators)&&this.generator.generators.forEach(t=>{let n=extractId(t);n&&e.push(n)});for(let t of this.filters){let n=extractId(t);n&&e.push(n)}return[...new Set(e)]}async getTagEloStatus(e){let t=toCourseElo((await this.user.getCourseRegDoc(this.course.getCourseID())).elo),n={};if(e){let r=Array.isArray(e)?e:[e];for(let e of r){let r=globToRegex(e);for(let[e,a]of Object.entries(t.tags))r.test(e)&&(n[e]={score:a.score,count:a.count})}}else for(let[e,r]of Object.entries(t.tags))n[e]={score:r.score,count:r.count};return n}async forecast(e){let t=e?.threshold??.1,n=e?.unseenOnly??!0,r=this.course.getCourseID(),a=(await this.course.getAllCardIds()).map(e=>({cardId:e,courseId:r,score:1,provenance:[]}));a=await this.hydrateTags(a);let o=a.slice(),s=await this.buildContext();for(let e of this.forecastFilters())a=await e.transform(a,s);if(e?.hints&&(a=this.applyHints(a,e.hints,o)),a=a.filter(e=>e.score>=t),n){let e;try{e=new Set(await this.user.getSeenCards(r))}catch{e=new Set}a=a.filter(t=>!e.has(t.cardId))}return a.sort((e,t)=>t.score-e.score),e?.limit?a.slice(0,e.limit):a}forecastFilters(){return this.filters.filter(e=>!e.liveOnly)}async diagnoseCardSpace(e){let t=e?.threshold??.1,n=performance.now(),r=await this.course.getAllCardIds(),a=r.map(e=>({cardId:e,courseId:this.course.getCourseID(),score:1,provenance:[]}));a=await this.hydrateTags(a);let o=await this.buildContext(),s=[];for(let e of this.forecastFilters()){a=await e.transform(a,o);let n=a.filter(e=>e.score>=t).length;s.push({name:e.name,wellIndicated:n})}let c=a.filter(e=>e.score>=t),l=new Set(c.map(e=>e.cardId)),u;try{let e=this.course.getCourseID(),t=await this.user.getSeenCards(e);u=new Set(t)}catch{u=new Set}let d=c.filter(e=>!u.has(e.cardId)),p=new Map;for(let e of a){let n=e.cardId.split(`-`)[1]||`unknown`;p.has(n)||p.set(n,{total:0,wellIndicated:0,new:0});let r=p.get(n);r.total++,e.score>=t&&(r.wellIndicated++,u.has(e.cardId)||r.new++)}let m=performance.now()-n,g={totalCards:r.length,threshold:t,wellIndicated:l.size,encountered:u.size,wellIndicatedNew:d.length,byType:Object.fromEntries(p),filterBreakdown:s,elapsedMs:Math.round(m)};logger.info(`[Pipeline:diagnose] Card space scan (${g.elapsedMs}ms):`),logger.info(`[Pipeline:diagnose] Total cards: ${g.totalCards}`),logger.info(`[Pipeline:diagnose] Well-indicated (score >= ${t}): ${g.wellIndicated}`),logger.info(`[Pipeline:diagnose] Encountered: ${g.encountered}`),logger.info(`[Pipeline:diagnose] Well-indicated & new: ${g.wellIndicatedNew}`),logger.info(`[Pipeline:diagnose] By type:`);for(let[e,t]of p)logger.info(`[Pipeline:diagnose] ${e}: ${t.wellIndicated}/${t.total} well-indicated, ${t.new} new`);logger.info(`[Pipeline:diagnose] After each filter:`);for(let e of s)logger.info(`[Pipeline:diagnose] ${e.name}: ${e.wellIndicated} well-indicated`);return g}}}}),defaults_exports={};__export(defaults_exports,{createDefaultEloDistanceStrategy:()=>createDefaultEloDistanceStrategy,createDefaultEloStrategy:()=>createDefaultEloStrategy,createDefaultPipeline:()=>createDefaultPipeline,createDefaultSrsStrategy:()=>createDefaultSrsStrategy});function createDefaultEloStrategy(e){return{_id:`NAVIGATION_STRATEGY-ELO-default`,docType:`NAVIGATION_STRATEGY`,name:`ELO (default)`,description:`Default ELO-based navigation strategy for new cards`,implementingClass:`elo`,course:e,serializedData:``}}function createDefaultSrsStrategy(e){return{_id:`NAVIGATION_STRATEGY-SRS-default`,docType:`NAVIGATION_STRATEGY`,name:`SRS (default)`,description:`Default SRS-based navigation strategy for reviews`,implementingClass:`srs`,course:e,serializedData:``}}function createDefaultEloDistanceStrategy(e){return{_id:`NAVIGATION_STRATEGY-eloDistance-default`,docType:`NAVIGATION_STRATEGY`,name:`ELO Distance (default)`,description:`Scales every candidate, new or review, by its distance from the learner's ELO`,implementingClass:`eloDistance`,course:e,serializedData:JSON.stringify(DEFAULT_ELO_DISTANCE_CONFIG)}}function createDefaultPipeline(e,t){let n=t.getCourseID(),r=new ELONavigator(e,t,createDefaultEloStrategy(n)),a=new SRSNavigator(e,t,createDefaultSrsStrategy(n)),o=new CompositeGenerator([r,a]),s=new EloDistanceFilter(e,t,createDefaultEloDistanceStrategy(n));return new Pipeline(o,[s],e,t)}var init_defaults=__esm({"src/core/navigators/defaults.ts"(){init_navigators(),init_Pipeline(),init_CompositeGenerator(),init_elo(),init_srs(),init_eloDistance(),init_types_legacy()}}),pipelinePlan_exports={};__export(pipelinePlan_exports,{PIPELINE_STAGES:()=>PIPELINE_STAGES,planPipeline:()=>planPipeline});function planned(e,t,n){let r=t===`filter`?getRegisteredFilterKind(e.implementingClass):void 0;return{role:t,origin:n,name:e.name,implementingClass:e.implementingClass,strategy:e,...r?{kind:r}:{}}}function planPipeline(e,t){if(e.length===0)return{kind:`default`,generators:[planned(createDefaultEloStrategy(t),`generator`,`default-pipeline`),planned(createDefaultSrsStrategy(t),`generator`,`default-pipeline`)],filters:[planned(createDefaultEloDistanceStrategy(t),`filter`,`default-pipeline`)],skipped:[],warnings:[],notes:[],regulators:DEFAULT_REGULATOR_CONFIG};let n=[],r=[],a=[],o=[];for(let t of e)isGenerator(t.implementingClass)?n.push(planned(t,`generator`,`strategy-doc`)):isFilter(t.implementingClass)?r.push(planned(t,`filter`,`strategy-doc`)):(a.push({strategy:t,reason:`not a registered generator or filter`}),o.push(`Unknown strategy type '${t.implementingClass}', skipping: ${t.name}`));let s=new Set(n.map(e=>e.implementingClass));s.has(createDefaultEloStrategy(t).implementingClass)||n.push(planned(createDefaultEloStrategy(t),`generator`,`assembler-default`)),s.has(createDefaultSrsStrategy(t).implementingClass)||n.push(planned(createDefaultSrsStrategy(t),`generator`,`assembler-default`));let c=createDefaultEloDistanceStrategy(t);return r.some(e=>e.implementingClass===c.implementingClass)||r.push(planned(c,`filter`,`assembler-default`)),r.sort((e,t)=>e.name.localeCompare(t.name)),{kind:`assembled`,generators:n,filters:r,skipped:a,warnings:o,notes:[],regulators:DEFAULT_REGULATOR_CONFIG}}var PIPELINE_STAGES,init_pipelinePlan=__esm({"src/core/navigators/pipelinePlan.ts"(){init_navigators(),init_regulators(),init_defaults(),PIPELINE_STAGES=[{key:`generate`,title:`Generate`,summary:`Each generator proposes candidates (up to 500 in all), scored on what is specific to its source. A card proposed by several generators keeps their mean score, raised 10% per extra generator.`},{key:`filter`,title:`Filter`,summary:`Each filter multiplies candidate scores, in the order shown. A gate says a card is not ready yet; a signal expresses preference. Gates usually penalize rather than remove, so a gated card stays in the pool at a low score.`},{key:`drop-zero`,title:`Drop zero scores`,summary:`Candidates whose score reached 0 leave the pool.`},{key:`regulate`,title:`Regulate`,summary:`Balances reviews against new cards. Review mass: the due reviews weighed by their filtered scores; above a healthy level, every review is lifted. Intake: hours since a new card was last presented; new cards no gate penalized are lifted, and the clock stops while there are none.`},{key:`hints`,title:`Apply hints`,summary:`The session's hints (from the app: an intro's follow-up, a difficulty boost) exclude, boost, or require cards. Required cards skip the filters entirely.`},{key:`diversity`,title:`Diversity re-rank`,summary:`Demotes candidates that repeat a distinctive tag already ranked above them, so one concept or answer cannot take the whole head of the queue. Sees this run only, not what the session already served.`},{key:`select`,title:`Select`,summary:`Highest scores first, up to the run's limit. The session mixes them into its supply queue.`}]}}),PipelineAssembler_exports={};__export(PipelineAssembler_exports,{PipelineAssembler:()=>PipelineAssembler});var PipelineAssembler,init_PipelineAssembler=__esm({"src/core/navigators/PipelineAssembler.ts"(){init_navigators(),init_WeightedFilter(),init_Pipeline(),init_logger(),init_CompositeGenerator(),init_pipelinePlan(),PipelineAssembler=class{async assemble(e){let{strategies:t,user:n,course:r}=e,a=[];if(t.length===0)return{pipeline:null,generatorStrategies:[],filterStrategies:[],warnings:a};let o=planPipeline(t,r.getCourseID());a.push(...o.warnings);for(let e of[...o.generators,...o.filters])e.origin===`assembler-default`&&logger.debug(`[PipelineAssembler] No ${e.implementingClass} ${e.role} configured, adding default`);let s=o.generators.map(e=>e.strategy),c=o.filters.map(e=>e.strategy);if(s.length===0)return a.push(`No generator strategy found`),{pipeline:null,generatorStrategies:[],filterStrategies:[],warnings:a};let l;s.length===1?(l=await ContentNavigator.create(n,r,s[0]),logger.debug(`[PipelineAssembler] Using single generator: ${s[0].name}`)):(logger.debug(`[PipelineAssembler] Using CompositeGenerator for ${s.length} generators: ${s.map(e=>e.name).join(`, `)}`),l=await CompositeGenerator.fromStrategies(n,r,s));let u=[];for(let e of c)try{let t=await ContentNavigator.create(n,r,e);if(`transform`in t&&typeof t.transform==`function`){let n=t;e.learnable&&(n=new WeightedFilter(n,e.learnable,e.staticWeight,e._id)),u.push(n),logger.debug(`[PipelineAssembler] Added filter: ${e.name}`)}else a.push(`Filter '${e.name}' does not implement CardFilter.transform(), skipping`)}catch(t){a.push(`Failed to instantiate filter '${e.name}': ${t}`)}let d=new Pipeline(l,u,n,r);return logger.debug(`[PipelineAssembler] Assembled pipeline with ${s.length} generator(s) and ${u.length} filter(s)`),{pipeline:d,generatorStrategies:s,filterStrategies:c,warnings:a}}}}}),globImport,init_3=__esm({'import("./**/*") in src/core/navigators/index.ts'(){globImport=__glob({"./Pipeline.ts":()=>Promise.resolve().then(()=>(init_Pipeline(),Pipeline_exports)),"./PipelineAssembler.ts":()=>Promise.resolve().then(()=>(init_PipelineAssembler(),PipelineAssembler_exports)),"./PipelineDebugger.ts":()=>Promise.resolve().then(()=>(init_PipelineDebugger(),PipelineDebugger_exports)),"./SrsDebugger.ts":()=>Promise.resolve().then(()=>(init_SrsDebugger(),SrsDebugger_exports)),"./StrategyPressureDebugger.ts":()=>Promise.resolve().then(()=>(init_StrategyPressureDebugger(),StrategyPressureDebugger_exports)),"./defaults.ts":()=>Promise.resolve().then(()=>(init_defaults(),defaults_exports)),"./diversityRerank.ts":()=>Promise.resolve().then(()=>(init_diversityRerank(),diversityRerank_exports)),"./filters/WeightedFilter.ts":()=>Promise.resolve().then(()=>(init_WeightedFilter(),WeightedFilter_exports)),"./filters/eloDistance.ts":()=>Promise.resolve().then(()=>(init_eloDistance(),eloDistance_exports)),"./filters/hierarchyDefinition.ts":()=>Promise.resolve().then(()=>(init_hierarchyDefinition(),hierarchyDefinition_exports)),"./filters/index.ts":()=>Promise.resolve().then(()=>(init_filters(),filters_exports)),"./filters/inferredPreferenceStub.ts":()=>Promise.resolve().then(()=>(init_inferredPreferenceStub(),inferredPreferenceStub_exports)),"./filters/interferenceMitigator.ts":()=>Promise.resolve().then(()=>(init_interferenceMitigator(),interferenceMitigator_exports)),"./filters/relativePriority.ts":()=>Promise.resolve().then(()=>(init_relativePriority(),relativePriority_exports)),"./filters/types.ts":()=>Promise.resolve().then(()=>(init_types2(),types_exports2)),"./filters/userGoalStub.ts":()=>Promise.resolve().then(()=>(init_userGoalStub(),userGoalStub_exports)),"./filters/userTagPreference.ts":()=>Promise.resolve().then(()=>(init_userTagPreference(),userTagPreference_exports)),"./generators/CompositeGenerator.ts":()=>Promise.resolve().then(()=>(init_CompositeGenerator(),CompositeGenerator_exports)),"./generators/elo.ts":()=>Promise.resolve().then(()=>(init_elo(),elo_exports)),"./generators/index.ts":()=>Promise.resolve().then(()=>(init_generators(),generators_exports)),"./generators/prescribed.ts":()=>Promise.resolve().then(()=>(init_prescribed(),prescribed_exports)),"./generators/srs.ts":()=>Promise.resolve().then(()=>(init_srs(),srs_exports)),"./generators/types.ts":()=>Promise.resolve().then(()=>(init_types(),types_exports)),"./index.ts":()=>Promise.resolve().then(()=>(init_navigators(),navigators_exports)),"./pipelinePlan.ts":()=>Promise.resolve().then(()=>(init_pipelinePlan(),pipelinePlan_exports)),"./regulators.ts":()=>Promise.resolve().then(()=>(init_regulators(),regulators_exports))})}}),navigators_exports={};__export(navigators_exports,{ContentNavigator:()=>ContentNavigator,DIVERSITY_FLOOR:()=>DIVERSITY_FLOOR,DIVERSITY_STRENGTH:()=>DIVERSITY_STRENGTH,NavigatorRole:()=>NavigatorRole,NavigatorRoles:()=>NavigatorRoles,Navigators:()=>Navigators,captureStrategyPressure:()=>captureStrategyPressure,clearSrsBacklogDebug:()=>clearSrsBacklogDebug,clearStrategyPressureDebug:()=>clearStrategyPressureDebug,diversityRerank:()=>diversityRerank,drainCapturedRuns:()=>drainCapturedRuns,getActivePipeline:()=>getActivePipeline,getCardOrigin:()=>getCardOrigin,getRegisteredFilterKind:()=>getRegisteredFilterKind,getRegisteredNavigator:()=>getRegisteredNavigator,getRegisteredNavigatorNames:()=>getRegisteredNavigatorNames,getRegisteredNavigatorRole:()=>getRegisteredNavigatorRole,getRunsForSession:()=>getRunsForSession,getSrsBacklogDebug:()=>getSrsBacklogDebug,getStrategyPressureDebug:()=>getStrategyPressureDebug,hasRegisteredNavigator:()=>hasRegisteredNavigator,initializeNavigatorRegistry:()=>initializeNavigatorRegistry,isFilter:()=>isFilter,isGenerator:()=>isGenerator,mountPipelineDebugger:()=>mountPipelineDebugger,pipelineDebugAPI:()=>pipelineDebugAPI,registerNavigator:()=>registerNavigator,setDebugSessionId:()=>setDebugSessionId});function registerNavigator(e,t,n){navigatorRegistry.set(e,{constructor:t,role:n}),logger.debug(`[NavigatorRegistry] Registered: ${e}${n?` (${n})`:``}`)}function getRegisteredNavigator(e){return navigatorRegistry.get(e)?.constructor}function hasRegisteredNavigator(e){return navigatorRegistry.has(e)}function getRegisteredNavigatorRole(e){return navigatorRegistry.get(e)?.role}function getRegisteredFilterKind(e){return navigatorRegistry.get(e)?.constructor?.kind}function getRegisteredNavigatorNames(){return Array.from(navigatorRegistry.keys())}async function initializeNavigatorRegistry(){logger.debug(`[NavigatorRegistry] Initializing built-in navigators...`);let[e,t]=await Promise.all([Promise.resolve().then(()=>(init_elo(),elo_exports)),Promise.resolve().then(()=>(init_srs(),srs_exports))]),n=await Promise.resolve().then(()=>(init_prescribed(),prescribed_exports));registerNavigator(`elo`,e.default),registerNavigator(`srs`,t.default),registerNavigator(`prescribed`,n.default);let[r,a,o,s,c]=await Promise.all([Promise.resolve().then(()=>(init_hierarchyDefinition(),hierarchyDefinition_exports)),Promise.resolve().then(()=>(init_interferenceMitigator(),interferenceMitigator_exports)),Promise.resolve().then(()=>(init_relativePriority(),relativePriority_exports)),Promise.resolve().then(()=>(init_userTagPreference(),userTagPreference_exports)),Promise.resolve().then(()=>(init_eloDistance(),eloDistance_exports))]);registerNavigator(`hierarchyDefinition`,r.default),registerNavigator(`interferenceMitigator`,a.default),registerNavigator(`relativePriority`,o.default),registerNavigator(`userTagPreference`,s.default),registerNavigator(`eloDistance`,c.default),logger.debug(`[NavigatorRegistry] Initialized ${navigatorRegistry.size} navigators: ${getRegisteredNavigatorNames().join(`, `)}`)}function getCardOrigin(e){if(e.provenance.length===0)throw Error(`Card has no provenance - cannot determine origin`);let t=e.provenance[0].reason.toLowerCase();return t.includes(`failed`)?`failed`:t.includes(`review`)?`review`:`new`}function isGenerator(e){return NavigatorRoles[e]===`generator`?!0:getRegisteredNavigatorRole(e)===`generator`}function isFilter(e){return NavigatorRoles[e]===`filter`?!0:getRegisteredNavigatorRole(e)===`filter`}var navigatorRegistry,Navigators,NavigatorRole,NavigatorRoles,ContentNavigator,init_navigators=__esm({"src/core/navigators/index.ts"(){init_diversityRerank(),init_PipelineDebugger(),init_SrsDebugger(),init_StrategyPressureDebugger(),init_logger(),init_(),init_2(),init_3(),navigatorRegistry=new Map,Navigators=(e=>(e.ELO=`elo`,e.SRS=`srs`,e.PRESCRIBED=`prescribed`,e.HIERARCHY=`hierarchyDefinition`,e.INTERFERENCE=`interferenceMitigator`,e.RELATIVE_PRIORITY=`relativePriority`,e.USER_TAG_PREFERENCE=`userTagPreference`,e.ELO_DISTANCE=`eloDistance`,e))(Navigators||{}),NavigatorRole=(e=>(e.GENERATOR=`generator`,e.FILTER=`filter`,e))(NavigatorRole||{}),NavigatorRoles={elo:`generator`,srs:`generator`,prescribed:`generator`,hierarchyDefinition:`filter`,interferenceMitigator:`filter`,relativePriority:`filter`,userTagPreference:`filter`,eloDistance:`filter`},ContentNavigator=class{constructor(e,t,n){_defineProperty(this,`user`,void 0),_defineProperty(this,`course`,void 0),_defineProperty(this,`strategyName`,void 0),_defineProperty(this,`strategyId`,void 0),_defineProperty(this,`learnable`,void 0),_defineProperty(this,`staticWeight`,void 0),this.user=e,this.course=t,n&&(this.strategyName=n.name,this.strategyId=n._id,this.learnable=n.learnable,this.staticWeight=n.staticWeight)}get strategyKey(){return this.constructor.name}async getStrategyState(){if(!this.user||!this.course)throw Error(`Cannot get strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`);return this.user.getStrategyState(this.course.getCourseID(),this.strategyKey)}async putStrategyState(e){if(!this.user||!this.course)throw Error(`Cannot put strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`);return this.user.putStrategyState(this.course.getCourseID(),this.strategyKey,e)}static async create(e,t,n){let r=n.implementingClass,a=getRegisteredNavigator(r);if(a)return logger.debug(`[ContentNavigator.create] Using registered navigator: ${r}`),new a(e,t,n);logger.debug(`[ContentNavigator.create] Navigator not in registry, attempting dynamic import: ${r}`);let o;for(let e of[`.ts`,`.js`,``]){try{if(o=(await globImport_generators(`./generators/${r}${e}`)).default,o)break}catch(t){logger.debug(`Failed to load generator ${r}${e}:`,t)}try{if(o=(await globImport_filters(`./filters/${r}${e}`)).default,o)break}catch(t){logger.debug(`Failed to load filter ${r}${e}:`,t)}try{if(o=(await globImport(`./${r}${e}`)).default,o)break}catch(t){logger.debug(`Failed to load legacy ${r}${e}:`,t)}if(o)break}if(!o)throw Error(`Could not load navigator implementation for: ${r}`);return new o(e,t,n)}async getWeightedCards(e){throw Error(`${this.constructor.name} must implement getWeightedCards(). `)}setEphemeralHints(e){}}}});function randIntWeightedTowardZero(e){return Math.floor(Math.random()*Math.random()*Math.random()*e)}async function getCourseTagStubs(e){logger.debug(`Getting tag stubs for course: ${e}`);let t=await filterAllDocsByPrefix(getCourseDB2(e),`TAG`.valueOf()+`-`);return t.rows.forEach(e=>{logger.debug(` Tag stub for doc: ${e.id}`)}),t}async function createTag(e,t,n){logger.debug(`Creating tag: ${t}...`);let r=getTagID(t);return await getCourseDB2(e).put({course:e,docType:`TAG`,name:t,snippet:``,taggedCards:[],wiki:``,author:n,_id:r})}async function updateTag(e){let t=await getTag(e.course,e.name);return await getCourseDB2(e.course).put({...e,_rev:t._rev})}async function getTag(e,t){let n=getTagID(t);return getCourseDB2(e).get(n)}async function removeTagFromCard(e,t,n){n=getTagID(n);let r=getCourseDB2(e),a=await r.get(n);return a.taggedCards=a.taggedCards.filter(e=>t!==e),r.put(a)}async function getAppliedTags(e,t){return await getCourseDB2(e).query(`getTags`,{startkey:t,endkey:t})}async function updateCredentialledCourseConfig(e,t){logger.debug(`Updating course config:
254
+ 💡 Inspect: window.skuilder.pipeline`)}function logResultCards(e){if(!(!VERBOSE_RESULTS||e.length===0)){logger.info(`[Pipeline] Results (${e.length} cards):`);for(let t=0;t<e.length;t++){let n=e[t],r=n.tags?.slice(0,3).join(`, `)||``,a=n.provenance.filter(e=>e.strategy===`hierarchyDefinition`||e.strategy===`priorityDefinition`||e.strategy===`interferenceFilter`||e.strategy===`letterGating`||e.strategy===`ephemeralHint`||e.strategy===`diversityRerank`).map(e=>{let t=e.action===`boosted`?`↑`:e.action===`penalized`?`↓`:`=`;return`${e.strategyName}${t}${e.score.toFixed(2)}`}).join(` | `);logger.info(`[Pipeline] ${String(t+1).padStart(2)}. ${n.score.toFixed(4)} ${n.cardId} [${r}]${a?` {${a}}`:``}`)}}}function logCardProvenance(e,t=3){let n=e.slice(0,t);logger.debug(`[Pipeline] Provenance for top ${n.length} cards:`);for(let e of n){logger.debug(`[Pipeline] ${e.cardId} (final score: ${e.score.toFixed(3)}):`);for(let t of e.provenance){let e=t.score.toFixed(3),n=t.action.padEnd(9);logger.debug(`[Pipeline] ${n} ${e} - ${t.strategyName}: ${t.reason}`)}}}var VERBOSE_RESULTS,Pipeline,init_Pipeline=__esm({"src/core/navigators/Pipeline.ts"(){init_navigators(),init_logger(),init_orchestration(),init_PipelineDebugger(),init_diversityRerank(),init_regulators(),init_SrsDebugger(),VERBOSE_RESULTS=!0,Pipeline=class extends ContentNavigator{constructor(e,t,n,r){super(),_defineProperty(this,`generator`,void 0),_defineProperty(this,`filters`,void 0),_defineProperty(this,`_cachedOrchestration`,null),_defineProperty(this,`strategyHash`,void 0),_defineProperty(this,`_tagCache`,new Map),_defineProperty(this,`_ephemeralHints`,null),_defineProperty(this,`_intakeClock`,null),_defineProperty(this,`_intakeClockWrite`,Promise.resolve()),this.generator=e,this.filters=t,this.user=n,this.course=r,r.getCourseConfig().then(e=>{logger.debug(`[pipeline] Crated pipeline for ${e.name}`)}).catch(e=>{logger.error(`[pipeline] Failed to lookup courseCfg: ${e}`)}),logPipelineConfig(e,t),registerPipelineForDebug(this)}setEphemeralHints(e){this._ephemeralHints=e,logger.info(`[Pipeline] Ephemeral hints set: ${JSON.stringify(e)}`)}async getWeightedCards(e){let t=performance.now(),n=await this.buildContext(),r=performance.now(),a=500;logger.debug(`[Pipeline] Fetching 500 candidates from generator '${this.generator.name}'`);let o=await this.generator.getWeightedCards(500,n),s=o.cards,c=performance.now(),l=s.length;this._ephemeralHints=mergeHints2([this._ephemeralHints,o.hints])??null;let u;if(this.generator.generators){let e=new Map;for(let t of s){let n=t.provenance[0];if(n){let r=n.strategyName;e.has(r)||e.set(r,{cards:[]}),e.get(r).cards.push(t)}}u=Array.from(e.entries()).map(([e,t])=>{let n=t.cards.filter(e=>e.reviewID).length;return{name:e,cardCount:t.cards.length,newCount:t.cards.length-n,reviewCount:n,topScore:Math.max(...t.cards.map(e=>e.score),0)}})}logger.debug(`[Pipeline] Generator returned ${l} candidates`),s=await this.hydrateTags(s);let d=performance.now(),p=[...s],m=this._ephemeralHints;if(m?.requireCards?.length){let e=new Set(p.map(e=>e.cardId)),t=m.requireCards.filter(t=>!t.includes(`*`)&&!e.has(t));if(t.length>0){let e=await this.course.getAppliedTagsBatch(t),n=this.course.getCourseID();for(let r of t)p.push({cardId:r,courseId:n,score:1,tags:e.get(r)??[],provenance:[]});logger.info(`[Pipeline] Pre-fetched ${t.length} required card(s) into pool: ${t.join(`, `)}`)}}let g=new Set(s.filter(e=>e.provenance.some(e=>e.strategy===`prescribed`)).map(e=>e.cardId)),_=[],v=new Map(s.map(e=>[e.cardId,e.score])),y=new Set;for(let e of this.filters){let t=s.length,r=new Map(s.map(e=>[e.cardId,e.score]));s=await e.transform(s,n);let a=0,o=0,c=0,l=t-s.length,u=e.kind??`gate`;for(let e of s){let t=r.get(e.cardId)??0;e.score>t?a++:e.score<t?(o++,u===`gate`&&y.add(e.cardId)):c++}if(_.push({name:e.name,kind:u,boosted:a,penalized:o,passed:c,removed:l}),g.size>0){let t=new Set(s.map(e=>e.cardId)),n=[...g].filter(e=>!t.has(e)),r=s.filter(e=>g.has(e.cardId)&&e.score===0).map(e=>e.cardId);(n.length>0||r.length>0)&&(logger.info(`[Pipeline] Filter '${e.name}' impact on prescribed cards: `+(n.length>0?`removed=[${n.join(`, `)}] `:``)+(r.length>0?`zeroed=[${r.join(`, `)}]`:``)),n.forEach(e=>g.delete(e)))}logger.debug(`[Pipeline] Filter '${e.name}': ${r.size} \u2192 ${s.length} cards (\u2191${a} \u2193${o} =${c})`)}let b=s;s=s.filter(e=>e.score>0);let x=await this.regulate(s,v,y),S=this._ephemeralHints;S&&(this._ephemeralHints=null,s=this.applyHints(s,S,p)),s=diversityRerank(s),s.sort((e,t)=>t.score-e.score);let C=performance.now(),w=s.slice(0,e);logger.info(`[Pipeline:timing] total=${(C-t).toFixed(0)}ms (context=${(r-t).toFixed(0)} generate=${(c-r).toFixed(0)} hydrate=${(d-c).toFixed(0)} filter=${(C-d).toFixed(0)})`);let T=w.slice(0,3).map(e=>e.score);logExecutionSummary(this.generator.name,l,this.filters.length,w.length,T,_),logResultCards(w),logCardProvenance(w,3);try{let e=await this.course?.getCourseConfig().catch(()=>void 0),t=e?.name,r=buildRunReport(this.course?.getCourseID()||`unknown`,t,this.generator.name,u,l,_,s,w,n.userElo,S??void 0,b,x),a={...this.strategyHash?{strategies:this.strategyHash}:{},...e?.contentVersion?{content:e.contentVersion}:{}};captureRun({...r,...Object.keys(a).length?{versions:a}:{}})}catch(e){logger.debug(`[Pipeline] Failed to capture debug run: ${e}`)}return{cards:w}}async hydrateTags(e){if(e.length===0)return e;let t=[];for(let n of e)this._tagCache.has(n.cardId)||t.push(n.cardId);if(t.length>0){let e=await this.course.getAppliedTagsBatch(t);for(let[t,n]of e)this._tagCache.set(t,n)}let n=new Map;for(let t of e)n.set(t.cardId,this._tagCache.get(t.cardId)??[]);return logTagHydration(e,n),e.map(e=>({...e,tags:this._tagCache.get(e.cardId)??[]}))}applyHints(e,t,n){let r=e.length;if(t.excludeCards?.length&&(e=e.filter(e=>!t.excludeCards.some(t=>globMatch(e.cardId,t)))),t.excludeTags?.length&&(e=e.filter(e=>!t.excludeTags.some(t=>cardMatchesTagPattern(e,t)))),t.boostTags)for(let[n,r]of Object.entries(t.boostTags))for(let a of e)cardMatchesTagPattern(a,n)&&(a.score*=r,a.provenance.push({strategy:`ephemeralHint`,strategyId:`ephemeral-hint`,strategyName:t._label?`Replan Hint (${t._label})`:`Replan Hint`,action:`boosted`,score:a.score,reason:`boostTag ${n} \xD7${r}`}));if(t.boostCards)for(let[n,r]of Object.entries(t.boostCards))for(let a of e)globMatch(a.cardId,n)&&(a.score*=r,a.provenance.push({strategy:`ephemeralHint`,strategyId:`ephemeral-hint`,strategyName:t._label?`Replan Hint (${t._label})`:`Replan Hint`,action:`boosted`,score:a.score,reason:`boostCard ${n} \xD7${r}`}));let a=new Set(e.map(e=>e.cardId)),o=new Map(e.map(e=>[e.cardId,e])),s=t._label?`Replan Hint (${t._label})`:`Replan Hint`,applyRequirement=(t,n)=>{let r=1/0,c=o.get(t.cardId);c?c.score<r&&(c.score=r,c.provenance.push({strategy:`ephemeralHint`,strategyId:`ephemeral-hint`,strategyName:s,action:`boosted`,score:r,reason:`${n} (upgrade to mandatory score)`})):(e.push({...t,score:r,provenance:[...t.provenance,{strategy:`ephemeralHint`,strategyId:`ephemeral-hint`,strategyName:s,action:`boosted`,score:r,reason:n}]}),a.add(t.cardId),o.set(t.cardId,e[e.length-1]))};if(t.requireCards?.length)for(let e of t.requireCards){for(let t of a)globMatch(t,e)&&applyRequirement(o.get(t),`requireCard ${e}`);for(let t of n)globMatch(t.cardId,e)&&applyRequirement(t,`requireCard ${e}`)}if(t.requireTags?.length)for(let e of t.requireTags){for(let t of a){let n=o.get(t);cardMatchesTagPattern(n,e)&&applyRequirement(n,`requireTag ${e}`)}for(let t of n)cardMatchesTagPattern(t,e)&&applyRequirement(t,`requireTag ${e}`)}return logger.info(`[Pipeline] Hints applied: ${r} \u2192 ${e.length} cards`),e}async regulate(e,t,n){let r=DEFAULT_REGULATOR_CONFIG,a=e.filter(e=>e.reviewID),o=e.filter(e=>!e.reviewID),s=o.filter(e=>!n.has(e.cardId)),c=reviewMassReading(a,t,r.reviewMass);applyReading(a,c),noteReviewPressure(this.course.getCourseID(),{mass:c.urgency,healthyMass:r.reviewMass.healthyMass,rate:r.reviewMass.rate,multiplier:c.multiplier});let l=Date.now(),u=await this.loadIntakeClock(l),d=stepIntakeClock(u,l,s.length);d!==u&&this.saveIntakeClock(d);let p=intakeReading(d,l,{eligibleNew:s.length,newCandidates:o.length},r.intake);return applyReading(s,p),logger.info(`[Pipeline:regulators] review mass ${c.urgency.toFixed(1)} over ${a.length} due \u2192 \xD7${c.multiplier.toFixed(2)}; intake ${p.urgency.toFixed(1)}h, ${s.length}/${o.length} new eligible \u2192 \xD7${p.multiplier.toFixed(2)}`),[c,p]}notePresented(e){e.status!==`new`||e.courseId!==this.course?.getCourseID()||this.saveIntakeClock(resetIntakeClock(Date.now()))}async loadIntakeClock(e){if(this._intakeClock)return this._intakeClock;let t=null;try{t=await this.user.getStrategyState(this.course.getCourseID(),INTAKE_CLOCK_KEY)}catch(e){logger.warn(`[Pipeline:regulators] Could not read the intake clock: ${e}`)}return t?this._intakeClock=t:this.saveIntakeClock(resetIntakeClock(e)),this._intakeClock}saveIntakeClock(e){this._intakeClock=e;let t=this.course.getCourseID();this._intakeClockWrite=this._intakeClockWrite.then(()=>this.user.putStrategyState(t,INTAKE_CLOCK_KEY,e)).catch(e=>logger.warn(`[Pipeline:regulators] Could not save the intake clock: ${e}`))}async buildContext(){let e=1e3,t;try{t=toCourseElo((await this.user.getCourseRegDoc(this.course.getCourseID())).elo),e=t.global.score}catch(e){logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`)}this._cachedOrchestration||(this._cachedOrchestration=await createOrchestrationContext(this.user,this.course));let n=this._cachedOrchestration;return{user:this.user,course:this.course,userElo:e,...t?{userCourseElo:t}:{},orchestration:n}}getCourseID(){return this.course.getCourseID()}async getOrchestrationContext(){return createOrchestrationContext(this.user,this.course)}getStrategyIds(){let e=[],extractId=e=>e.strategyId?e.strategyId:null,t=extractId(this.generator);t&&e.push(t),this.generator.generators&&Array.isArray(this.generator.generators)&&this.generator.generators.forEach(t=>{let n=extractId(t);n&&e.push(n)});for(let t of this.filters){let n=extractId(t);n&&e.push(n)}return[...new Set(e)]}async getTagEloStatus(e){let t=toCourseElo((await this.user.getCourseRegDoc(this.course.getCourseID())).elo),n={};if(e){let r=Array.isArray(e)?e:[e];for(let e of r){let r=globToRegex(e);for(let[e,a]of Object.entries(t.tags))r.test(e)&&(n[e]={score:a.score,count:a.count})}}else for(let[e,r]of Object.entries(t.tags))n[e]={score:r.score,count:r.count};return n}async forecast(e){let t=e?.threshold??.1,n=e?.unseenOnly??!0,r=this.course.getCourseID(),a=(await this.course.getAllCardIds()).map(e=>({cardId:e,courseId:r,score:1,provenance:[]}));a=await this.hydrateTags(a);let o=a.slice(),s=await this.buildContext();for(let e of this.forecastFilters())a=await e.transform(a,s);if(e?.hints&&(a=this.applyHints(a,e.hints,o)),a=a.filter(e=>e.score>=t),n){let e;try{e=new Set(await this.user.getSeenCards(r))}catch{e=new Set}a=a.filter(t=>!e.has(t.cardId))}return a.sort((e,t)=>t.score-e.score),e?.limit?a.slice(0,e.limit):a}forecastFilters(){return this.filters.filter(e=>!e.liveOnly)}async diagnoseCardSpace(e){let t=e?.threshold??.1,n=performance.now(),r=await this.course.getAllCardIds(),a=r.map(e=>({cardId:e,courseId:this.course.getCourseID(),score:1,provenance:[]}));a=await this.hydrateTags(a);let o=await this.buildContext(),s=[];for(let e of this.forecastFilters()){a=await e.transform(a,o);let n=a.filter(e=>e.score>=t).length;s.push({name:e.name,wellIndicated:n})}let c=a.filter(e=>e.score>=t),l=new Set(c.map(e=>e.cardId)),u;try{let e=this.course.getCourseID(),t=await this.user.getSeenCards(e);u=new Set(t)}catch{u=new Set}let d=c.filter(e=>!u.has(e.cardId)),p=new Map;for(let e of a){let n=e.cardId.split(`-`)[1]||`unknown`;p.has(n)||p.set(n,{total:0,wellIndicated:0,new:0});let r=p.get(n);r.total++,e.score>=t&&(r.wellIndicated++,u.has(e.cardId)||r.new++)}let m=performance.now()-n,g={totalCards:r.length,threshold:t,wellIndicated:l.size,encountered:u.size,wellIndicatedNew:d.length,byType:Object.fromEntries(p),filterBreakdown:s,elapsedMs:Math.round(m)};logger.info(`[Pipeline:diagnose] Card space scan (${g.elapsedMs}ms):`),logger.info(`[Pipeline:diagnose] Total cards: ${g.totalCards}`),logger.info(`[Pipeline:diagnose] Well-indicated (score >= ${t}): ${g.wellIndicated}`),logger.info(`[Pipeline:diagnose] Encountered: ${g.encountered}`),logger.info(`[Pipeline:diagnose] Well-indicated & new: ${g.wellIndicatedNew}`),logger.info(`[Pipeline:diagnose] By type:`);for(let[e,t]of p)logger.info(`[Pipeline:diagnose] ${e}: ${t.wellIndicated}/${t.total} well-indicated, ${t.new} new`);logger.info(`[Pipeline:diagnose] After each filter:`);for(let e of s)logger.info(`[Pipeline:diagnose] ${e.name}: ${e.wellIndicated} well-indicated`);return g}}}});function setAppVersion(e){hostAppVersion=e}function sessionVersions(){return{framework:FRAMEWORK_VERSION,...hostAppVersion?{app:hostAppVersion}:{}}}function stableStringify(e){return Array.isArray(e)?`[${e.map(stableStringify).join(`,`)}]`:e&&typeof e==`object`?`{${Object.entries(e).filter(([,e])=>e!==void 0).sort(([e],[t])=>e<t?-1:e>t?1:0).map(([e,t])=>`${JSON.stringify(e)}:${stableStringify(t)}`).join(`,`)}}`:JSON.stringify(e)}function strategyHash(e){if(e.length===0)return DEFAULT_STRATEGY_HASH;let t=e.map(e=>{let{_rev:t,...n}=e;return stableStringify(n)}).sort().join(`
255
+ `),n=2166136261;for(let e=0;e<t.length;e++)n^=t.charCodeAt(e),n=Math.imul(n,16777619);return(n>>>0).toString(16).padStart(8,`0`)}var FRAMEWORK_VERSION,hostAppVersion,DEFAULT_STRATEGY_HASH,init_versionStamps=__esm({"src/core/versionStamps.ts"(){FRAMEWORK_VERSION=`0.2.33`,DEFAULT_STRATEGY_HASH=`default`}}),defaults_exports={};__export(defaults_exports,{createDefaultEloDistanceStrategy:()=>createDefaultEloDistanceStrategy,createDefaultEloStrategy:()=>createDefaultEloStrategy,createDefaultPipeline:()=>createDefaultPipeline,createDefaultSrsStrategy:()=>createDefaultSrsStrategy});function createDefaultEloStrategy(e){return{_id:`NAVIGATION_STRATEGY-ELO-default`,docType:`NAVIGATION_STRATEGY`,name:`ELO (default)`,description:`Default ELO-based navigation strategy for new cards`,implementingClass:`elo`,course:e,serializedData:``}}function createDefaultSrsStrategy(e){return{_id:`NAVIGATION_STRATEGY-SRS-default`,docType:`NAVIGATION_STRATEGY`,name:`SRS (default)`,description:`Default SRS-based navigation strategy for reviews`,implementingClass:`srs`,course:e,serializedData:``}}function createDefaultEloDistanceStrategy(e){return{_id:`NAVIGATION_STRATEGY-eloDistance-default`,docType:`NAVIGATION_STRATEGY`,name:`ELO Distance (default)`,description:`Scales every candidate, new or review, by its distance from the learner's ELO`,implementingClass:`eloDistance`,course:e,serializedData:JSON.stringify(DEFAULT_ELO_DISTANCE_CONFIG)}}function createDefaultPipeline(e,t){let n=t.getCourseID(),r=new ELONavigator(e,t,createDefaultEloStrategy(n)),a=new SRSNavigator(e,t,createDefaultSrsStrategy(n)),o=new CompositeGenerator([r,a]),s=new EloDistanceFilter(e,t,createDefaultEloDistanceStrategy(n)),c=new Pipeline(o,[s],e,t);return c.strategyHash=DEFAULT_STRATEGY_HASH,c}var init_defaults=__esm({"src/core/navigators/defaults.ts"(){init_navigators(),init_Pipeline(),init_CompositeGenerator(),init_elo(),init_srs(),init_eloDistance(),init_types_legacy(),init_versionStamps()}}),pipelinePlan_exports={};__export(pipelinePlan_exports,{PIPELINE_STAGES:()=>PIPELINE_STAGES,planPipeline:()=>planPipeline});function planned(e,t,n){let r=t===`filter`?getRegisteredFilterKind(e.implementingClass):void 0;return{role:t,origin:n,name:e.name,implementingClass:e.implementingClass,strategy:e,...r?{kind:r}:{}}}function planPipeline(e,t){if(e.length===0)return{kind:`default`,generators:[planned(createDefaultEloStrategy(t),`generator`,`default-pipeline`),planned(createDefaultSrsStrategy(t),`generator`,`default-pipeline`)],filters:[planned(createDefaultEloDistanceStrategy(t),`filter`,`default-pipeline`)],skipped:[],warnings:[],notes:[],regulators:DEFAULT_REGULATOR_CONFIG};let n=[],r=[],a=[],o=[];for(let t of e)isGenerator(t.implementingClass)?n.push(planned(t,`generator`,`strategy-doc`)):isFilter(t.implementingClass)?r.push(planned(t,`filter`,`strategy-doc`)):(a.push({strategy:t,reason:`not a registered generator or filter`}),o.push(`Unknown strategy type '${t.implementingClass}', skipping: ${t.name}`));let s=new Set(n.map(e=>e.implementingClass));s.has(createDefaultEloStrategy(t).implementingClass)||n.push(planned(createDefaultEloStrategy(t),`generator`,`assembler-default`)),s.has(createDefaultSrsStrategy(t).implementingClass)||n.push(planned(createDefaultSrsStrategy(t),`generator`,`assembler-default`));let c=createDefaultEloDistanceStrategy(t);return r.some(e=>e.implementingClass===c.implementingClass)||r.push(planned(c,`filter`,`assembler-default`)),r.sort((e,t)=>e.name.localeCompare(t.name)),{kind:`assembled`,generators:n,filters:r,skipped:a,warnings:o,notes:[],regulators:DEFAULT_REGULATOR_CONFIG}}var PIPELINE_STAGES,init_pipelinePlan=__esm({"src/core/navigators/pipelinePlan.ts"(){init_navigators(),init_regulators(),init_defaults(),PIPELINE_STAGES=[{key:`generate`,title:`Generate`,summary:`Each generator proposes candidates (up to 500 in all), scored on what is specific to its source. A card proposed by several generators keeps their mean score, raised 10% per extra generator.`},{key:`filter`,title:`Filter`,summary:`Each filter multiplies candidate scores, in the order shown. A gate says a card is not ready yet; a signal expresses preference. Gates usually penalize rather than remove, so a gated card stays in the pool at a low score.`},{key:`drop-zero`,title:`Drop zero scores`,summary:`Candidates whose score reached 0 leave the pool.`},{key:`regulate`,title:`Regulate`,summary:`Balances reviews against new cards. Review mass: the due reviews weighed by their filtered scores; above a healthy level, every review is lifted. Intake: hours since a new card was last presented; new cards no gate penalized are lifted, and the clock stops while there are none.`},{key:`hints`,title:`Apply hints`,summary:`The session's hints (from the app: an intro's follow-up, a difficulty boost) exclude, boost, or require cards. Required cards skip the filters entirely.`},{key:`diversity`,title:`Diversity re-rank`,summary:`Demotes candidates that repeat a distinctive tag already ranked above them, so one concept or answer cannot take the whole head of the queue. Sees this run only, not what the session already served.`},{key:`select`,title:`Select`,summary:`Highest scores first, up to the run's limit. The session mixes them into its supply queue.`}]}}),PipelineAssembler_exports={};__export(PipelineAssembler_exports,{PipelineAssembler:()=>PipelineAssembler});var PipelineAssembler,init_PipelineAssembler=__esm({"src/core/navigators/PipelineAssembler.ts"(){init_navigators(),init_WeightedFilter(),init_Pipeline(),init_logger(),init_CompositeGenerator(),init_pipelinePlan(),init_versionStamps(),PipelineAssembler=class{async assemble(e){let{strategies:t,user:n,course:r}=e,a=[];if(t.length===0)return{pipeline:null,generatorStrategies:[],filterStrategies:[],warnings:a};let o=planPipeline(t,r.getCourseID());a.push(...o.warnings);for(let e of[...o.generators,...o.filters])e.origin===`assembler-default`&&logger.debug(`[PipelineAssembler] No ${e.implementingClass} ${e.role} configured, adding default`);let s=o.generators.map(e=>e.strategy),c=o.filters.map(e=>e.strategy);if(s.length===0)return a.push(`No generator strategy found`),{pipeline:null,generatorStrategies:[],filterStrategies:[],warnings:a};let l;s.length===1?(l=await ContentNavigator.create(n,r,s[0]),logger.debug(`[PipelineAssembler] Using single generator: ${s[0].name}`)):(logger.debug(`[PipelineAssembler] Using CompositeGenerator for ${s.length} generators: ${s.map(e=>e.name).join(`, `)}`),l=await CompositeGenerator.fromStrategies(n,r,s));let u=[];for(let e of c)try{let t=await ContentNavigator.create(n,r,e);if(`transform`in t&&typeof t.transform==`function`){let n=t;e.learnable&&(n=new WeightedFilter(n,e.learnable,e.staticWeight,e._id)),u.push(n),logger.debug(`[PipelineAssembler] Added filter: ${e.name}`)}else a.push(`Filter '${e.name}' does not implement CardFilter.transform(), skipping`)}catch(t){a.push(`Failed to instantiate filter '${e.name}': ${t}`)}let d=new Pipeline(l,u,n,r);return d.strategyHash=strategyHash(t),logger.debug(`[PipelineAssembler] Assembled pipeline with ${s.length} generator(s) and ${u.length} filter(s)`),{pipeline:d,generatorStrategies:s,filterStrategies:c,warnings:a}}}}}),globImport,init_3=__esm({'import("./**/*") in src/core/navigators/index.ts'(){globImport=__glob({"./Pipeline.ts":()=>Promise.resolve().then(()=>(init_Pipeline(),Pipeline_exports)),"./PipelineAssembler.ts":()=>Promise.resolve().then(()=>(init_PipelineAssembler(),PipelineAssembler_exports)),"./PipelineDebugger.ts":()=>Promise.resolve().then(()=>(init_PipelineDebugger(),PipelineDebugger_exports)),"./SrsDebugger.ts":()=>Promise.resolve().then(()=>(init_SrsDebugger(),SrsDebugger_exports)),"./StrategyPressureDebugger.ts":()=>Promise.resolve().then(()=>(init_StrategyPressureDebugger(),StrategyPressureDebugger_exports)),"./defaults.ts":()=>Promise.resolve().then(()=>(init_defaults(),defaults_exports)),"./diversityRerank.ts":()=>Promise.resolve().then(()=>(init_diversityRerank(),diversityRerank_exports)),"./filters/WeightedFilter.ts":()=>Promise.resolve().then(()=>(init_WeightedFilter(),WeightedFilter_exports)),"./filters/eloDistance.ts":()=>Promise.resolve().then(()=>(init_eloDistance(),eloDistance_exports)),"./filters/hierarchyDefinition.ts":()=>Promise.resolve().then(()=>(init_hierarchyDefinition(),hierarchyDefinition_exports)),"./filters/index.ts":()=>Promise.resolve().then(()=>(init_filters(),filters_exports)),"./filters/inferredPreferenceStub.ts":()=>Promise.resolve().then(()=>(init_inferredPreferenceStub(),inferredPreferenceStub_exports)),"./filters/interferenceMitigator.ts":()=>Promise.resolve().then(()=>(init_interferenceMitigator(),interferenceMitigator_exports)),"./filters/relativePriority.ts":()=>Promise.resolve().then(()=>(init_relativePriority(),relativePriority_exports)),"./filters/types.ts":()=>Promise.resolve().then(()=>(init_types2(),types_exports2)),"./filters/userGoalStub.ts":()=>Promise.resolve().then(()=>(init_userGoalStub(),userGoalStub_exports)),"./filters/userTagPreference.ts":()=>Promise.resolve().then(()=>(init_userTagPreference(),userTagPreference_exports)),"./generators/CompositeGenerator.ts":()=>Promise.resolve().then(()=>(init_CompositeGenerator(),CompositeGenerator_exports)),"./generators/elo.ts":()=>Promise.resolve().then(()=>(init_elo(),elo_exports)),"./generators/index.ts":()=>Promise.resolve().then(()=>(init_generators(),generators_exports)),"./generators/prescribed.ts":()=>Promise.resolve().then(()=>(init_prescribed(),prescribed_exports)),"./generators/srs.ts":()=>Promise.resolve().then(()=>(init_srs(),srs_exports)),"./generators/types.ts":()=>Promise.resolve().then(()=>(init_types(),types_exports)),"./index.ts":()=>Promise.resolve().then(()=>(init_navigators(),navigators_exports)),"./pipelinePlan.ts":()=>Promise.resolve().then(()=>(init_pipelinePlan(),pipelinePlan_exports)),"./regulators.ts":()=>Promise.resolve().then(()=>(init_regulators(),regulators_exports))})}}),navigators_exports={};__export(navigators_exports,{ContentNavigator:()=>ContentNavigator,DIVERSITY_FLOOR:()=>DIVERSITY_FLOOR,DIVERSITY_STRENGTH:()=>DIVERSITY_STRENGTH,NavigatorRole:()=>NavigatorRole,NavigatorRoles:()=>NavigatorRoles,Navigators:()=>Navigators,captureStrategyPressure:()=>captureStrategyPressure,clearSrsBacklogDebug:()=>clearSrsBacklogDebug,clearStrategyPressureDebug:()=>clearStrategyPressureDebug,diversityRerank:()=>diversityRerank,drainCapturedRuns:()=>drainCapturedRuns,getActivePipeline:()=>getActivePipeline,getCardOrigin:()=>getCardOrigin,getRegisteredFilterKind:()=>getRegisteredFilterKind,getRegisteredNavigator:()=>getRegisteredNavigator,getRegisteredNavigatorNames:()=>getRegisteredNavigatorNames,getRegisteredNavigatorRole:()=>getRegisteredNavigatorRole,getRunsForSession:()=>getRunsForSession,getSrsBacklogDebug:()=>getSrsBacklogDebug,getStrategyPressureDebug:()=>getStrategyPressureDebug,hasRegisteredNavigator:()=>hasRegisteredNavigator,initializeNavigatorRegistry:()=>initializeNavigatorRegistry,isFilter:()=>isFilter,isGenerator:()=>isGenerator,mountPipelineDebugger:()=>mountPipelineDebugger,pipelineDebugAPI:()=>pipelineDebugAPI,registerNavigator:()=>registerNavigator,setDebugSessionId:()=>setDebugSessionId});function registerNavigator(e,t,n){navigatorRegistry.set(e,{constructor:t,role:n}),logger.debug(`[NavigatorRegistry] Registered: ${e}${n?` (${n})`:``}`)}function getRegisteredNavigator(e){return navigatorRegistry.get(e)?.constructor}function hasRegisteredNavigator(e){return navigatorRegistry.has(e)}function getRegisteredNavigatorRole(e){return navigatorRegistry.get(e)?.role}function getRegisteredFilterKind(e){return navigatorRegistry.get(e)?.constructor?.kind}function getRegisteredNavigatorNames(){return Array.from(navigatorRegistry.keys())}async function initializeNavigatorRegistry(){logger.debug(`[NavigatorRegistry] Initializing built-in navigators...`);let[e,t]=await Promise.all([Promise.resolve().then(()=>(init_elo(),elo_exports)),Promise.resolve().then(()=>(init_srs(),srs_exports))]),n=await Promise.resolve().then(()=>(init_prescribed(),prescribed_exports));registerNavigator(`elo`,e.default),registerNavigator(`srs`,t.default),registerNavigator(`prescribed`,n.default);let[r,a,o,s,c]=await Promise.all([Promise.resolve().then(()=>(init_hierarchyDefinition(),hierarchyDefinition_exports)),Promise.resolve().then(()=>(init_interferenceMitigator(),interferenceMitigator_exports)),Promise.resolve().then(()=>(init_relativePriority(),relativePriority_exports)),Promise.resolve().then(()=>(init_userTagPreference(),userTagPreference_exports)),Promise.resolve().then(()=>(init_eloDistance(),eloDistance_exports))]);registerNavigator(`hierarchyDefinition`,r.default),registerNavigator(`interferenceMitigator`,a.default),registerNavigator(`relativePriority`,o.default),registerNavigator(`userTagPreference`,s.default),registerNavigator(`eloDistance`,c.default),logger.debug(`[NavigatorRegistry] Initialized ${navigatorRegistry.size} navigators: ${getRegisteredNavigatorNames().join(`, `)}`)}function getCardOrigin(e){if(e.provenance.length===0)throw Error(`Card has no provenance - cannot determine origin`);let t=e.provenance[0].reason.toLowerCase();return t.includes(`failed`)?`failed`:t.includes(`review`)?`review`:`new`}function isGenerator(e){return NavigatorRoles[e]===`generator`?!0:getRegisteredNavigatorRole(e)===`generator`}function isFilter(e){return NavigatorRoles[e]===`filter`?!0:getRegisteredNavigatorRole(e)===`filter`}var navigatorRegistry,Navigators,NavigatorRole,NavigatorRoles,ContentNavigator,init_navigators=__esm({"src/core/navigators/index.ts"(){init_diversityRerank(),init_PipelineDebugger(),init_SrsDebugger(),init_StrategyPressureDebugger(),init_logger(),init_(),init_2(),init_3(),navigatorRegistry=new Map,Navigators=(e=>(e.ELO=`elo`,e.SRS=`srs`,e.PRESCRIBED=`prescribed`,e.HIERARCHY=`hierarchyDefinition`,e.INTERFERENCE=`interferenceMitigator`,e.RELATIVE_PRIORITY=`relativePriority`,e.USER_TAG_PREFERENCE=`userTagPreference`,e.ELO_DISTANCE=`eloDistance`,e))(Navigators||{}),NavigatorRole=(e=>(e.GENERATOR=`generator`,e.FILTER=`filter`,e))(NavigatorRole||{}),NavigatorRoles={elo:`generator`,srs:`generator`,prescribed:`generator`,hierarchyDefinition:`filter`,interferenceMitigator:`filter`,relativePriority:`filter`,userTagPreference:`filter`,eloDistance:`filter`},ContentNavigator=class{constructor(e,t,n){_defineProperty(this,`user`,void 0),_defineProperty(this,`course`,void 0),_defineProperty(this,`strategyName`,void 0),_defineProperty(this,`strategyId`,void 0),_defineProperty(this,`learnable`,void 0),_defineProperty(this,`staticWeight`,void 0),this.user=e,this.course=t,n&&(this.strategyName=n.name,this.strategyId=n._id,this.learnable=n.learnable,this.staticWeight=n.staticWeight)}get strategyKey(){return this.constructor.name}async getStrategyState(){if(!this.user||!this.course)throw Error(`Cannot get strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`);return this.user.getStrategyState(this.course.getCourseID(),this.strategyKey)}async putStrategyState(e){if(!this.user||!this.course)throw Error(`Cannot put strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`);return this.user.putStrategyState(this.course.getCourseID(),this.strategyKey,e)}static async create(e,t,n){let r=n.implementingClass,a=getRegisteredNavigator(r);if(a)return logger.debug(`[ContentNavigator.create] Using registered navigator: ${r}`),new a(e,t,n);logger.debug(`[ContentNavigator.create] Navigator not in registry, attempting dynamic import: ${r}`);let o;for(let e of[`.ts`,`.js`,``]){try{if(o=(await globImport_generators(`./generators/${r}${e}`)).default,o)break}catch(t){logger.debug(`Failed to load generator ${r}${e}:`,t)}try{if(o=(await globImport_filters(`./filters/${r}${e}`)).default,o)break}catch(t){logger.debug(`Failed to load filter ${r}${e}:`,t)}try{if(o=(await globImport(`./${r}${e}`)).default,o)break}catch(t){logger.debug(`Failed to load legacy ${r}${e}:`,t)}if(o)break}if(!o)throw Error(`Could not load navigator implementation for: ${r}`);return new o(e,t,n)}async getWeightedCards(e){throw Error(`${this.constructor.name} must implement getWeightedCards(). `)}setEphemeralHints(e){}}}});function randIntWeightedTowardZero(e){return Math.floor(Math.random()*Math.random()*Math.random()*e)}async function getCourseTagStubs(e){logger.debug(`Getting tag stubs for course: ${e}`);let t=await filterAllDocsByPrefix(getCourseDB2(e),`TAG`.valueOf()+`-`);return t.rows.forEach(e=>{logger.debug(` Tag stub for doc: ${e.id}`)}),t}async function createTag(e,t,n){logger.debug(`Creating tag: ${t}...`);let r=getTagID(t);return await getCourseDB2(e).put({course:e,docType:`TAG`,name:t,snippet:``,taggedCards:[],wiki:``,author:n,_id:r})}async function updateTag(e){let t=await getTag(e.course,e.name);return await getCourseDB2(e.course).put({...e,_rev:t._rev})}async function getTag(e,t){let n=getTagID(t);return getCourseDB2(e).get(n)}async function removeTagFromCard(e,t,n){n=getTagID(n);let r=getCourseDB2(e),a=await r.get(n);return a.taggedCards=a.taggedCards.filter(e=>t!==e),r.put(a)}async function getAppliedTags(e,t){return await getCourseDB2(e).query(`getTags`,{startkey:t,endkey:t})}async function updateCredentialledCourseConfig(e,t){logger.debug(`Updating course config:
255
256
 
256
257
  ${JSON.stringify(t)}
257
258
  `);let n=getCourseDB2(e),r=await getCredentialledCourseConfig(e);return await n.put({...t,_rev:r._rev})}function isSuccessRow(e){return`doc`in e&&e.doc!==null&&e.doc!==void 0}var CoursesDB,CourseDB,init_courseDB=__esm({"src/impl/couch/courseDB.ts"(){init_couch(),init_updateQueue(),init_types_legacy(),init_logger(),init_clientCache(),init_courseAPI(),init_courseLookupDB(),init_navigators(),init_PipelineAssembler(),init_defaults(),CoursesDB=class{constructor(e){_defineProperty(this,`_courseIDs`,void 0),e&&e.length>0?this._courseIDs=e:this._courseIDs=void 0}async getCourseList(){let e=await CourseLookup.allCourseWare();return logger.debug(`AllCourses: ${e.map(e=>e.name+`, `+e._id+`
@@ -268,17 +269,17 @@ ${o.rows.map(e=>` ${e.id}-${e.key}
268
269
  reason: ${t.reason}
269
270
  message: ${t.message}`),{status:Status.error,message:`Error adding note to course. ${e.reason||t.message}`}}}async getCourseDoc(e,t){return await this.db.get(e,t??{})}async getCourseDocs(e,t={}){return await this.db.allDocs({...t,keys:e})}getNavigationStrategy(e){if(logger.debug(`[courseDB] Getting navigation strategy: ${e}`),e==``){let e={_id:`NAVIGATION_STRATEGY-ELO`,docType:`NAVIGATION_STRATEGY`,name:`ELO`,description:`ELO-based navigation strategy for ordering content by difficulty`,implementingClass:`elo`,course:this.id,serializedData:``};return Promise.resolve(e)}else return this.db.get(e)}async getAllNavigationStrategies(){let e=DocTypePrefixes.NAVIGATION_STRATEGY;return(await this.db.allDocs({startkey:e,endkey:`${e}\uFFF0`,include_docs:!0})).rows.map(e=>e.doc)}async addNavigationStrategy(e){return logger.debug(`[courseDB] Adding navigation strategy: ${e._id}`),this.invalidateNavigatorCache(),this.remoteDB.put(e).then(()=>{})}updateNavigationStrategy(e,t){return logger.debug(`[courseDB] Updating navigation strategy: ${e}`),logger.debug(JSON.stringify(t)),Promise.resolve()}async createNavigator(e){try{let t=await this.getAllNavigationStrategies();if(t.length===0)return logger.debug(`[courseDB] No strategy documents found, using default Pipeline(Composite(ELO, SRS), [eloDistanceFilter])`),createDefaultPipeline(e,this);let{pipeline:n,generatorStrategies:r,filterStrategies:a,warnings:o}=await new PipelineAssembler().assemble({strategies:t,user:e,course:this});for(let e of o)logger.warn(`[PipelineAssembler] ${e}`);return n?(logger.debug(`[courseDB] Using assembled pipeline with ${r.length} generator(s) and ${a.length} filter(s)`),n):(logger.debug(`[courseDB] Pipeline assembly failed, using default pipeline`),createDefaultPipeline(e,this))}catch(e){let t=e instanceof Error?`${e.message}
270
271
  ${e.stack}`:JSON.stringify(e);throw logger.error(`[courseDB] Error creating navigator: ${t}`),e}}setEphemeralHints(e){this._pendingHints=e}notePresented(e){e.status===`new`&&this._getCurrentUser().then(e=>this._getCachedNavigator(e)).then(({navigator:t})=>t.notePresented?.(e)).catch(e=>logger.warn(`[courseDB] Could not note a presentation: ${e}`))}async getWeightedCards(e){let t=await this._getCurrentUser();try{let{navigator:n}=await this._getCachedNavigator(t);return this._pendingHints&&(n.setEphemeralHints(this._pendingHints),this._pendingHints=null),await n.getWeightedCards(e)}catch(e){throw logger.error(`[courseDB] Error getting weighted cards: ${e}`),e}}async _getCachedNavigator(e){let t=e.getUsername(),n=Date.now();if(this._cachedNavigator&&this._cachedNavigator.userId===t&&n-this._cachedNavigator.builtAt<this._navigatorTtlMs)return{navigator:this._cachedNavigator.navigator,cacheStatus:`hit`};let r=await this.createNavigator(e);return this._cachedNavigator={navigator:r,userId:t,builtAt:n},{navigator:r,cacheStatus:`miss`}}invalidateNavigatorCache(){this._cachedNavigator=null}async getCardsCenteredAtELO(e={limit:99,elo:`user`},t){let n;if(e.elo===`user`){let e=await this._getCurrentUser();n=-1;try{n=EloToNumber((await e.getCourseRegistrationsDoc()).courses.find(e=>e.courseID===this.id).elo)}catch{n=1e3}}else if(e.elo===`random`){let e=await GET_CACHED(`elo-bounds-${this.id}`,()=>this.getELOBounds());n=Math.round(e.low+Math.random()*(e.high-e.low))}else n=e.elo;let r=Math.max(2e3,e.limit*4),a=Date.now(),o=`hit`;if(!this._eloPoolCache||a-this._eloPoolCache.fetchedAt>this._eloPoolTtlMs){let e=await this.getCardsByELO(n,r);e.length>0&&(this._eloPoolCache={rows:e,fetchedAt:a}),o=`miss`}let rankAgainstCurrentElo=()=>{let e=this._eloPoolCache?.rows??[];return(t?e.filter(e=>t(e)):e).map(e=>({...e})).sort((e,t)=>Math.abs((e.elo??n)-n)-Math.abs((t.elo??n)-n))},s=rankAgainstCurrentElo();if(s.length<e.limit&&(o===`hit`||!this._eloPoolCache)){let e=await this.getCardsByELO(n,r);e.length>0&&(this._eloPoolCache={rows:e,fetchedAt:a}),s=rankAgainstCurrentElo(),o=`refresh`}let c=[];for(;c.length<e.limit&&s.length>0;){let e=randIntWeightedTowardZero(s.length),t=s.splice(e,1)[0];c.push(t)}return c.map(e=>({courseID:this.id,cardID:e.cardID,contentSourceType:`course`,contentSourceID:this.id,elo:e.elo,status:`new`}))}async searchCards(e){logger.log(`[CourseDB ${this.id}] Searching for: "${e}"`);let t;try{t=await this.db.find({selector:{docType:`DISPLAYABLE_DATA`,"data.0.data":{$regex:`.*${e}.*`}}}),logger.log(`[CourseDB ${this.id}] Regex search on data[0].data successful`)}catch(n){logger.log(`[CourseDB ${this.id}] Regex search failed, falling back to manual search:`,n);let r=await this.db.find({selector:{docType:`DISPLAYABLE_DATA`}});logger.log(`[CourseDB ${this.id}] Retrieved ${r.docs.length} documents for manual filtering`),t={docs:r.docs.filter(t=>{let n=JSON.stringify(t).toLowerCase().includes(e.toLowerCase());return n&&logger.log(`[CourseDB ${this.id}] Manual match found in document: ${t._id}`),n})}}if(logger.log(`[CourseDB ${this.id}] Found ${t.docs.length} displayable data documents`),t.docs.length===0){let e=await this.db.find({selector:{docType:`DISPLAYABLE_DATA`},limit:5});logger.log(`[CourseDB ${this.id}] Sample displayable data:`,e.docs.map(e=>({id:e._id,docType:e.docType,dataStructure:e.data?Object.keys(e.data):`no data field`,dataContent:e.data,fullDoc:e})))}let n=[];for(let e of t.docs){let t=await this.db.find({selector:{docType:`CARD`,id_displayable_data:{$in:[e._id]}}});logger.log(`[CourseDB ${this.id}] Displayable data ${e._id} linked to ${t.docs.length} cards`),n.push(...t.docs)}return logger.log(`[CourseDB ${this.id}] Total cards found: ${n.length}`),n}async find(e){return this.db.find(e)}}}}),classroomLookupDBTitle,CLASSROOM_CONFIG,ClassroomDBBase,StudentClassroomDB,TeacherClassroomDB,ClassroomLookupDB,init_classroomDB2=__esm({"src/impl/couch/classroomDB.ts"(){init_factory(),init_logger(),init_pouchdb_setup(),init_couch(),init_courseDB(),classroomLookupDBTitle=`classdb-lookup`,CLASSROOM_CONFIG=`ClassroomConfig`,ClassroomDBBase=class{constructor(){_defineProperty(this,`_id`,void 0),_defineProperty(this,`_db`,void 0),_defineProperty(this,`_cfg`,void 0),_defineProperty(this,`_initComplete`,!1),_defineProperty(this,`_content_prefix`,`content`)}get _content_searchkeys(){return getStartAndEndKeys(this._content_prefix)}async getAssignedContent(){return logger.info(`Getting assigned content...`),(await this._db.allDocs({startkey:this._content_prefix,endkey:this._content_prefix+`￰`,include_docs:!0})).rows.map(e=>e.doc)}getContentId(e){return e.type===`tag`?`${this._content_prefix}-${e.courseID}-${e.tagID}`:`${this._content_prefix}-${e.courseID}`}get ready(){return this._initComplete}getConfig(){return this._cfg}},StudentClassroomDB=class _StudentClassroomDB extends ClassroomDBBase{constructor(e,t){super(),_defineProperty(this,`userMessages`,void 0),_defineProperty(this,`_user`,void 0),this._id=e,this._user=t}async init(){let e=`classdb-student-${this._id}`;this._db=new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+e,createPouchDBConfig());try{this._cfg=await this._db.get(CLASSROOM_CONFIG),this.userMessages=this._db.changes({since:`now`,live:!0,include_docs:!0}),this._initComplete=!0;return}catch(e){throw Error(`Error in StudentClassroomDB constructor: ${JSON.stringify(e)}`)}}static async factory(e,t){let n=new _StudentClassroomDB(e,t);return await n.init(),n}setChangeFcn(e){this.userMessages.on(`change`,e)}async getWeightedCards(e){let t=[],n=(await this._user.getPendingReviews()).filter(e=>e.scheduledFor===`classroom`&&e.schedulingAgentId===this._id);for(let e of n)t.push({cardId:e.cardId,courseId:e.courseId,score:1,reviewID:e._id,provenance:[{strategy:`classroom`,strategyName:`Classroom`,strategyId:`CLASSROOM`,action:`generated`,score:1,reason:`Classroom scheduled review`}]});let r=await this._user.getActiveCards(),a=new Set(r.map(e=>e.cardID)),o=hooks.utc(),s=(await this.getAssignedContent()).filter(e=>o.isAfter(hooks.utc(e.activeOn,REVIEW_TIME_FORMAT)));logger.info(`[StudentClassroomDB] Due content: ${JSON.stringify(s)}`);for(let n of s)if(n.type===`course`){let{cards:r}=await new CourseDB(n.courseID,async()=>this._user).getWeightedCards(e);for(let e of r)a.has(e.cardId)||t.push({...e,provenance:[...e.provenance,{strategy:`classroom`,strategyName:`Classroom`,strategyId:`CLASSROOM`,action:`passed`,score:e.score,reason:`Assigned via classroom from course ${n.courseID}`}]})}else if(n.type===`tag`){let e=await getTag(n.courseID,n.tagID);for(let r of e.taggedCards)a.has(r)||t.push({cardId:r,courseId:n.courseID,score:1,provenance:[{strategy:`classroom`,strategyName:`Classroom`,strategyId:`CLASSROOM`,action:`generated`,score:1,reason:`Classroom assigned tag: ${n.tagID}, new card`}]})}else n.type===`card`&&(a.has(n.cardID)||t.push({cardId:n.cardID,courseId:n.courseID,score:1,provenance:[{strategy:`classroom`,strategyName:`Classroom`,strategyId:`CLASSROOM`,action:`generated`,score:1,reason:`Classroom assigned card, new card`}]}));return logger.info(`[StudentClassroomDB] New cards from classroom ${this._cfg.name}: ${t.length} total (reviews + new)`),{cards:t.sort((e,t)=>t.score-e.score).slice(0,e)}}},TeacherClassroomDB=class _TeacherClassroomDB extends ClassroomDBBase{constructor(e){super(),_defineProperty(this,`_stuDb`,void 0),this._id=e}async init(){let e=`classdb-teacher-${this._id}`,t=`classdb-student-${this._id}`;this._db=new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+e,createPouchDBConfig()),this._stuDb=new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+t,createPouchDBConfig());try{return this._db.get(CLASSROOM_CONFIG).then(e=>{this._cfg=e,this._initComplete=!0}).then(()=>{})}catch(e){throw Error(`Error in TeacherClassroomDB constructor: ${JSON.stringify(e)}`)}}static async factory(e){let t=new _TeacherClassroomDB(e);return await t.init(),t}async removeContent(e){let t=this.getContentId(e);try{let e=await this._db.get(t);await this._db.remove(e),this._db.replicate.to(this._stuDb,{doc_ids:[t]})}catch(e){logger.error(`Failed to remove content:`,t,e)}}async assignContent(e){let t,n=this.getContentId(e);return t=e.type===`tag`?await this._db.put({courseID:e.courseID,tagID:e.tagID,type:`tag`,_id:n,assignedBy:e.assignedBy,assignedOn:hooks.utc(),activeOn:e.activeOn||hooks.utc()}):await this._db.put({courseID:e.courseID,type:`course`,_id:n,assignedBy:e.assignedBy,assignedOn:hooks.utc(),activeOn:e.activeOn||hooks.utc()}),t.ok?(this._db.replicate.to(this._stuDb,{doc_ids:[n]}),!0):!1}},ClassroomLookupDB=()=>new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+classroomLookupDBTitle,{skip_setup:!0})}}),AdminDB,init_adminDB2=__esm({"src/impl/couch/adminDB.ts"(){init_pouchdb_setup(),init_factory(),init_couch(),init_classroomDB2(),init_courseLookupDB(),init_logger(),AdminDB=class{constructor(){_defineProperty(this,`usersDB`,void 0),this.usersDB=new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+`_users`,createPouchDBConfig())}async getUsers(){return(await this.usersDB.allDocs({include_docs:!0,...getStartAndEndKeys(`org.couchdb.user:`)})).rows.map(e=>e.doc)}async getCourses(){let e=await CourseLookup.allCourseWare();return await Promise.all(e.map(e=>getCredentialledCourseConfig(e._id)))}async removeCourse(e){let t=await CourseLookup.delete(e),n=await getCredentialledCourseConfig(e);n.deleted=!0;let r=await updateCredentialledCourseConfig(e,n);return{ok:t.ok&&r.ok,id:t.id,rev:t.rev}}async getClassrooms(){let e=(await ClassroomLookupDB().allDocs({include_docs:!0})).rows.map(e=>e.doc.uuid);logger.debug(e.join(`, `));let t=[];for(let n=0;n<e.length;n++)try{let r=await TeacherClassroomDB.factory(e[n]);t.push(r)}catch(t){let r=t;r.error&&r.error===`not_found`&&logger.warn(`db ${e[n]} not found`)}return t.map(e=>({...e.getConfig(),_id:e._id}))}}}}),CourseSyncService_exports={};__export(CourseSyncService_exports,{CourseSyncService:()=>CourseSyncService});var DEFAULT_REPLICATION,CourseSyncService,init_CourseSyncService=__esm({"src/impl/couch/CourseSyncService.ts"(){var e;init_pouchdb_setup(),init_couch(),init_logger(),DEFAULT_REPLICATION={batchSize:1e3,batchesLimit:5},CourseSyncService=(e=class _CourseSyncService{constructor(){_defineProperty(this,`entries`,new Map),_defineProperty(this,`replicationOptions`,DEFAULT_REPLICATION)}static getInstance(){return _CourseSyncService.instance||(_CourseSyncService.instance=new _CourseSyncService),_CourseSyncService.instance}configure(e){e.replication&&(this.replicationOptions={...DEFAULT_REPLICATION,...e.replication},logger.info(`[CourseSyncService] Replication configured: batch_size=${this.replicationOptions.batchSize}, batches_limit=${this.replicationOptions.batchesLimit}`))}static resetInstance(){if(_CourseSyncService.instance){for(let[,e]of _CourseSyncService.instance.entries)e.localDB&&e.localDB.close().catch(()=>{});_CourseSyncService.instance.entries.clear()}_CourseSyncService.instance=null}async ensureSynced(e,t){let n=this.entries.get(e);if(n?.status.state===`ready`&&n.localDB){if(!await this.isLocalEpochStale(e,n.localDB))return;logger.info(`[CourseSyncService] Remote DB epoch changed for course ${e} \u2014 destroying stale local replica`);try{await n.localDB.destroy()}catch{}n.localDB=null,n.readyPromise=null}if(n?.status.state===`disabled`)return;if(n?.readyPromise)return n.readyPromise;let r={localDB:null,status:{state:`not-started`},readyPromise:null};return this.entries.set(e,r),r.readyPromise=this.performSync(e,r,t),r.readyPromise}getLocalDB(e){let t=this.entries.get(e);return t?.status.state===`ready`&&t.localDB?t.localDB:null}isReady(e){return this.entries.get(e)?.status.state===`ready`}getStatus(e){return this.entries.get(e)?.status??{state:`not-started`}}async performSync(e,t,n){try{if(!n&&(t.status={state:`checking-config`},!await this.checkLocalSyncEnabled(e))){t.status={state:`disabled`},t.readyPromise=null,logger.debug(`[CourseSyncService] Local sync disabled for course ${e}`);return}t.status={state:`syncing`};let r=this.localDBName(e),a=new pouchdb_setup_default(r);await this.isLocalEpochStale(e,a)&&(logger.info(`[CourseSyncService] Stale local DB detected for course ${e} \u2014 destroying before sync`),await a.destroy(),a=new pouchdb_setup_default(r)),t.localDB=a;let o=this.getRemoteDB(e),s=Date.now();logger.info(`[CourseSyncService] Starting one-shot replication for course ${e} (batch_size=${this.replicationOptions.batchSize}, batches_limit=${this.replicationOptions.batchesLimit})`);let c=await this.replicate(o,a),l=Date.now()-s;logger.info(`[CourseSyncService] Replication complete for course ${e}: ${c.docs_written} docs in ${l}ms`),t.status={state:`warming-views`};let u=Date.now();await this.warmViewIndices(a);let d=Date.now()-u;logger.info(`[CourseSyncService] View indices warmed for course ${e} in ${d}ms`),t.status={state:`ready`,docsReplicated:c.docs_written,syncTimeMs:l,viewWarmTimeMs:d}}catch(n){let r=n instanceof Error?n.message:String(n);if(logger.error(`[CourseSyncService] Sync failed for course ${e}: ${r}`),t.status={state:`error`,error:r},t.readyPromise=null,t.localDB){try{await t.localDB.destroy()}catch{}t.localDB=null}}}async checkLocalSyncEnabled(e){try{return(await this.getRemoteDB(e).get(`CourseConfig`)).localSync?.enabled===!0}catch(t){return logger.warn(`[CourseSyncService] Could not read CourseConfig for ${e}, assuming local sync disabled: ${t}`),!1}}replicate(e,t){return new Promise((n,r)=>{pouchdb_setup_default.replicate(e,t,{batch_size:this.replicationOptions.batchSize,batches_limit:this.replicationOptions.batchesLimit}).on(`complete`,e=>{n(e)}).on(`error`,e=>{r(e)})})}async warmViewIndices(e){for(let t of[`elo`,`getTags`])try{await e.query(t,{limit:1}),logger.debug(`[CourseSyncService] Warmed view index: ${t}`)}catch(e){logger.debug(`[CourseSyncService] Could not warm view ${t}: ${e}`)}}async isLocalEpochStale(e,t){try{let n=await this.getRemoteDB(e).get(`db-epoch`),r=null;try{r=await t.get(`db-epoch`)}catch{return!0}return n.epoch!==r.epoch}catch{return!1}}getRemoteDB(e){return getCourseDB2(e)}localDBName(e){return`coursedb-local-${e}`}},_defineProperty(e,`instance`,null),e)}});async function getCurrentSession(){try{if(ENV.COUCHDB_SERVER_URL===NOT_SET||ENV.COUCHDB_SERVER_PROTOCOL===NOT_SET)throw Error(`CouchDB server configuration not properly initialized. Protocol: "${ENV.COUCHDB_SERVER_PROTOCOL}", URL: "${ENV.COUCHDB_SERVER_URL}"`);let e=ENV.COUCHDB_SERVER_URL.endsWith(`/`)?ENV.COUCHDB_SERVER_URL.slice(0,-1):ENV.COUCHDB_SERVER_URL,t=`${ENV.COUCHDB_SERVER_PROTOCOL}://${e}/_session`;logger.debug(`Attempting session check at: ${t}`);let n=await(0,import_browser_ponyfill.default)(t,{method:`GET`,credentials:`include`});if(!n.ok)throw Error(`Session check failed: ${n.status}`);return await n.json()}catch(e){let t=ENV.COUCHDB_SERVER_URL.endsWith(`/`)?ENV.COUCHDB_SERVER_URL.slice(0,-1):ENV.COUCHDB_SERVER_URL,n=`${ENV.COUCHDB_SERVER_PROTOCOL}://${t}/_session`;throw logger.error(`Session check error attempting to connect to: ${n} - ${e}`),Error(`Session check failed connecting to ${n}: ${e}`)}}async function getLoggedInUsername(){let e=await getCurrentSession();if(e.userCtx.name&&e.userCtx.name!==``)return e.userCtx.name;throw Error(`No logged in user`)}var init_auth=__esm({"src/impl/couch/auth.ts"(){init_factory(),init_logger()}}),CouchDBSyncStrategy_exports={};__export(CouchDBSyncStrategy_exports,{CouchDBSyncStrategy:()=>CouchDBSyncStrategy});var log2,CouchDBSyncStrategy,init_CouchDBSyncStrategy=__esm({"src/impl/couch/CouchDBSyncStrategy.ts"(){init_factory(),init_types_legacy(),init_logger(),init_common(),init_pouchdb_setup(),init_couch(),init_auth(),log2=e=>{logger.info(e)},CouchDBSyncStrategy=class{constructor(){_defineProperty(this,`syncHandle`,void 0),_defineProperty(this,`hydrationHandle`,void 0)}setupRemoteDB(e){return e===GuestUsername||e.startsWith(GuestUsername)?getLocalUserDB(e):this.getUserDB(e)}getWriteDB(e){return e===GuestUsername||e.startsWith(GuestUsername)?getLocalUserDB(e):this.getUserDB(e)}async hydrate(e,t){let n=(await e.info()).doc_count===0,r=pouchdb_setup_default.replicate(t,e,n?{selector:{_deleted:{$exists:!1}}}:{});this.hydrationHandle=r;try{let e=await r;return{docsWritten:e.docs_written,lastSeq:n?e.last_seq:void 0}}finally{this.hydrationHandle=void 0}}startSync(e,t,n){e.name!==t.name&&(this.syncHandle=pouchdb_setup_default.sync(e,t,{live:!0,retry:!0,...n===void 0?{}:{pull:{since:n}}}))}stopSync(){if(this.hydrationHandle){try{this.hydrationHandle.cancel()}catch(e){logger.warn(`Failed to cancel hydration pull (continuing anyway): ${e}`)}this.hydrationHandle=void 0}if(this.syncHandle){try{this.syncHandle.cancel()}catch(e){logger.warn(`Failed to cancel user sync (continuing anyway): ${e}`)}this.syncHandle=void 0}}canCreateAccount(){return!0}canAuthenticate(){return!0}async createAccount(e,t){let n=await this.getCurrentUsername(),r=n.startsWith(GuestUsername);r&&logger.info(`Creating account for funnel user ${n} -> ${e}`);try{let a=await this.getRemoteCouchRootDB().signUp(e,t);if(a.ok){log2(`CREATEACCOUNT: Successfully created account for ${e}`);try{let e=await this.getRemoteCouchRootDB().logOut();log2(`CREATEACCOUNT: logged out: ${e.ok}`)}catch{}let a=await this.getRemoteCouchRootDB().logIn(e,t);if(log2(`CREATEACCOUNT: logged in as new user: ${a.ok}`),a.ok){if(r){logger.info(`Migrating data from funnel account ${n} to ${e}`);let t=await this.migrateFunnelData(n,e);t.success||logger.warn(`Migration failed: ${t.error}`)}return{status:Status.ok,error:void 0}}else return{status:Status.error,error:`Failed to log in after account creation`}}else return logger.warn(`Signup not OK: ${JSON.stringify(a)}`),{status:Status.error,error:`Account creation failed`}}catch(e){return e.reason===`Document update conflict.`?{status:Status.error,error:`This username is taken!`}:(logger.error(`Error on signup: ${JSON.stringify(e)}`),{status:Status.error,error:e.message||`Unknown error during account creation`})}}async authenticate(e,t){try{return(await this.getRemoteCouchRootDB().logIn(e,t)).ok?(log2(`Successfully logged in as ${e}`),{ok:!0}):(log2(`Login failed for ${e}`),{ok:!1,error:`Invalid username or password`})}catch(t){return logger.error(`Authentication error for ${e}:`,t),{ok:!1,error:t.message||`Authentication failed`}}}async adoptSession(e){let t;try{t=await getLoggedInUsername()}catch{return{ok:!1,error:`No session to adopt`}}if(e?.startsWith(GuestUsername)){logger.info(`Migrating data from funnel account ${e} to ${t}`);let n=await this.migrateFunnelData(e,t);n.success||logger.warn(`Migration failed: ${n.error}`)}return{ok:!0,username:t}}async logout(){try{let e=await this.getRemoteCouchRootDB().logOut();return{ok:e.ok,error:e.ok?void 0:`Logout failed`}}catch(e){return logger.error(`Logout error:`,e),{ok:!1,error:e.message||`Logout failed`}}}async getCurrentUsername(){logger.log(`[funnel] CouchDBSyncStrategy.getCurrentUsername() called`);try{let e=await getLoggedInUsername();return logger.log(`[funnel] getLoggedInUsername() returned:`,e),e}catch(e){logger.log(`[funnel] getLoggedInUsername() failed, calling accomodateGuest()`),logger.log(`[funnel] Error was:`,e);let t=accomodateGuest();return logger.log(`[funnel] accomodateGuest() returned:`,t),t.username}}async migrateFunnelData(e,t){try{logger.info(`Starting data migration from ${e} to ${t}`);let n=getLocalUserDB(e),r=getLocalUserDB(t),a=await n.allDocs({include_docs:!0});logger.info(`Found ${a.rows.length} documents in funnel account`);let o=a.rows.filter(e=>!e.id.startsWith(`_design/`)).map(e=>({...e.doc,_rev:void 0}));o.length>0?(await r.bulkDocs(o),logger.info(`Successfully migrated ${o.length} documents from ${e} to ${t}`)):logger.info(`No documents to migrate from funnel account`);try{await n.destroy(),logger.info(`Destroyed consumed guest DB for ${e}`)}catch(t){logger.warn(`Failed to destroy consumed guest DB for ${e} (non-fatal): ${t instanceof Error?t.message:String(t)}`)}return{success:!0}}catch(e){return logger.error(`Migration failed:`,e),{success:!1,error:e instanceof Error?e.message:`Unknown error`}}}getRemoteCouchRootDB(){let e=ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+`skuilder`;try{return new pouchdb_setup_default(e,{skip_setup:!0})}catch(e){throw logger.error(`Failed to initialize remote CouchDB connection:`,e),Error(`Failed to initialize CouchDB: ${JSON.stringify(e)}`)}}getUserDB(e){let t=!1,n=`userdb-${hexEncode(e)}`;return log2(`Fetching user database: ${n} (${e})`),new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+n,createPouchDBConfig())}}}});function createPouchDBConfig(){return ENV.COUCHDB_USERNAME&&ENV.COUCHDB_PASSWORD&&typeof window>`u`?{fetch(e,t={}){let n=btoa(`${ENV.COUCHDB_USERNAME}:${ENV.COUCHDB_PASSWORD}`),r=new Headers(t.headers||{});r.set(`Authorization`,`Basic ${n}`);let a={...t,headers:r};return pouchdb_setup_default.fetch(e,a)}}:pouchDBincludeCredentialsConfig}function getCourseDB2(e){return new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+`coursedb-`+e,createPouchDBConfig())}function filterAllDocsByPrefix(e,t,n){let r={startkey:t,endkey:t+`￰`,include_docs:!0};return n&&Object.assign(r,n),e.allDocs(r)}function getStartAndEndKeys(e){return{startkey:e,endkey:e+`￰`}}var isBrowser,GUEST_LOCAL_DB,localUserDB,pouchDBincludeCredentialsConfig,REVIEW_TIME_FORMAT,init_couch=__esm({"src/impl/couch/index.ts"(){init_factory(),init_types_legacy(),init_logger(),init_pouchdb_setup(),init_contentSource(),init_adminDB2(),init_classroomDB2(),init_courseAPI(),init_courseDB(),init_CourseSyncService(),init_CouchDBSyncStrategy(),isBrowser=typeof window<`u`,isBrowser&&(window.process=import_browser.default),GUEST_LOCAL_DB=`userdb-${GuestUsername}`,new pouchdb_setup_default(GUEST_LOCAL_DB),pouchDBincludeCredentialsConfig={fetch(e,t){return t.credentials=`include`,pouchdb_setup_default.fetch(e,t)}},REVIEW_TIME_FORMAT=`YYYY-MM-DD--kk:mm:ss-SSS`}});function newInterval(e,t){return areQuestionRecords(t)?newQuestionInterval(e,t):1e5}function newQuestionInterval(e,t){let n=t.records,r=n[n.length-1],a=lastSuccessfulInterval(n);if(a>t.bestInterval&&(t.bestInterval=a,e.update(t._id,{bestInterval:a}).catch(e=>{logger.warn(`[SpacedRepetition] Failed to update bestInterval for ${t._id}: ${e?.message??e}`)})),r.isCorrect){let e=r.performance,n=isTaggedPerformance(e)?e._global:e,o=Math.min(1,Math.max(0,n));logger.debug(`Demontrated skill: ${o}`);let s=a*(.75+o);if(t.lapses=getLapses(t.records),t.streak=getStreak(t.records),t.lapses&&t.streak&&t.bestInterval&&(t.lapses>=0||t.streak>=0)){let e=(t.lapses*s+t.streak*t.bestInterval)/(t.lapses+t.streak);return logger.debug(`Weighted average interval calculation:
271
- (${t.lapses} * ${s} + ${t.streak} * ${t.bestInterval}) / (${t.lapses} + ${t.streak}) = ${e}`),e}else return s}else return 0}function lastSuccessfulInterval(e){for(let t=e.length-1;t>=1;t--)if(e[t].priorAttemps===0&&e[t].isCorrect){let n=secondsBetween(e[t-1].timeStamp,e[t].timeStamp),r=Math.max(n,1200*60);return logger.debug(`Last interval w/ this card was: ${n}s, returning ${r}s`),r}return getInitialInterval(e)}function getStreak(e){let t=0,n=e.length-1;for(;n>=0&&e[n].isCorrect;)n--,t++;return t}function getLapses(e){return e.filter(e=>e.isCorrect===!1).length}function getInitialInterval(e){return logger.warn(`history of length: ${e.length} ignored!`),3600*24*3}function secondsBetween(e,t){return e=hooks(e),t=hooks(t),duration(t.diff(e)).asSeconds()}var duration,init_SpacedRepetition=__esm({"src/study/SpacedRepetition.ts"(){init_util(),init_logger(),duration=hooks.duration}}),SrsService,init_SrsService=__esm({"src/study/services/SrsService.ts"(){init_couch(),init_SpacedRepetition(),init_logger(),SrsService=class{constructor(e){_defineProperty(this,`user`,void 0),this.user=e}removeReview(e){logger.info(`[SrsService] Removing orphaned scheduled review: ${e}`),this.user.removeScheduledCardReview(e)}async scheduleReview(e,t){let n=newInterval(this.user,e),r=hooks.utc().add(n,`seconds`);isReview(t)&&(logger.info(`[SrsService] Removing previously scheduled review for: ${t.cardID}`),this.user.removeScheduledCardReview(t.reviewID)),this.user.scheduleCardReview({user:this.user.getUsername(),course_id:e.courseID,card_id:e.cardID,time:r,scheduledFor:t.contentSourceType,schedulingAgentId:t.contentSourceID})}}}});function currentRecord(e){return e.length?e[e.length-1]:null}function isFirstAttempt(e){let t=currentRecord(e);if(!t)return!1;let n=t.priorAttemps;return typeof n==`number`?n===0:e.length===1}function recordTagPresentations(e,t,n,r,a){if(!isFirstAttempt(n))return[];let o=currentRecord(n)?.isCorrect===!0,s=[];for(let[n,c]of Object.entries(t)){if(n===`_global`||typeof c!=`number`)continue;let t=e.tags[n]??{score:e.global.score,count:0},l={at:a,ok:o,perf:c,card:r};e.tags[n]=pushTagPresentation(t,l),s.push(n)}return s}var init_tagRecent=__esm({"src/study/services/tagRecent.ts"(){}});function withCountOnlyRoles(e,t){let n={...e},r=[];for(let[t,a]of Object.entries(e))t===`_global`||a===null||!isCountOnlyTag(t)||(n[t]=null,r.push(t));return r.length&&logger.warn(`[EloService] ${t} sent scores for bookkeeping tags [${r.join(`, `)}]; counted, not graded`),n}var EloService,init_EloService=__esm({"src/study/services/EloService.ts"(){init_logger(),init_tagRecent(),EloService=class{constructor(e,t){_defineProperty(this,`dataLayer`,void 0),_defineProperty(this,`user`,void 0),this.dataLayer=e,this.user=t}async updateUserAndCardElo(e,t,n,r,a,o){o&&logger.warn(`k value interpretation not currently implemented`);let s=this.dataLayer.getCourseDB(a.card.course_id),c=r.courses.find(e=>e.courseID===t);if(!c)return logger.error(`[EloService] No registration for course ${t} on user's registration doc \u2014 skipping ELO update for card ${n}. (Is the user registered for this course?)`),null;let l=toCourseElo(c.elo),u=(await s.getCardEloData([a.card.card_id]))[0];if(u&&l){let r=l.global.score,a=u.global.score,o=Object.keys(u.tags),d={};for(let e of o)d[e]=l.tags[e]?.score??l.global.score;let p=adjustCourseScores(l,u,e);c.elo=p.userElo;let m={};for(let t of o){let n=isCountOnlyTag(t);m[t]={before:d[t],after:n?d[t]:p.userElo.tags[t].score,score:n?null:e}}let g={cardId:n,at:new Date().toISOString(),userScore:e,global:{before:r,after:p.userElo.global.score},card:{before:a,after:p.cardElo.global.score},...o.length?{tags:m}:{}},_=await Promise.allSettled([this.user.updateUserElo(t,p.userElo),s.updateCardElo(n,p.cardElo)]),v=_[0].status===`fulfilled`,y=_[1].status===`fulfilled`;if(v&&y){let e=_[0].value,t=_[1].value;e.ok&&t&&t.ok&&logger.info(`[EloService] Updated ELOS:
272
- User: ${JSON.stringify(p.userElo)})
273
- Card: ${JSON.stringify(p.cardElo)})
272
+ (${t.lapses} * ${s} + ${t.streak} * ${t.bestInterval}) / (${t.lapses} + ${t.streak}) = ${e}`),e}else return s}else return 0}function lastSuccessfulInterval(e){for(let t=e.length-1;t>=1;t--)if(e[t].priorAttemps===0&&e[t].isCorrect){let n=secondsBetween(e[t-1].timeStamp,e[t].timeStamp),r=Math.max(n,1200*60);return logger.debug(`Last interval w/ this card was: ${n}s, returning ${r}s`),r}return getInitialInterval(e)}function getStreak(e){let t=0,n=e.length-1;for(;n>=0&&e[n].isCorrect;)n--,t++;return t}function getLapses(e){return e.filter(e=>e.isCorrect===!1).length}function getInitialInterval(e){return logger.warn(`history of length: ${e.length} ignored!`),3600*24*3}function secondsBetween(e,t){return e=hooks(e),t=hooks(t),duration(t.diff(e)).asSeconds()}var duration,init_SpacedRepetition=__esm({"src/study/SpacedRepetition.ts"(){init_util(),init_logger(),duration=hooks.duration}}),SrsService,init_SrsService=__esm({"src/study/services/SrsService.ts"(){init_couch(),init_SpacedRepetition(),init_logger(),SrsService=class{constructor(e){_defineProperty(this,`user`,void 0),this.user=e}removeReview(e){logger.info(`[SrsService] Removing orphaned scheduled review: ${e}`),this.user.removeScheduledCardReview(e)}async scheduleReview(e,t){let n=newInterval(this.user,e),r=hooks.utc().add(n,`seconds`);isReview(t)&&(logger.info(`[SrsService] Removing previously scheduled review for: ${t.cardID}`),this.user.removeScheduledCardReview(t.reviewID)),this.user.scheduleCardReview({user:this.user.getUsername(),course_id:e.courseID,card_id:e.cardID,time:r,scheduledFor:t.contentSourceType,schedulingAgentId:t.contentSourceID})}}}});function currentRecord(e){return e.length?e[e.length-1]:null}function isFirstAttempt(e){let t=currentRecord(e);if(!t)return!1;let n=t.priorAttemps;return typeof n==`number`?n===0:e.length===1}function recordTagPresentations(e,t,n,r,a){if(!isFirstAttempt(n))return[];let o=currentRecord(n)?.isCorrect===!0,s=[];for(let[n,c]of Object.entries(t)){if(n===`_global`||typeof c!=`number`)continue;let t=e.tags[n]??{score:e.global.score,count:0},l={at:a,ok:o,perf:c,card:r};e.tags[n]=pushTagPresentation(t,l),s.push(n)}return s}var init_tagRecent=__esm({"src/study/services/tagRecent.ts"(){}});function withCountOnlyRoles(e,t){let n={...e},r=[];for(let[t,a]of Object.entries(e))t===`_global`||a===null||!isCountOnlyTag(t)||(n[t]=null,r.push(t));return r.length&&logger.warn(`[EloService] ${t} sent scores for bookkeeping tags [${r.join(`, `)}]; counted, not graded`),n}var EloService,init_EloService=__esm({"src/study/services/EloService.ts"(){init_logger(),init_tagRecent(),EloService=class{constructor(e,t){_defineProperty(this,`dataLayer`,void 0),_defineProperty(this,`user`,void 0),_defineProperty(this,`qaPatterns`,new Map),this.dataLayer=e,this.user=t}async isQaUser(e){let t=e.getCourseID(),n=this.qaPatterns.get(t);return n||(n=e.getCourseConfig().then(e=>e.qaUsernamePattern?new RegExp(e.qaUsernamePattern,`i`):null).catch(e=>(logger.warn(`[EloService] No QA username pattern for ${t}: ${e}`),null)),this.qaPatterns.set(t,n)),(await n)?.test(this.user.getUsername())??!1}async updateUserAndCardElo(e,t,n,r,a,o){o&&logger.warn(`k value interpretation not currently implemented`);let s=this.dataLayer.getCourseDB(a.card.course_id),c=r.courses.find(e=>e.courseID===t);if(!c)return logger.error(`[EloService] No registration for course ${t} on user's registration doc \u2014 skipping ELO update for card ${n}. (Is the user registered for this course?)`),null;let l=toCourseElo(c.elo),u=(await s.getCardEloData([a.card.card_id]))[0];if(u&&l){let r=!await this.isQaUser(s),a=l.global.score,o=u.global.score,d=Object.keys(u.tags),p={};for(let e of d)p[e]=l.tags[e]?.score??l.global.score;let m=adjustCourseScores(l,u,e);c.elo=m.userElo;let g={};for(let t of d){let n=isCountOnlyTag(t);g[t]={before:p[t],after:n?p[t]:m.userElo.tags[t].score,score:n?null:e}}let _={cardId:n,at:new Date().toISOString(),userScore:e,global:{before:a,after:m.userElo.global.score},card:{before:o,after:r?m.cardElo.global.score:o},...d.length?{tags:g}:{}};r||logger.info(`[EloService] QA account: card ELO for ${n} not written`);let v=await Promise.allSettled([this.user.updateUserElo(t,m.userElo),r?s.updateCardElo(n,m.cardElo):Promise.resolve(null)]),y=v[0].status===`fulfilled`,b=v[1].status===`fulfilled`;if(y&&b){let e=v[0].value,t=v[1].value;e.ok&&t&&t.ok&&logger.info(`[EloService] Updated ELOS:
273
+ User: ${JSON.stringify(m.userElo)})
274
+ Card: ${JSON.stringify(m.cardElo)})
274
275
  `)}else logger.warn(`[EloService] Partial ELO update:
275
- User ELO update: ${v?`SUCCESS`:`FAILED`}
276
- Card ELO update: ${y?`SUCCESS`:`FAILED`}`),!v&&_[0].status===`rejected`&&logger.error(`[EloService] User ELO update error:`,_[0].reason),!y&&_[1].status===`rejected`&&logger.error(`[EloService] Card ELO update error:`,_[1].reason);return g}return null}async updateUserAndCardEloPerTag(e,t,n,r,a){let o=this.dataLayer.getCourseDB(a.card.course_id),s=r.courses.find(e=>e.courseID===t);if(!s)return logger.error(`[EloService] No registration for course ${t} on user's registration doc \u2014 skipping per-tag ELO update for card ${n}. (Is the user registered for this course?)`),null;let c=toCourseElo(s.elo),[l,u]=await Promise.all([o.getCardEloData([a.card.card_id]),o.getAppliedTagsBatch([n])]),d=l[0],p=u.get(n)??[],m=withCountOnlyRoles(e,n),g={...m},_=e._global;for(let e of p)e in g||(g[e]=isCountOnlyTag(e)?null:_);if(d&&c){let e=c.global.score,r=d.global.score,l=Object.keys(g).filter(e=>e!==`_global`),u={};for(let e of l)u[e]=c.tags[e]?.score??c.global.score;let p=adjustCourseScoresPerTag(c,d,g),v=new Date().toISOString(),y=recordTagPresentations(p.userElo,m,a.records,n,v);y.length&&logger.info(`[EloService] recent-presentation entries for ${n}: [${y.join(`, `)}]`),s.elo=p.userElo;let b={};for(let e of l){let t=g[e],n=t===null?u[e]:p.userElo.tags[e]?.score??u[e];b[e]={before:u[e],after:n,score:t}}let x={cardId:n,at:v,userScore:_,global:{before:e,after:p.userElo.global.score},card:{before:r,after:p.cardElo.global.score},...l.length?{tags:b}:{}},S=await Promise.allSettled([this.user.updateUserElo(t,p.userElo),o.updateCardElo(n,p.cardElo)]),C=S[0].status===`fulfilled`,w=S[1].status===`fulfilled`;if(C&&w){let e=S[0].value,t=S[1].value;if(e.ok&&t&&t.ok){let e=Object.keys(g).length-1;logger.info(`[EloService] Updated ELOS (per-tag, ${e} tags):
277
- User: ${JSON.stringify(p.userElo)})
278
- Card: ${JSON.stringify(p.cardElo)})
276
+ User ELO update: ${y?`SUCCESS`:`FAILED`}
277
+ Card ELO update: ${b?`SUCCESS`:`FAILED`}`),!y&&v[0].status===`rejected`&&logger.error(`[EloService] User ELO update error:`,v[0].reason),!b&&v[1].status===`rejected`&&logger.error(`[EloService] Card ELO update error:`,v[1].reason);return _}return null}async updateUserAndCardEloPerTag(e,t,n,r,a){let o=this.dataLayer.getCourseDB(a.card.course_id),s=r.courses.find(e=>e.courseID===t);if(!s)return logger.error(`[EloService] No registration for course ${t} on user's registration doc \u2014 skipping per-tag ELO update for card ${n}. (Is the user registered for this course?)`),null;let c=toCourseElo(s.elo),[l,u]=await Promise.all([o.getCardEloData([a.card.card_id]),o.getAppliedTagsBatch([n])]),d=l[0],p=u.get(n)??[],m=withCountOnlyRoles(e,n),g={...m},_=e._global;for(let e of p)e in g||(g[e]=isCountOnlyTag(e)?null:_);if(d&&c){let e=!await this.isQaUser(o),r=c.global.score,l=d.global.score,u=Object.keys(g).filter(e=>e!==`_global`),p={};for(let e of u)p[e]=c.tags[e]?.score??c.global.score;let v=adjustCourseScoresPerTag(c,d,g),y=new Date().toISOString(),b=recordTagPresentations(v.userElo,m,a.records,n,y);b.length&&logger.info(`[EloService] recent-presentation entries for ${n}: [${b.join(`, `)}]`),s.elo=v.userElo;let x={};for(let e of u){let t=g[e],n=t===null?p[e]:v.userElo.tags[e]?.score??p[e];x[e]={before:p[e],after:n,score:t}}let S={cardId:n,at:y,userScore:_,global:{before:r,after:v.userElo.global.score},card:{before:l,after:e?v.cardElo.global.score:l},...u.length?{tags:x}:{}};e||logger.info(`[EloService] QA account: card ELO for ${n} not written`);let C=await Promise.allSettled([this.user.updateUserElo(t,v.userElo),e?o.updateCardElo(n,v.cardElo):Promise.resolve(null)]),w=C[0].status===`fulfilled`,T=C[1].status===`fulfilled`;if(w&&T){let e=C[0].value,t=C[1].value;if(e.ok&&t&&t.ok){let e=Object.keys(g).length-1;logger.info(`[EloService] Updated ELOS (per-tag, ${e} tags):
278
+ User: ${JSON.stringify(v.userElo)})
279
+ Card: ${JSON.stringify(v.cardElo)})
279
280
  `)}}else logger.warn(`[EloService] Partial ELO update (per-tag):
280
- User ELO update: ${C?`SUCCESS`:`FAILED`}
281
- Card ELO update: ${w?`SUCCESS`:`FAILED`}`),!C&&S[0].status===`rejected`&&logger.error(`[EloService] User ELO update error:`,S[0].reason),!w&&S[1].status===`rejected`&&logger.error(`[EloService] Card ELO update error:`,S[1].reason);return x}return null}}}}),ResponseProcessor,init_ResponseProcessor=__esm({"src/study/services/ResponseProcessor.ts"(){init_core(),init_logger(),ResponseProcessor=class{constructor(e,t,n){_defineProperty(this,`srsService`,void 0),_defineProperty(this,`eloService`,void 0),_defineProperty(this,`onEloEvent`,void 0),this.srsService=e,this.eloService=t,this.onEloEvent=n}logEloFailure(e,t){return n=>logger.error(`[ResponseProcessor] ELO update failed (${e}) for ${t}:`,n)}trackElo(e,t,n){e.then(e=>{e&&this.onEloEvent?.(e)}).catch(this.logEloFailure(t,n))}parsePerformance(e){return typeof e==`number`?{globalScore:e,taggedPerformance:null}:isTaggedPerformance(e)?{globalScore:e._global,taggedPerformance:e}:(logger.warn(`[ResponseProcessor] Unexpected performance structure, using neutral score`,{performance:e}),{globalScore:.5,taggedPerformance:null})}async processResponse(e,t,n,r,a,o,s,c,l,u){if(!isQuestionRecord(e))return{nextCardAction:`dismiss-success`,shouldLoadNextCard:!0,isCorrect:!0,shouldClearFeedbackShadow:!0};try{let d=await t,p;return p=e.isCorrect?this.processCorrectResponse(e,d,n,r,a,o,s,l,u):this.processIncorrectResponse(e,d,r,a,o,s,c,l,u),e.deferAdvance&&p.shouldLoadNextCard&&(logger.info(`[ResponseProcessor] deferAdvance requested — suppressing navigation, action stashed:`,{nextCardAction:p.nextCardAction}),p={...p,shouldLoadNextCard:!1,deferred:!0}),p}catch(e){throw logger.error(`[ResponseProcessor] Failed to load card history`,{e,cardId:s}),e}}processCorrectResponse(e,t,n,r,a,o,s,c,l){if(e.priorAttemps===0){a.card.tags.includes(`srs:skip`)||this.srsService.scheduleReview(t,n);let{globalScore:c,taggedPerformance:l}=this.parsePerformance(e.performance);if(l){let n=Object.keys(l).filter(e=>e!==`_global`),c=n.filter(e=>l[e]===null),u=n.filter(e=>l[e]!==null);logger.info(`[FirstContactElo] correct first-attempt per-tag ELO update for ${s} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps}): scored=[${u.join(`, `)}] count-only=[${c.join(`, `)}]`),this.trackElo(this.eloService.updateUserAndCardEloPerTag(l,o,s,r,a),`correct per-tag`,s)}else{let n=.5+c/2;if(t.records.length===1)this.trackElo(this.eloService.updateUserAndCardElo(n,o,s,r,a),`correct`,s);else{let e=Math.ceil(32/t.records.length);this.trackElo(this.eloService.updateUserAndCardElo(n,o,s,r,a,e),`correct repeat-view`,s)}logger.info(`[FirstContactElo] correct first-attempt ELO update (score=${n.toFixed(3)}) for ${s} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps})`)}return{nextCardAction:`dismiss-success`,shouldLoadNextCard:!0,isCorrect:!0,performanceScore:c,shouldClearFeedbackShadow:!0}}else{let t=l>=c;logger.info(`[ResponseProcessor] Processed correct response (retry attempt - no scheduling/ELO); sessionViews=${l}/${c} -> ${t?`dismiss-success`:`marked-failed`}`);let{globalScore:n}=this.parsePerformance(e.performance);return{nextCardAction:t?`dismiss-success`:`marked-failed`,shouldLoadNextCard:!0,isCorrect:!0,performanceScore:n,shouldClearFeedbackShadow:!0}}}processIncorrectResponse(e,t,n,r,a,o,s,c,l){let{taggedPerformance:u}=this.parsePerformance(e.performance),d=!1;return e.priorAttemps===0?(u?(this.trackElo(this.eloService.updateUserAndCardEloPerTag(u,a,o,n,r),`incorrect per-tag`,o),logger.info(`[FirstContactElo] incorrect first-attempt per-tag ELO update for ${o} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps}, tags=${Object.keys(u).length-1})`)):(this.trackElo(this.eloService.updateUserAndCardElo(0,a,o,n,r),`incorrect`,o),logger.info(`[FirstContactElo] incorrect first-attempt ELO update (score=0) for ${o} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps})`)),d=!0):logger.info(`[FirstContactElo] incorrect retry \u2014 no ELO update for ${o} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps})`),r.records.length>=s?l>=c?(d?logger.info(`[FirstContactElo] dismiss-failed \u2014 ELO already updated this response, skipping double penalty for ${o}`):(u?this.trackElo(this.eloService.updateUserAndCardEloPerTag(u,a,o,n,r),`dismiss-failed per-tag`,o):this.trackElo(this.eloService.updateUserAndCardElo(0,a,o,n,r),`dismiss-failed`,o),logger.info(`[FirstContactElo] dismiss-failed final ELO penalty for ${o} (historyLen=${t.records.length}, sessionViews=${l})`)),{nextCardAction:`dismiss-failed`,shouldLoadNextCard:!0,isCorrect:!1,shouldClearFeedbackShadow:!0}):{nextCardAction:`marked-failed`,shouldLoadNextCard:!0,isCorrect:!1,shouldClearFeedbackShadow:!0}:{nextCardAction:`none`,shouldLoadNextCard:!1,isCorrect:!1,shouldClearFeedbackShadow:!0}}}}});function parseAudioURIs(e){return typeof e==`string`?e.match(/https?:\/\/[^\s"'<>]+\.(wav|mp3|ogg|m4a|aac|webm)/gi)??[]:[]}function prefetchAudio(e){return new Promise(t=>{let n=new Audio;n.preload=`auto`;let cleanup=()=>{n.oncanplaythrough=null,n.onerror=null};n.oncanplaythrough=()=>{cleanup(),t()},n.onerror=()=>{cleanup(),logger.warn(`[CardHydrationService] Failed to prefetch audio: ${e}`),t()},n.src=e})}var CardHydrationService,init_CardHydrationService=__esm({"src/study/services/CardHydrationService.ts"(){init_logger(),CardHydrationService=class{constructor(e,t,n){_defineProperty(this,`hydratedCards`,new Map),_defineProperty(this,`hydrationInFlight`,new Set),_defineProperty(this,`hydrationInProgress`,!1),this.getViewComponent=e,this.getCourseDB=t,this.getItemsToHydrate=n}getHydratedCard(e){return this.hydratedCards.get(e)??null}hasHydratedCard(e){return this.hydratedCards.has(e)}removeCard(e){this.hydratedCards.delete(e)}async ensureHydratedCards(){this.fillHydratedCards()}async waitForCard(e){if(this.hydratedCards.has(e))return this.hydratedCards.get(e);this.hydrationInProgress||this.fillHydratedCards();let t=1e4,n=25,r=0;for(;r<1e4;){if(this.hydratedCards.has(e))return this.hydratedCards.get(e);if(!this.hydrationInFlight.has(e)&&!this.hydrationInProgress)break;await new Promise(e=>setTimeout(e,25)),r+=25}return this.hydratedCards.get(e)??null}get hydratedCount(){return this.hydratedCards.size}getHydratedCardIds(){return Array.from(this.hydratedCards.keys())}async fillHydratedCards(){if(!this.hydrationInProgress){this.hydrationInProgress=!0;try{let e=this.getItemsToHydrate();for(let t of e)if(!(this.hydratedCards.has(t.cardID)||this.hydrationInFlight.has(t.cardID)))try{await this.hydrateCard(t)}catch(e){logger.error(`[CardHydrationService] Error hydrating card ${t.cardID}:`,e)}}finally{this.hydrationInProgress=!1}}}async hydrateCard(e){if(!(this.hydratedCards.has(e.cardID)||this.hydrationInFlight.has(e.cardID))){this.hydrationInFlight.add(e.cardID);try{let t=this.getCourseDB(e.courseID),[n,r]=await Promise.all([t.getCourseDoc(e.cardID),t.getAppliedTagsBatch([e.cardID])]);isCourseElo(n.elo)||(n.elo=toCourseElo(n.elo));let a=this.getViewComponent(n.id_view),o=await Promise.all(n.id_displayable_data.map(e=>t.getCourseDoc(e,{attachments:!0,binary:!0}))),s=[];o.forEach(e=>{e.data.forEach(e=>{s.push(...parseAudioURIs(e.data))})});let c=[...new Set(s)];c.length>0&&(logger.debug(`[CardHydrationService] Prefetching ${c.length} audio files for card ${e.cardID}`),await Promise.allSettled(c.map(prefetchAudio)));let l=o.map(displayableDataToViewData).reverse();this.hydratedCards.set(e.cardID,{item:{...e,elo:toCourseElo(n.elo).global.score},view:a,data:l,tags:r.get(e.cardID)??[]}),logger.debug(`[CardHydrationService] Hydrated card ${e.cardID}`)}finally{this.hydrationInFlight.delete(e.cardID)}}}}}}),ItemQueue,init_ItemQueue=__esm({"src/study/ItemQueue.ts"(){ItemQueue=class{constructor(){_defineProperty(this,`q`,[]),_defineProperty(this,`seenCardIds`,[]),_defineProperty(this,`_dequeueCount`,0)}get dequeueCount(){return this._dequeueCount}add(e,t){this.seenCardIds.find(e=>e===t)||(this.seenCardIds.push(t),this.q.push(e))}addAll(e,t){e.forEach(e=>this.add(e,t(e)))}get length(){return this.q.length}peek(e){return this.q[e]}dequeue(e){if(this.q.length!==0){this._dequeueCount++;let t=this.q.splice(0,1)[0];if(e){let n=e(t),r=this.seenCardIds.indexOf(n);r>-1&&this.seenCardIds.splice(r,1)}return t}else return null}replaceAll(e,t){this.q=[],this.seenCardIds=[];for(let n of e){let e=t(n);this.seenCardIds.includes(e)||(this.seenCardIds.push(e),this.q.push(n))}}mergeToFront(e,t,n){let r=0,a=[];for(let o of e){let e=t(o);if(!this.seenCardIds.includes(e))this.seenCardIds.push(e),a.push(o),r++;else if(n?.has(e)){let n=this.q.findIndex(n=>t(n)===e);n>=0&&a.push(...this.q.splice(n,1))}}return this.q.unshift(...a),r}get toString(){return`${typeof this.q[0]}:
281
+ User ELO update: ${w?`SUCCESS`:`FAILED`}
282
+ Card ELO update: ${T?`SUCCESS`:`FAILED`}`),!w&&C[0].status===`rejected`&&logger.error(`[EloService] User ELO update error:`,C[0].reason),!T&&C[1].status===`rejected`&&logger.error(`[EloService] Card ELO update error:`,C[1].reason);return S}return null}}}}),ResponseProcessor,init_ResponseProcessor=__esm({"src/study/services/ResponseProcessor.ts"(){init_core(),init_logger(),ResponseProcessor=class{constructor(e,t,n){_defineProperty(this,`srsService`,void 0),_defineProperty(this,`eloService`,void 0),_defineProperty(this,`onEloEvent`,void 0),this.srsService=e,this.eloService=t,this.onEloEvent=n}logEloFailure(e,t){return n=>logger.error(`[ResponseProcessor] ELO update failed (${e}) for ${t}:`,n)}trackElo(e,t,n){e.then(e=>{e&&this.onEloEvent?.(e)}).catch(this.logEloFailure(t,n))}parsePerformance(e){return typeof e==`number`?{globalScore:e,taggedPerformance:null}:isTaggedPerformance(e)?{globalScore:e._global,taggedPerformance:e}:(logger.warn(`[ResponseProcessor] Unexpected performance structure, using neutral score`,{performance:e}),{globalScore:.5,taggedPerformance:null})}async processResponse(e,t,n,r,a,o,s,c,l,u){if(!isQuestionRecord(e))return{nextCardAction:`dismiss-success`,shouldLoadNextCard:!0,isCorrect:!0,shouldClearFeedbackShadow:!0};try{let d=await t,p;return p=e.isCorrect?this.processCorrectResponse(e,d,n,r,a,o,s,l,u):this.processIncorrectResponse(e,d,r,a,o,s,c,l,u),e.deferAdvance&&p.shouldLoadNextCard&&(logger.info(`[ResponseProcessor] deferAdvance requested — suppressing navigation, action stashed:`,{nextCardAction:p.nextCardAction}),p={...p,shouldLoadNextCard:!1,deferred:!0}),p}catch(e){throw logger.error(`[ResponseProcessor] Failed to load card history`,{e,cardId:s}),e}}processCorrectResponse(e,t,n,r,a,o,s,c,l){if(e.priorAttemps===0){a.card.tags.includes(`srs:skip`)||this.srsService.scheduleReview(t,n);let{globalScore:c,taggedPerformance:l}=this.parsePerformance(e.performance);if(l){let n=Object.keys(l).filter(e=>e!==`_global`),c=n.filter(e=>l[e]===null),u=n.filter(e=>l[e]!==null);logger.info(`[FirstContactElo] correct first-attempt per-tag ELO update for ${s} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps}): scored=[${u.join(`, `)}] count-only=[${c.join(`, `)}]`),this.trackElo(this.eloService.updateUserAndCardEloPerTag(l,o,s,r,a),`correct per-tag`,s)}else{let n=.5+c/2;if(t.records.length===1)this.trackElo(this.eloService.updateUserAndCardElo(n,o,s,r,a),`correct`,s);else{let e=Math.ceil(32/t.records.length);this.trackElo(this.eloService.updateUserAndCardElo(n,o,s,r,a,e),`correct repeat-view`,s)}logger.info(`[FirstContactElo] correct first-attempt ELO update (score=${n.toFixed(3)}) for ${s} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps})`)}return{nextCardAction:`dismiss-success`,shouldLoadNextCard:!0,isCorrect:!0,performanceScore:c,shouldClearFeedbackShadow:!0}}else{let t=l>=c;logger.info(`[ResponseProcessor] Processed correct response (retry attempt - no scheduling/ELO); sessionViews=${l}/${c} -> ${t?`dismiss-success`:`marked-failed`}`);let{globalScore:n}=this.parsePerformance(e.performance);return{nextCardAction:t?`dismiss-success`:`marked-failed`,shouldLoadNextCard:!0,isCorrect:!0,performanceScore:n,shouldClearFeedbackShadow:!0}}}processIncorrectResponse(e,t,n,r,a,o,s,c,l){let{taggedPerformance:u}=this.parsePerformance(e.performance),d=!1;return e.priorAttemps===0?(u?(this.trackElo(this.eloService.updateUserAndCardEloPerTag(u,a,o,n,r),`incorrect per-tag`,o),logger.info(`[FirstContactElo] incorrect first-attempt per-tag ELO update for ${o} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps}, tags=${Object.keys(u).length-1})`)):(this.trackElo(this.eloService.updateUserAndCardElo(0,a,o,n,r),`incorrect`,o),logger.info(`[FirstContactElo] incorrect first-attempt ELO update (score=0) for ${o} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps})`)),d=!0):logger.info(`[FirstContactElo] incorrect retry \u2014 no ELO update for ${o} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps})`),r.records.length>=s?l>=c?(d?logger.info(`[FirstContactElo] dismiss-failed \u2014 ELO already updated this response, skipping double penalty for ${o}`):(u?this.trackElo(this.eloService.updateUserAndCardEloPerTag(u,a,o,n,r),`dismiss-failed per-tag`,o):this.trackElo(this.eloService.updateUserAndCardElo(0,a,o,n,r),`dismiss-failed`,o),logger.info(`[FirstContactElo] dismiss-failed final ELO penalty for ${o} (historyLen=${t.records.length}, sessionViews=${l})`)),{nextCardAction:`dismiss-failed`,shouldLoadNextCard:!0,isCorrect:!1,shouldClearFeedbackShadow:!0}):{nextCardAction:`marked-failed`,shouldLoadNextCard:!0,isCorrect:!1,shouldClearFeedbackShadow:!0}:{nextCardAction:`none`,shouldLoadNextCard:!1,isCorrect:!1,shouldClearFeedbackShadow:!0}}}}});function parseAudioURIs(e){return typeof e==`string`?e.match(/https?:\/\/[^\s"'<>]+\.(wav|mp3|ogg|m4a|aac|webm)/gi)??[]:[]}function prefetchAudio(e){return new Promise(t=>{let n=new Audio;n.preload=`auto`;let cleanup=()=>{n.oncanplaythrough=null,n.onerror=null};n.oncanplaythrough=()=>{cleanup(),t()},n.onerror=()=>{cleanup(),logger.warn(`[CardHydrationService] Failed to prefetch audio: ${e}`),t()},n.src=e})}var CardHydrationService,init_CardHydrationService=__esm({"src/study/services/CardHydrationService.ts"(){init_logger(),CardHydrationService=class{constructor(e,t,n){_defineProperty(this,`hydratedCards`,new Map),_defineProperty(this,`hydrationInFlight`,new Set),_defineProperty(this,`hydrationInProgress`,!1),this.getViewComponent=e,this.getCourseDB=t,this.getItemsToHydrate=n}getHydratedCard(e){return this.hydratedCards.get(e)??null}hasHydratedCard(e){return this.hydratedCards.has(e)}removeCard(e){this.hydratedCards.delete(e)}async ensureHydratedCards(){this.fillHydratedCards()}async waitForCard(e){if(this.hydratedCards.has(e))return this.hydratedCards.get(e);this.hydrationInProgress||this.fillHydratedCards();let t=1e4,n=25,r=0;for(;r<1e4;){if(this.hydratedCards.has(e))return this.hydratedCards.get(e);if(!this.hydrationInFlight.has(e)&&!this.hydrationInProgress)break;await new Promise(e=>setTimeout(e,25)),r+=25}return this.hydratedCards.get(e)??null}get hydratedCount(){return this.hydratedCards.size}getHydratedCardIds(){return Array.from(this.hydratedCards.keys())}async fillHydratedCards(){if(!this.hydrationInProgress){this.hydrationInProgress=!0;try{let e=this.getItemsToHydrate();for(let t of e)if(!(this.hydratedCards.has(t.cardID)||this.hydrationInFlight.has(t.cardID)))try{await this.hydrateCard(t)}catch(e){logger.error(`[CardHydrationService] Error hydrating card ${t.cardID}:`,e)}}finally{this.hydrationInProgress=!1}}}async hydrateCard(e){if(!(this.hydratedCards.has(e.cardID)||this.hydrationInFlight.has(e.cardID))){this.hydrationInFlight.add(e.cardID);try{let t=this.getCourseDB(e.courseID),[n,r]=await Promise.all([t.getCourseDoc(e.cardID),t.getAppliedTagsBatch([e.cardID])]);isCourseElo(n.elo)||(n.elo=toCourseElo(n.elo));let a=this.getViewComponent(n.id_view),o=await Promise.all(n.id_displayable_data.map(e=>t.getCourseDoc(e,{attachments:!0,binary:!0}))),s=[];o.forEach(e=>{e.data.forEach(e=>{s.push(...parseAudioURIs(e.data))})});let c=[...new Set(s)];c.length>0&&(logger.debug(`[CardHydrationService] Prefetching ${c.length} audio files for card ${e.cardID}`),await Promise.allSettled(c.map(prefetchAudio)));let l=o.map(displayableDataToViewData).reverse();this.hydratedCards.set(e.cardID,{item:{...e,elo:toCourseElo(n.elo).global.score},view:a,data:l,tags:r.get(e.cardID)??[]}),logger.debug(`[CardHydrationService] Hydrated card ${e.cardID}`)}finally{this.hydrationInFlight.delete(e.cardID)}}}}}}),ItemQueue,init_ItemQueue=__esm({"src/study/ItemQueue.ts"(){ItemQueue=class{constructor(){_defineProperty(this,`q`,[]),_defineProperty(this,`seenCardIds`,[]),_defineProperty(this,`_dequeueCount`,0)}get dequeueCount(){return this._dequeueCount}add(e,t){this.seenCardIds.find(e=>e===t)||(this.seenCardIds.push(t),this.q.push(e))}addAll(e,t){e.forEach(e=>this.add(e,t(e)))}get length(){return this.q.length}peek(e){return this.q[e]}dequeue(e){if(this.q.length!==0){this._dequeueCount++;let t=this.q.splice(0,1)[0];if(e){let n=e(t),r=this.seenCardIds.indexOf(n);r>-1&&this.seenCardIds.splice(r,1)}return t}else return null}replaceAll(e,t){this.q=[],this.seenCardIds=[];for(let n of e){let e=t(n);this.seenCardIds.includes(e)||(this.seenCardIds.push(e),this.q.push(n))}}mergeToFront(e,t,n){let r=0,a=[];for(let o of e){let e=t(o);if(!this.seenCardIds.includes(e))this.seenCardIds.push(e),a.push(o),r++;else if(n?.has(e)){let n=this.q.findIndex(n=>t(n)===e);n>=0&&a.push(...this.q.splice(n,1))}}return this.q.unshift(...a),r}get toString(){return`${typeof this.q[0]}:
282
283
  `+this.q.map(e=>` ${e.courseID}+${e.cardID}: ${e.status}`).join(`
283
284
  `)}}}});function makeStudySessionId(e,t,n){return`${DocTypePrefixes.STUDY_SESSION}::${e}::${t}::${n}`}function newSessionId(){return`session-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var init_studySession=__esm({"src/core/types/studySession.ts"(){init_types_legacy()}}),init_types3=__esm({"src/util/packer/types.ts"(){}}),CouchDBToStaticPacker,init_CouchDBToStaticPacker=__esm({"src/util/packer/CouchDBToStaticPacker.ts"(){init_types_legacy(),init_logger(),CouchDBToStaticPacker=class{constructor(e={}){_defineProperty(this,`config`,void 0),_defineProperty(this,`sourceDB`,null),this.config={chunkSize:1e3,includeAttachments:!0,...e}}async packCourse(e,t){logger.info(`Starting static pack for course: ${t}`),this.sourceDB=e;let n={version:`1.0.0`,courseId:t,courseName:``,courseConfig:null,lastUpdated:new Date().toISOString(),documentCount:0,chunks:[],indices:[],designDocs:[]},r=await this.extractCourseConfig(e);n.courseName=r.name,n.courseConfig=r,n.designDocs=await this.extractDesignDocs(e);let a=await this.extractDocumentsByType(e),o=new Map;this.config.includeAttachments&&await this.extractAllAttachments(a,o);let s=new Map;for(let[e,t]of Object.entries(a)){let r=this.createChunks(t,e);n.chunks.push(...r),n.documentCount+=t.length,this.prepareChunkData(r,t,s)}let c=new Map;return n.indices=await this.buildIndices(a,n.designDocs,c),{manifest:n,chunks:s,indices:c,attachments:o}}async packCourseToFiles(e,t,n,r){logger.info(`Packing course ${t} to files in ${n}`);let a=await this.packCourse(e,t),o=await this.writePackedDataToFiles(a,n,r);return{manifest:a.manifest,filesWritten:o,attachmentsFound:a.attachments?a.attachments.size:0}}async writePackedDataToFiles(e,t,n){let r=0;await n.ensureDir(t);let a=n.joinPath(t,`manifest.json`);await n.writeJson(a,e.manifest,{spaces:2}),r++,logger.info(`Wrote manifest: ${a}`);let o=n.joinPath(t,`chunks`),s=n.joinPath(t,`indices`);await n.ensureDir(o),await n.ensureDir(s);for(let[t,a]of e.chunks){let e=n.joinPath(o,`${t}.json`);await n.writeJson(e,a),r++}logger.info(`Wrote ${e.chunks.size} chunk files`);for(let[t,a]of e.indices){let e=n.joinPath(s,`${t}.json`);await n.writeJson(e,a,{spaces:2}),r++}if(logger.info(`Wrote ${e.indices.size} index files`),e.attachments&&e.attachments.size>0){for(let[a,o]of e.attachments){let e=n.joinPath(t,a),s=n.dirname(e);await n.ensureDir(s),await n.writeFile(e,o.buffer),r++}logger.info(`Wrote ${e.attachments.size} attachment files`)}return r}async extractCourseConfig(e){try{return await e.get(`CourseConfig`)}catch(e){throw logger.error(`Failed to extract course config:`,e),Error(`Course config not found`)}}async extractDesignDocs(e){return(await e.allDocs({startkey:`_design/`,endkey:`_design/￰`,include_docs:!0})).rows.map(e=>({_id:e.id,views:e.doc.views||{}}))}async extractDocumentsByType(e){let t=await e.allDocs({include_docs:!0}),n={};for(let e of t.rows){if(e.id.startsWith(`_`))continue;let t=e.doc;t.docType&&(n[t.docType]||(n[t.docType]=[]),n[t.docType].push(t))}return n}createChunks(e,t){let n=[],r=e.sort((e,t)=>e._id.localeCompare(t._id));for(let e=0;e<r.length;e+=this.config.chunkSize){let a=r.slice(e,e+this.config.chunkSize),o=`${t}-${String(Math.floor(e/this.config.chunkSize)).padStart(4,`0`)}`;n.push({id:o,docType:t,startKey:a[0]._id,endKey:a[a.length-1]._id,documentCount:a.length,path:`chunks/${o}.json`})}return n}prepareChunkData(e,t,n){let r=t.sort((e,t)=>e._id.localeCompare(t._id));for(let t of e){let e=r.filter(e=>e._id>=t.startKey&&e._id<=t.endKey).map(e=>{let t={...e};return delete t._rev,this.config.includeAttachments&&t._attachments?t._attachments=this.transformAttachmentStubs(t._attachments,t._id):this.config.includeAttachments||delete t._attachments,t});n.set(t.id,e)}}async buildIndices(e,t,n){let r=[];if(e.CARD){let t=await this.buildEloIndex(e.CARD,n);r.push(t)}if(e.TAG){let t=await this.buildTagIndex(e.TAG,n);r.push(t)}for(let e of t)for(let[t,a]of Object.entries(e.views))if(a.map){logger.info(`Processing view: ${e._id}/${t}`);let a=await this.buildViewIndex(t,e,n);a?(r.push(a),logger.info(`Successfully built index: ${a.name}`)):logger.warn(`Skipped view index: ${e._id}/${t}`)}return r}async buildEloIndex(e,t){let n=[];for(let t of e)t.elo?.global?.score&&n.push({elo:t.elo.global.score,cardId:t._id});n.sort((e,t)=>e.elo-t.elo);let r={},a=50;for(let e of n){let t=Math.floor(e.elo/50)*50;r[t]||(r[t]=[]),r[t].push(e.cardId)}return t.set(`elo`,{sorted:n,buckets:r,stats:{min:n[0]?.elo||0,max:n[n.length-1]?.elo||0,count:n.length}}),{name:`elo`,type:`btree`,path:`indices/elo.json`}}async buildTagIndex(e,t){let n={};for(let t of e)n[t.name]={cardIds:t.taggedCards,snippet:t.snippet,count:t.taggedCards.length};let r={};for(let t of e)for(let e of t.taggedCards)r[e]||(r[e]=[]),r[e].push(t.name);return t.set(`tags`,{byTag:n,byCard:r}),{name:`tags`,type:`hash`,path:`indices/tags.json`}}async buildViewIndex(e,t,n){if(!this.sourceDB)return logger.error(`Source database not available for view querying`),null;try{let r=`${t._id.replace(`_design/`,``)}/${e}`;logger.info(`Querying CouchDB view: ${r}`);let a=await this.sourceDB.query(r,{include_docs:!1});if(!a.rows||a.rows.length===0)return logger.warn(`View ${r} returned no results`),null;logger.info(`Successfully queried view ${r}: ${a.rows.length} results`);let o=this.formatViewResults(e,a.rows,t),s=`view-${t._id.replace(`_design/`,``)}-${e}`;return n.set(s,o),{name:s,type:`view`,path:`indices/${s}.json`}}catch(n){return logger.error(`Failed to query view ${t._id}/${e}:`,n),null}}formatViewResults(e,t,n){let r={type:`couchdb-view`,viewName:e,designDoc:n._id,results:t,metadata:{resultCount:t.length,generatedAt:new Date().toISOString()}};switch(e){case`elo`:return this.formatEloViewIndex(t,r);case`getTags`:return this.formatTagsViewIndex(t,r);case`cardsByInexperience`:return this.formatInexperienceViewIndex(t,r);default:return this.formatGenericViewIndex(t,r)}}formatEloViewIndex(e,t){let n=e.sort((e,t)=>typeof e.key==`number`&&typeof t.key==`number`?e.key-t.key:0);return{...t,sorted:n,stats:{min:n[0]?.key||0,max:n[n.length-1]?.key||0,count:n.length}}}formatTagsViewIndex(e,t){let n={};for(let t of e){let e=t.key;typeof e==`string`&&(n[e]||(n[e]=[]),n[e].push(t.id))}return{...t,byTag:n,tagCount:Object.keys(n).length}}formatInexperienceViewIndex(e,t){let n=e.sort((e,t)=>typeof e.key==`number`&&typeof t.key==`number`?e.key-t.key:0);return{...t,sorted:n,stats:{minInexperience:n[0]?.key||0,maxInexperience:n[n.length-1]?.key||0,count:n.length}}}formatGenericViewIndex(e,t){return{...t}}async extractAllAttachments(e,t){logger.info(`Extracting attachments...`);let n=[];for(let t of Object.values(e))n.push(...t);let r=n.filter(e=>e._attachments&&Object.keys(e._attachments).length>0);if(r.length===0){logger.info(`No attachments found`);return}logger.info(`Found ${r.length} documents with attachments`);let a=r.map(e=>this.extractDocumentAttachments(e,t));await Promise.all(a),logger.info(`Extracted ${t.size} attachment files`)}async extractDocumentAttachments(e,t){if(!e._attachments||!this.sourceDB)return;let n=e._id;for(let[r,a]of Object.entries(e._attachments))try{let e=await this.sourceDB.getAttachment(n,r),o;if(e instanceof ArrayBuffer)o=Buffer.from(e);else if(Buffer.isBuffer(e))o=e;else{let t=e;o=Buffer.from(await t.arrayBuffer())}let s=`${r}${this.getFileExtension(a.content_type)}`,c=`attachments/${n}/${s}`;t.set(c,{docId:n,attachmentName:r,filename:s,path:c,contentType:a.content_type,length:a.length||o.length,digest:a.digest,buffer:o}),logger.debug(`Extracted attachment: ${c}`)}catch(e){throw logger.error(`Failed to extract attachment ${n}/${r}:`,e),Error(`Failed to extract attachment ${n}/${r}: ${e}`)}}transformAttachmentStubs(e,t){let n={};for(let[r,a]of Object.entries(e))n[r]={path:`attachments/${t}/${`${r}${this.getFileExtension(a.content_type)}`}`,content_type:a.content_type,length:a.length,digest:a.digest,stub:!1};return n}getFileExtension(e){return{"image/jpeg":`.jpg`,"image/jpg":`.jpg`,"image/png":`.png`,"image/gif":`.gif`,"image/webp":`.webp`,"audio/mpeg":`.mp3`,"audio/mp3":`.mp3`,"audio/wav":`.wav`,"audio/ogg":`.ogg`,"video/mp4":`.mp4`,"video/webm":`.webm`,"application/pdf":`.pdf`,"text/plain":`.txt`,"application/json":`.json`}[e]||``}}}}),init_packer=__esm({"src/util/packer/index.ts"(){init_types3(),init_CouchDBToStaticPacker()}}),DEFAULT_MIGRATION_OPTIONS,init_types4=__esm({"src/util/migrator/types.ts"(){DEFAULT_MIGRATION_OPTIONS={chunkBatchSize:100,validateRoundTrip:!1,cleanupOnFailure:!0,timeout:3e5}}}),FileSystemError,init_FileSystemAdapter=__esm({"src/util/migrator/FileSystemAdapter.ts"(){FileSystemError=class extends Error{constructor(e,t,n,r){super(e),this.operation=t,this.filePath=n,this.cause=r,this.name=`FileSystemError`}}}});async function validateStaticCourse(e,t){let n={valid:!0,manifestExists:!1,chunksExist:!1,attachmentsExist:!1,errors:[],warnings:[]};try{if(t){if(!(await t.stat(e)).isDirectory())return n.errors.push(`Path is not a directory: ${e}`),n.valid=!1,n}else if(!nodeFS)return n.errors.push(`File system access not available - validation skipped`),n.valid=!1,n;else if(!(await nodeFS.promises.stat(e)).isDirectory())return n.errors.push(`Path is not a directory: ${e}`),n.valid=!1,n;let r=`${e}/manifest.json`;try{if(t)if(r=t.joinPath(e,`manifest.json`),await t.exists(r)){n.manifestExists=!0;let e=await t.readFile(r),a=JSON.parse(e);n.courseId=a.courseId,n.courseName=a.courseName,(!a.version||!a.courseId||!a.chunks||!Array.isArray(a.chunks))&&(n.errors.push(`Invalid manifest structure`),n.valid=!1)}else n.errors.push(`Manifest not found: ${r}`),n.valid=!1;else{r=`${e}/manifest.json`,await nodeFS.promises.access(r),n.manifestExists=!0;let t=await nodeFS.promises.readFile(r,`utf8`),a=JSON.parse(t);n.courseId=a.courseId,n.courseName=a.courseName,(!a.version||!a.courseId||!a.chunks||!Array.isArray(a.chunks))&&(n.errors.push(`Invalid manifest structure`),n.valid=!1)}}catch(e){let t=e instanceof FileSystemError?e.message:`Manifest not found or invalid: ${r}`;n.errors.push(t),n.valid=!1}let a=`${e}/chunks`;try{t?(a=t.joinPath(e,`chunks`),await t.exists(a)?(await t.stat(a)).isDirectory()?n.chunksExist=!0:(n.errors.push(`Chunks path is not a directory: ${a}`),n.valid=!1):(n.errors.push(`Chunks directory not found: ${a}`),n.valid=!1)):(a=`${e}/chunks`,(await nodeFS.promises.stat(a)).isDirectory()?n.chunksExist=!0:(n.errors.push(`Chunks path is not a directory: ${a}`),n.valid=!1))}catch(e){let t=e instanceof FileSystemError?e.message:`Chunks directory not found: ${a}`;n.errors.push(t),n.valid=!1}let o;try{t?(o=t.joinPath(e,`attachments`),await t.exists(o)?(await t.stat(o)).isDirectory()&&(n.attachmentsExist=!0):n.warnings.push(`Attachments directory not found: ${o} (this is OK if course has no attachments)`)):(o=`${e}/attachments`,(await nodeFS.promises.stat(o)).isDirectory()&&(n.attachmentsExist=!0))}catch(t){o=o||`${e}/attachments`;let r=t instanceof FileSystemError?t.message:`Attachments directory not found: ${o} (this is OK if course has no attachments)`;n.warnings.push(r)}}catch(e){n.errors.push(`Failed to validate static course: ${e instanceof Error?e.message:String(e)}`),n.valid=!1}return n}async function validateMigration(e,t,n){let r={valid:!0,documentCountMatch:!1,attachmentIntegrity:!1,viewFunctionality:!1,issues:[]};try{logger.info(`Starting migration validation...`),r.documentCountMatch=compareDocumentCounts(t,await getActualDocumentCounts(e),r.issues),await validateCourseConfig(e,n,r.issues),r.viewFunctionality=await validateViews(e,n,r.issues),r.attachmentIntegrity=await validateAttachmentIntegrity(e,r.issues),r.valid=r.documentCountMatch&&r.viewFunctionality&&r.attachmentIntegrity,logger.info(`Migration validation completed. Valid: ${r.valid}`),r.issues.length>0&&(logger.info(`Validation issues: ${r.issues.length}`),r.issues.forEach(e=>{e.type===`error`?logger.error(`${e.category}: ${e.message}`):logger.warn(`${e.category}: ${e.message}`)}))}catch(e){r.valid=!1,r.issues.push({type:`error`,category:`metadata`,message:`Validation failed: ${e instanceof Error?e.message:String(e)}`})}return r}async function getActualDocumentCounts(e){let t={};try{let n=await e.allDocs({include_docs:!0});for(let e of n.rows){if(e.id.startsWith(`_design/`)){t._design=(t._design||0)+1;continue}let n=e.doc;n&&n.docType?t[n.docType]=(t[n.docType]||0)+1:t.unknown=(t.unknown||0)+1}}catch(e){logger.error(`Failed to get actual document counts:`,e)}return t}function compareDocumentCounts(e,t,n){let r=!0;for(let[a,o]of Object.entries(e)){let e=t[a]||0;e!==o&&(r=!1,n.push({type:`error`,category:`documents`,message:`Document count mismatch for ${a}: expected ${o}, got ${e}`}))}for(let[r,a]of Object.entries(t))!e[r]&&r!==`_design`&&n.push({type:`warning`,category:`documents`,message:`Unexpected document type found: ${r} (${a} documents)`});return r}async function validateCourseConfig(e,t,n){try{let r=await e.get(`CourseConfig`);if(!r){n.push({type:`error`,category:`course_config`,message:`CourseConfig document not found after migration`});return}r.courseID||n.push({type:`warning`,category:`course_config`,message:`CourseConfig document missing courseID field`}),r.courseID!==t.courseId&&n.push({type:`warning`,category:`course_config`,message:`CourseConfig courseID mismatch: expected ${t.courseId}, got ${r.courseID}`}),logger.debug(`CourseConfig document validation passed`)}catch(e){e.status===404?n.push({type:`error`,category:`course_config`,message:`CourseConfig document not found in database`}):n.push({type:`error`,category:`course_config`,message:`Failed to validate CourseConfig document: ${e instanceof Error?e.message:String(e)}`})}}async function validateViews(e,t,n){let r=!0;try{for(let a of t.designDocs)try{if(!await e.get(a._id)){r=!1,n.push({type:`error`,category:`views`,message:`Design document not found: ${a._id}`});continue}for(let t of Object.keys(a.views))try{let n=`${a._id}/${t}`;await e.query(n,{limit:1})}catch(e){r=!1,n.push({type:`error`,category:`views`,message:`View not accessible: ${a._id}/${t} - ${e}`})}}catch(e){r=!1,n.push({type:`error`,category:`views`,message:`Failed to validate design document ${a._id}: ${e}`})}}catch(e){r=!1,n.push({type:`error`,category:`views`,message:`View validation failed: ${e instanceof Error?e.message:String(e)}`})}return r}async function validateAttachmentIntegrity(e,t){let n=!0;try{let r=await e.allDocs({include_docs:!0,limit:10}),a=0,o=0;for(let s of r.rows){let r=s.doc;if(r&&r._attachments)for(let[s,c]of Object.entries(r._attachments)){a++;try{await e.getAttachment(r._id,s)&&o++}catch(e){n=!1,t.push({type:`error`,category:`attachments`,message:`Attachment not accessible: ${r._id}/${s} - ${e}`})}}}a===0?t.push({type:`warning`,category:`attachments`,message:`No attachments found in sampled documents`}):logger.info(`Validated ${o}/${a} sampled attachments`)}catch(e){n=!1,t.push({type:`error`,category:`attachments`,message:`Attachment validation failed: ${e instanceof Error?e.message:String(e)}`})}return n}var nodeFS,init_validation=__esm({"src/util/migrator/validation.ts"(){init_logger(),init_FileSystemAdapter(),nodeFS=null;try{typeof window>`u`&&typeof process<`u`&&process.versions?.node&&(nodeFS=eval(`require`)(`fs`),nodeFS.promises=nodeFS.promises||eval(`require`)(`fs`).promises)}catch{}}}),nodeFS2,nodePath,StaticToCouchDBMigrator,init_StaticToCouchDBMigrator=__esm({"src/util/migrator/StaticToCouchDBMigrator.ts"(){init_logger(),init_types4(),init_validation(),init_FileSystemAdapter(),nodeFS2=null,nodePath=null;try{typeof window>`u`&&typeof process<`u`&&process.versions?.node&&(nodeFS2=eval(`require`)(`fs`),nodePath=eval(`require`)(`path`),nodeFS2.promises=nodeFS2.promises||eval(`require`)(`fs`).promises)}catch{}StaticToCouchDBMigrator=class{constructor(e={},t){_defineProperty(this,`options`,void 0),_defineProperty(this,`progressCallback`,void 0),_defineProperty(this,`fs`,void 0),this.options={...DEFAULT_MIGRATION_OPTIONS,...e},this.fs=t}setProgressCallback(e){this.progressCallback=e}async migrateCourse(e,t){let n=Date.now(),r={success:!1,documentsRestored:0,attachmentsRestored:0,designDocsRestored:0,courseConfigRestored:0,errors:[],warnings:[],migrationTime:0};try{logger.info(`Starting migration from ${e} to CouchDB`),this.reportProgress(`manifest`,0,1,`Validating static course...`);let a=await validateStaticCourse(e,this.fs);if(!a.valid)throw r.errors.push(...a.errors),Error(`Static course validation failed: ${a.errors.join(`, `)}`);r.warnings.push(...a.warnings),this.reportProgress(`manifest`,1,1,`Loading course manifest...`);let o=await this.loadManifest(e);logger.info(`Loaded manifest for course: ${o.courseId} (${o.courseName})`),this.reportProgress(`design_docs`,0,o.designDocs.length,`Restoring design documents...`);let s=await this.restoreDesignDocuments(o.designDocs,t);r.designDocsRestored=s.restored,r.errors.push(...s.errors),r.warnings.push(...s.warnings),this.reportProgress(`course_config`,0,1,`Restoring CourseConfig document...`);let c=await this.restoreCourseConfig(o,t);r.courseConfigRestored=c.restored,r.errors.push(...c.errors),r.warnings.push(...c.warnings),this.reportProgress(`course_config`,1,1,`CourseConfig document restored`);let l=this.calculateExpectedCounts(o);this.reportProgress(`documents`,0,o.documentCount,`Aggregating documents from chunks...`);let u=await this.aggregateDocuments(e,o),d=u.filter(e=>e._id!==`CourseConfig`);u.length!==d.length&&r.warnings.push(`Filtered out ${u.length-d.length} CourseConfig document(s) from chunks to prevent conflicts`),this.reportProgress(`documents`,d.length,o.documentCount,`Uploading documents to CouchDB...`);let p=await this.uploadDocuments(d,t);r.documentsRestored=p.restored,r.errors.push(...p.errors),r.warnings.push(...p.warnings);let m=u.filter(e=>e._attachments&&Object.keys(e._attachments).length>0);this.reportProgress(`attachments`,0,m.length,`Uploading attachments...`);let g=await this.uploadAttachments(e,m,t);if(r.attachmentsRestored=g.restored,r.errors.push(...g.errors),r.warnings.push(...g.warnings),this.options.validateRoundTrip){this.reportProgress(`validation`,0,1,`Validating migration...`);let e=await validateMigration(t,l,o);e.valid||(r.warnings.push(`Migration validation found issues`),e.issues.forEach(e=>{e.type===`error`?r.errors.push(`Validation: ${e.message}`):r.warnings.push(`Validation: ${e.message}`)})),this.reportProgress(`validation`,1,1,`Migration validation completed`)}r.success=r.errors.length===0,r.migrationTime=Date.now()-n,logger.info(`Migration completed in ${r.migrationTime}ms`),logger.info(`Documents restored: ${r.documentsRestored}`),logger.info(`Attachments restored: ${r.attachmentsRestored}`),logger.info(`Design docs restored: ${r.designDocsRestored}`),logger.info(`CourseConfig restored: ${r.courseConfigRestored}`),r.errors.length>0&&logger.error(`Migration completed with ${r.errors.length} errors`),r.warnings.length>0&&logger.warn(`Migration completed with ${r.warnings.length} warnings`)}catch(e){r.success=!1,r.migrationTime=Date.now()-n;let a=e instanceof Error?e.message:String(e);if(r.errors.push(`Migration failed: ${a}`),logger.error(`Migration failed:`,e),this.options.cleanupOnFailure)try{await this.cleanupFailedMigration(t)}catch(e){logger.error(`Failed to cleanup after migration failure:`,e),r.warnings.push(`Failed to cleanup after migration failure`)}}return r}async loadManifest(e){try{let t,n;if(this.fs)n=this.fs.joinPath(e,`manifest.json`),t=await this.fs.readFile(n);else if(n=nodeFS2&&nodePath?nodePath.join(e,`manifest.json`):`${e}/manifest.json`,nodeFS2&&this.isLocalPath(e))t=await nodeFS2.promises.readFile(n,`utf8`);else{let e=await fetch(n);if(!e.ok)throw Error(`Failed to fetch manifest: ${e.status} ${e.statusText}`);t=await e.text()}let r=JSON.parse(t);if(!r.version||!r.courseId||!r.chunks)throw Error(`Invalid manifest structure`);return r}catch(e){let t=e instanceof FileSystemError?e.message:`Failed to load manifest: ${e instanceof Error?e.message:String(e)}`;throw Error(t)}}async restoreDesignDocuments(e,t){let n={restored:0,errors:[],warnings:[]};for(let r=0;r<e.length;r++){let a=e[r];this.reportProgress(`design_docs`,r,e.length,`Restoring ${a._id}...`);try{let e;try{e=await t.get(a._id)}catch{}let r={_id:a._id,views:a.views};e?(r._rev=e._rev,logger.debug(`Updating existing design document: ${a._id}`)):logger.debug(`Creating new design document: ${a._id}`),await t.put(r),n.restored++}catch(e){let t=`Failed to restore design document ${a._id}: ${e instanceof Error?e.message:String(e)}`;n.errors.push(t),logger.error(t)}}return this.reportProgress(`design_docs`,e.length,e.length,`Restored ${n.restored} design documents`),n}async aggregateDocuments(e,t){let n=[],r=new Map;for(let a=0;a<t.chunks.length;a++){let o=t.chunks[a];this.reportProgress(`documents`,n.length,t.documentCount,`Loading chunk ${o.id}...`);try{let t=await this.loadChunk(e,o);for(let e of t){if(!e._id){logger.warn(`Document without _id found in chunk ${o.id}, skipping`);continue}r.has(e._id)&&logger.warn(`Duplicate document ID found: ${e._id}, using latest version`),r.set(e._id,e)}}catch(e){throw Error(`Failed to load chunk ${o.id}: ${e instanceof Error?e.message:String(e)}`)}}return n.push(...r.values()),logger.info(`Aggregated ${n.length} unique documents from ${t.chunks.length} chunks`),n}async loadChunk(e,t){try{let n,r;if(this.fs)r=this.fs.joinPath(e,t.path),n=await this.fs.readFile(r);else if(r=nodeFS2&&nodePath?nodePath.join(e,t.path):`${e}/${t.path}`,nodeFS2&&this.isLocalPath(e))n=await nodeFS2.promises.readFile(r,`utf8`);else{let e=await fetch(r);if(!e.ok)throw Error(`Failed to fetch chunk: ${e.status} ${e.statusText}`);n=await e.text()}let a=JSON.parse(n);if(!Array.isArray(a))throw Error(`Chunk file does not contain an array of documents`);return a}catch(e){let t=e instanceof FileSystemError?e.message:`Failed to load chunk: ${e instanceof Error?e.message:String(e)}`;throw Error(t)}}async uploadDocuments(e,t){let n={restored:0,errors:[],warnings:[]},r=this.options.chunkBatchSize;for(let a=0;a<e.length;a+=r){let o=e.slice(a,a+r);this.reportProgress(`documents`,a,e.length,`Uploading batch ${Math.floor(a/r)+1}...`);try{let e=o.map(e=>{let t={...e};return delete t._rev,delete t._attachments,t}),r=await t.bulkDocs(e);for(let e=0;e<r.length;e++){let t=r[e],a=o[e];if(`error`in t){let e=`Failed to upload document ${a._id}: ${t.error} - ${t.reason}`;n.errors.push(e),logger.error(e)}else n.restored++}}catch(e){let t;t=e instanceof Error||e&&typeof e==`object`&&`message`in e?`Failed to upload document batch starting at index ${a}: ${e.message}`:`Failed to upload document batch starting at index ${a}: ${JSON.stringify(e)}`,n.errors.push(t),logger.error(t)}}return this.reportProgress(`documents`,e.length,e.length,`Uploaded ${n.restored} documents`),n}async uploadAttachments(e,t,n){let r={restored:0,errors:[],warnings:[]},a=0;for(let o of t)if(this.reportProgress(`attachments`,a,t.length,`Processing attachments for ${o._id}...`),a++,o._attachments)for(let[t,a]of Object.entries(o._attachments))try{let s=await this.uploadSingleAttachment(e,o._id,t,a,n);s.success?r.restored++:r.errors.push(s.error||`Unknown attachment upload error`)}catch(e){let n=`Failed to upload attachment ${o._id}/${t}: ${e instanceof Error?e.message:String(e)}`;r.errors.push(n),logger.error(n)}return this.reportProgress(`attachments`,t.length,t.length,`Uploaded ${r.restored} attachments`),r}async uploadSingleAttachment(e,t,n,r,a){let o={success:!1,attachmentName:n,docId:t};try{if(!r.path)return o.error=`Attachment metadata missing file path`,o;let s,c;if(this.fs)c=this.fs.joinPath(e,r.path),s=await this.fs.readBinary(c);else if(c=nodeFS2&&nodePath?nodePath.join(e,r.path):`${e}/${r.path}`,nodeFS2&&this.isLocalPath(e))s=await nodeFS2.promises.readFile(c);else{let e=await fetch(c);if(!e.ok)return o.error=`Failed to fetch attachment: ${e.status} ${e.statusText}`,o;s=await e.arrayBuffer()}let l=await a.get(t);await a.putAttachment(t,n,l._rev,s,r.content_type),o.success=!0}catch(e){o.error=e instanceof Error?e.message:String(e)}return o}async restoreCourseConfig(e,t){let n={restored:0,errors:[],warnings:[]};try{if(!e.courseConfig)return n.warnings.push(`No courseConfig found in manifest, skipping CourseConfig document creation`),n;let r={_id:`CourseConfig`,...e.courseConfig,courseID:e.courseId};delete r._rev,await t.put(r),n.restored=1,logger.info(`CourseConfig document created for course: ${e.courseId}`)}catch(e){let t=e instanceof Error?e.message:JSON.stringify(e);n.errors.push(`Failed to restore CourseConfig: ${t}`),logger.error(`CourseConfig restoration failed:`,e)}return n}calculateExpectedCounts(e){let t={};for(let n of e.chunks)t[n.docType]=(t[n.docType]||0)+n.documentCount;return e.designDocs.length>0&&(t._design=e.designDocs.length),t}async cleanupFailedMigration(e){logger.info(`Cleaning up failed migration...`);try{let t=(await e.allDocs()).rows.map(e=>({_id:e.id,_rev:e.value.rev,_deleted:!0}));t.length>0&&(await e.bulkDocs(t),logger.info(`Cleaned up ${t.length} documents from failed migration`))}catch(e){throw logger.error(`Failed to cleanup documents:`,e),e}}reportProgress(e,t,n,r){this.progressCallback&&this.progressCallback({phase:e,current:t,total:n,message:r})}isLocalPath(e){return!e.startsWith(`http://`)&&!e.startsWith(`https://`)}}}}),init_migrator=__esm({"src/util/migrator/index.ts"(){init_StaticToCouchDBMigrator(),init_validation(),init_FileSystemAdapter()}});function getAppDataDirectory(){return ENV.LOCAL_STORAGE_PREFIX?import___vite_browser_external.join(import___vite_browser_external.homedir(),`.tuilder`,ENV.LOCAL_STORAGE_PREFIX):import___vite_browser_external.join(import___vite_browser_external.homedir(),`.tuilder`)}async function ensureAppDataDirectory(){let e=getAppDataDirectory();try{await import___vite_browser_external.promises.mkdir(e,{recursive:!0})}catch(t){if(t.code!==`EEXIST`)throw Error(`Failed to create app data directory ${e}: ${t.message}`)}return e}function getDbPath(e){return import___vite_browser_external.join(getAppDataDirectory(),e)}async function initializeDataDirectory(){await ensureAppDataDirectory(),logger.info(`PouchDB data directory initialized: ${getAppDataDirectory()}`)}var init_dataDirectory=__esm({"src/util/dataDirectory.ts"(){init_logger(),init_factory()}}),init_util2=__esm({"src/util/index.ts"(){init_Loggable(),init_packer(),init_migrator(),init_dataDirectory()}}),QuotaRoundRobinMixer,init_SourceMixer=__esm({"src/study/SourceMixer.ts"(){QuotaRoundRobinMixer=class{mix(e,t){if(e.length===0)return[];let n=Math.ceil(t/e.length),r=e.map(e=>[...e.weighted].sort((e,t)=>t.score-e.score).slice(0,n));for(let e=r.length-1;e>0;e--){let t=Math.floor(Math.random()*(e+1));[r[e],r[t]]=[r[t],r[e]]}let a=[],o=0,s=Array(r.length).fill(0);for(;a.length<t&&o<r.length;){o=0;for(let e=0;e<r.length&&!(a.length>=t);e++)s[e]<r[e].length?(a.push(r[e][s[e]]),s[e]++):o++}return a}}}});function buildSourceSummary(e,t,n){let r=e.weighted.map(e=>e.score),a=e.weighted.filter(e=>getCardOrigin(e)===`review`).length,o=e.weighted.filter(e=>getCardOrigin(e)===`new`).length;return{sourceIndex:e.sourceIndex,sourceId:t,sourceName:n,totalCards:e.weighted.length,reviewCount:a,newCount:o,topScore:r.length>0?Math.max(...r):0,bottomScore:r.length>0?Math.min(...r):0,scoreRange:r.length>0?[Math.min(...r),Math.max(...r)]:[0,0],avgScore:r.length>0?r.reduce((e,t)=>e+t,0)/r.length:0}}function buildSourceBreakdown(e,t,n){let r=n.filter(t=>t.courseId===e),a=r.filter(e=>e.selected);return{sourceId:e,sourceName:t,reviewsProvided:r.filter(e=>e.origin===`review`).length,newProvided:r.filter(e=>e.origin===`new`).length,reviewsSelected:a.filter(e=>e.origin===`review`).length,newSelected:a.filter(e=>e.origin===`new`).length,totalSelected:a.length,selectionRate:r.length>0?a.length/r.length*100:0}}function captureMixerRun(e,t,n,r,a,o,s){let c=t.map((e,t)=>buildSourceSummary(e,n[t]||`source-${t}`,r[t])),l=new Set(s.map(e=>e.cardId)),u=new Map;t.forEach(e=>{let t=[...e.weighted].sort((e,t)=>t.score-e.score),r=new Map;t.forEach((e,t)=>{r.set(e.cardId,t+1)}),u.set(n[e.sourceIndex]||`source-${e.sourceIndex}`,r)});let d=new Map;s.forEach((e,t)=>{d.set(e.cardId,t+1)});let p=new Map;t.forEach(e=>{e.weighted.forEach(e=>{p.set(e.cardId,e)})});let m=Array.from(p.values()).map(e=>({cardId:e.cardId,courseId:e.courseId,origin:getCardOrigin(e),score:e.score,sourceIndex:t.findIndex(t=>t.weighted.some(t=>t.cardId===e.cardId)),selected:l.has(e.cardId),rankInSource:u.get(e.courseId)?.get(e.cardId),rankInMix:d.get(e.cardId)})),g=Array.from(new Set(n.filter(e=>e))).map((e,t)=>buildSourceBreakdown(e,r[t],m)),_={runId:`mix-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date,mixerType:e,requestedLimit:a,quotaPerSource:o,sourceSummaries:c,cards:m,finalCount:s.length,reviewsSelected:s.filter(e=>getCardOrigin(e)===`review`).length,newSelected:s.filter(e=>getCardOrigin(e)===`new`).length,sourceBreakdowns:g};runHistory2.unshift(_),runHistory2.length>MAX_RUNS2&&runHistory2.pop()}function printMixerSummary(e){console.group(`\u{1F3A8} Mixer Run: ${e.mixerType}`),logger.info(`Run ID: ${e.runId}`),logger.info(`Time: ${e.timestamp.toISOString()}`),logger.info(`Config: limit=${e.requestedLimit}${e.quotaPerSource?`, quota/source=${e.quotaPerSource}`:``}`),console.group(`\u{1F4E5} Input: ${e.sourceSummaries.length} sources`);for(let t of e.sourceSummaries)logger.info(` ${t.sourceName||t.sourceId}: ${t.totalCards} cards (${t.reviewCount} reviews, ${t.newCount} new)`),logger.info(` Score range: [${t.scoreRange[0].toFixed(2)}, ${t.scoreRange[1].toFixed(2)}], avg: ${t.avgScore.toFixed(2)}`);console.groupEnd(),console.group(`\u{1F4E4} Output: ${e.finalCount} cards selected (${e.reviewsSelected} reviews, ${e.newSelected} new)`);for(let t of e.sourceBreakdowns){let e=t.sourceName||t.sourceId;logger.info(` ${e}: ${t.totalSelected} selected (${t.reviewsSelected} reviews, ${t.newSelected} new) - ${t.selectionRate.toFixed(1)}% selection rate`)}console.groupEnd(),console.groupEnd()}function mountMixerDebugger(){if(typeof window>`u`)return;let e=window;e.skuilder=e.skuilder||{},e.skuilder.mixer=mixerDebugAPI}var MAX_RUNS2,runHistory2,mixerDebugAPI,init_MixerDebugger=__esm({"src/study/MixerDebugger.ts"(){init_logger(),init_navigators(),MAX_RUNS2=10,runHistory2=[],mixerDebugAPI={get runs(){return[...runHistory2]},showRun(e=0){if(runHistory2.length===0){logger.info(`[Mixer Debug] No runs captured yet.`);return}let t;if(typeof e==`number`){if(t=runHistory2[e],!t){logger.info(`[Mixer Debug] No run found at index ${e}. History length: ${runHistory2.length}`);return}}else if(t=runHistory2.find(t=>t.runId.endsWith(e)),!t){logger.info(`[Mixer Debug] No run found matching ID '${e}'.`);return}printMixerSummary(t)},showLastMix(){this.showRun(0)},explainSourceBalance(){if(runHistory2.length===0){logger.info(`[Mixer Debug] No runs captured yet.`);return}let e=runHistory2[0];console.group(`⚖️ Source Balance Analysis`),logger.info(`Mixer: ${e.mixerType}`),logger.info(`Requested limit: ${e.requestedLimit}`),e.quotaPerSource&&logger.info(`Quota per source: ${e.quotaPerSource}`),console.group(`Input Distribution:`);for(let t of e.sourceSummaries){let e=t.sourceName||t.sourceId;logger.info(`${e}:`),logger.info(` Provided: ${t.totalCards} cards (${t.reviewCount} reviews, ${t.newCount} new)`),logger.info(` Score range: [${t.scoreRange[0].toFixed(2)}, ${t.scoreRange[1].toFixed(2)}]`)}console.groupEnd(),console.group(`Selection Results:`);for(let t of e.sourceBreakdowns){let e=t.sourceName||t.sourceId;logger.info(`${e}:`),logger.info(` Selected: ${t.totalSelected}/${t.reviewsProvided+t.newProvided} (${t.selectionRate.toFixed(1)}%)`),logger.info(` Reviews: ${t.reviewsSelected}/${t.reviewsProvided}`),logger.info(` New: ${t.newSelected}/${t.newProvided}`),t.reviewsProvided>0&&t.reviewsSelected===0&&logger.info(` ⚠️ Had reviews but none selected!`),t.totalSelected===0&&t.reviewsProvided+t.newProvided>0&&logger.info(` ⚠️ Had cards but none selected!`)}console.groupEnd();let t=e.sourceBreakdowns.map(e=>e.selectionRate),n=t.reduce((e,t)=>e+t,0)/t.length,r=Math.max(...t.map(e=>Math.abs(e-n)));r>20&&(logger.info(`
284
285
  \u26A0\uFE0F Significant imbalance detected (max deviation: ${r.toFixed(1)}%)`),logger.info(`Possible causes:`),logger.info(` - Score range differences between sources`),logger.info(` - One source has much better quality cards`),logger.info(` - Different card availability (reviews vs new)`)),console.groupEnd()},compareScores(){if(runHistory2.length===0){logger.info(`[Mixer Debug] No runs captured yet.`);return}let e=runHistory2[0];console.group(`📊 Score Distribution Comparison`),console.table(e.sourceSummaries.map(e=>({source:e.sourceName||e.sourceId,cards:e.totalCards,min:e.bottomScore.toFixed(3),max:e.topScore.toFixed(3),avg:e.avgScore.toFixed(3),range:(e.topScore-e.bottomScore).toFixed(3)})));let t=e.sourceSummaries.map(e=>e.topScore-e.bottomScore),n=e.sourceSummaries.map(e=>e.avgScore),r=Math.max(...t)-Math.min(...t),a=Math.max(...n)-Math.min(...n);(r>.3||a>.2)&&(logger.info(`
@@ -327,12 +328,12 @@ Example:
327
328
  window.skuilder.session.showHistory()
328
329
  window.skuilder.session.showInterleaving()
329
330
  window.skuilder.session.showQueue()
330
- `)}},mountSessionDebugger()}});function sig4(e){return Number(e.toPrecision(4))}function toRunCard(e){return{cardId:e.cardId,origin:e.origin,...e.generator?{generator:e.generator}:{},...e.required?{required:e.required}:{},score:Number.isFinite(e.finalScore)?sig4(e.finalScore):null,selected:e.selected}}function toRunCardTrail(e){return{...toRunCard(e),trail:e.provenance.filter(e=>e.action!==`passed`).map(e=>({strategyName:e.strategyName,action:e.action,score:sig4(e.score),reason:e.reason}))}}function persistedReading(e){return{...e,urgency:sig4(e.urgency),multiplier:sig4(e.multiplier),inputs:Object.fromEntries(Object.entries(e.inputs).map(([e,t])=>[e,sig4(t)]))}}function persistedRunCards(e){let t=e.cards.filter(e=>e.selected),n=e.cards.filter(e=>!e.selected).slice(0,PERSISTED_RUNNERS_UP);return[...t,...n].map(toRunCard)}function persistedUnselectedNew(e){return{...e.nextInLine?{nextInLine:toRunCardTrail(e.nextInLine)}:{},...e.topGenerated?{topGenerated:toRunCardTrail(e.topGenerated)}:{}}}var PERSISTED_RUNNERS_UP,SessionController,init_SessionController=__esm({"src/study/SessionController.ts"(){var e;init_SrsService(),init_EloService(),init_ResponseProcessor(),init_CardHydrationService(),init_ItemQueue(),init_couch(),init_core(),init_types_legacy(),init_studySession(),init_recording(),init_util2(),init_navigators(),init_Pipeline(),init_SourceMixer(),init_MixerDebugger(),init_SessionDebugger(),init_SessionOverlay(),init_logger(),PERSISTED_RUNNERS_UP=5,SessionController=(e=class _SessionController extends Loggable{set sessionRecord(e){this._sessionRecord=e}get secondsRemaining(){return this._secondsRemaining}get hasCardGuarantee(){return this._minCardsGuarantee>0}get report(){let e=this.supplyQ.dequeueCount;return`${e} supply ${e===1?`card`:`cards`} drawn`}get detailedReport(){return this.supplyQ.toString+`
331
+ `)}},mountSessionDebugger()}});function sig4(e){return Number(e.toPrecision(4))}function toRunCard(e){return{cardId:e.cardId,origin:e.origin,...e.generator?{generator:e.generator}:{},...e.required?{required:e.required}:{},score:Number.isFinite(e.finalScore)?sig4(e.finalScore):null,selected:e.selected}}function toRunCardTrail(e){return{...toRunCard(e),trail:e.provenance.filter(e=>e.action!==`passed`).map(e=>({strategyName:e.strategyName,action:e.action,score:sig4(e.score),reason:e.reason}))}}function persistedReading(e){return{...e,urgency:sig4(e.urgency),multiplier:sig4(e.multiplier),inputs:Object.fromEntries(Object.entries(e.inputs).map(([e,t])=>[e,sig4(t)]))}}function persistedRunCards(e){let t=e.cards.filter(e=>e.selected),n=e.cards.filter(e=>!e.selected).slice(0,PERSISTED_RUNNERS_UP);return[...t,...n].map(toRunCard)}function persistedUnselectedNew(e){return{...e.nextInLine?{nextInLine:toRunCardTrail(e.nextInLine)}:{},...e.topGenerated?{topGenerated:toRunCardTrail(e.topGenerated)}:{}}}var PERSISTED_RUNNERS_UP,SessionController,init_SessionController=__esm({"src/study/SessionController.ts"(){var e;init_SrsService(),init_EloService(),init_ResponseProcessor(),init_CardHydrationService(),init_ItemQueue(),init_couch(),init_core(),init_types_legacy(),init_studySession(),init_recording(),init_util2(),init_navigators(),init_Pipeline(),init_versionStamps(),init_SourceMixer(),init_MixerDebugger(),init_SessionDebugger(),init_SessionOverlay(),init_logger(),PERSISTED_RUNNERS_UP=5,SessionController=(e=class _SessionController extends Loggable{set sessionRecord(e){this._sessionRecord=e}get secondsRemaining(){return this._secondsRemaining}get hasCardGuarantee(){return this._minCardsGuarantee>0}get report(){let e=this.supplyQ.dequeueCount;return`${e} supply ${e===1?`card`:`cards`} drawn`}get detailedReport(){return this.supplyQ.toString+`
331
332
  `+this.failedQ.toString}constructor(e,t,n,r,a,o){super(),_defineProperty(this,`_className`,`SessionController`),_defineProperty(this,`services`,void 0),_defineProperty(this,`srsService`,void 0),_defineProperty(this,`eloService`,void 0),_defineProperty(this,`hydrationService`,void 0),_defineProperty(this,`mixer`,void 0),_defineProperty(this,`dataLayer`,void 0),_defineProperty(this,`courseNameCache`,new Map),_defineProperty(this,`_defaultBatchLimit`,20),_defineProperty(this,`sources`,void 0),_defineProperty(this,`_sessionRecord`,[]),_defineProperty(this,`_currentCard`,null),_defineProperty(this,`supplyQ`,new ItemQueue),_defineProperty(this,`failedQ`,new ItemQueue),_defineProperty(this,`_supplyDrawsSinceFailed`,0),_defineProperty(this,`_replanPromise`,null),_defineProperty(this,`_activeReplanLabel`,null),_defineProperty(this,`_wellIndicatedRemaining`,0),_defineProperty(this,`_suppressQualityReplan`,!1),_defineProperty(this,`_minCardsGuarantee`,0),_defineProperty(this,`_sessionHints`,null),_defineProperty(this,`_servedCardIds`,new Set),_defineProperty(this,`_outcomeObservers`,[]),_defineProperty(this,`_sessionControls`,null),_defineProperty(this,`sessionId`,void 0),_defineProperty(this,`_courseId`,void 0),_defineProperty(this,`_stateSnapshotProvider`,void 0),_defineProperty(this,`_sessionDoc`,null),_defineProperty(this,`_openDocPromise`,null),_defineProperty(this,`_runLog`,[]),_defineProperty(this,`_eloLog`,[]),_defineProperty(this,`_sessionClosed`,!1),_defineProperty(this,`startTime`,void 0),_defineProperty(this,`endTime`,void 0),_defineProperty(this,`_secondsRemaining`,void 0),_defineProperty(this,`_intervalHandle`,void 0),this.sessionId=newSessionId(),setDebugSessionId(this.sessionId),this.dataLayer=n,this.mixer=a||new QuotaRoundRobinMixer,this.srsService=new SrsService(n.getUserDB()),this.eloService=new EloService(n,n.getUserDB()),this.hydrationService=new CardHydrationService(r,e=>n.getCourseDB(e),()=>this._getItemsToHydrate()),this.services={response:new ResponseProcessor(this.srsService,this.eloService,e=>this._recordEloEvent(e))},this.sources=e,this.startTime=new Date,this._secondsRemaining=t,this.endTime=new Date(this.startTime.valueOf()+1e3*this._secondsRemaining),o?.defaultBatchLimit!==void 0&&(this._defaultBatchLimit=o.defaultBatchLimit),o?.outcomeObservers?.length&&(this._outcomeObservers=[...o.outcomeObservers]),this._courseId=o?.courseId,this._stateSnapshotProvider=o?.stateSnapshotProvider,this.log(`Session constructed:
332
333
  sessionId: ${this.sessionId}
333
334
  startTime: ${this.startTime}
334
335
  endTime: ${this.endTime}
335
- defaultBatchLimit: ${this._defaultBatchLimit}`),registerActiveController(this)}tick(){this._secondsRemaining=Math.floor((this.endTime.valueOf()-Date.now())/1e3),this._secondsRemaining<=0&&clearInterval(this._intervalHandle)}estimateCleanupTime(){let e=0;for(let t=0;t<this.failedQ.length;t++){let n=this.failedQ.peek(t),r=this._sessionRecord.find(e=>e.item.cardID===n.cardID),a=0;if(r){for(let e=0;e<r.records.length;e++)a+=r.records[e].timeSpent;a/=r.records.length,e+=a}}let t=e/1e3;return this.log(`Failed card cleanup estimate: ${Math.round(t)}`),t}async prepareSession(){if(this.sources.some(e=>typeof e.getWeightedCards!=`function`))throw Error(`[SessionController] All content sources must implement getWeightedCards().`);clearStaleSessionDebugState();let e=await this.getWeightedContent();this._recordRuns(`bootstrap`),this._wellIndicatedRemaining=e,e>=0&&e<_SessionController.MIN_WELL_INDICATED&&this.log(`[Init] Only ${e}/${_SessionController.MIN_WELL_INDICATED} well-indicated cards in initial load`),await this.hydrationService.ensureHydratedCards(),startSessionTracking(this.sessionId,this.supplyQ.length,this.failedQ.length),this._openDocPromise=this._openSessionDoc(),this._intervalHandle=setInterval(()=>{this.tick()},1e3)}_recordRuns(e,t){for(let n of drainCapturedRuns()){if(this._runLog.length>=_SessionController.MAX_LOGGED_RUNS)break;this._runLog.push({runId:n.runId,at:n.timestamp.toISOString(),label:e,...t?{mode:t}:{},generatedCount:n.generatedCount,finalCount:n.finalCount,reviewsSelected:n.reviewsSelected,newSelected:n.newSelected,...typeof n.userElo==`number`?{userElo:n.userElo}:{},...n.generators?{generators:n.generators}:{},...n.filters?{filters:n.filters}:{},...n.hints?{hints:n.hints}:{},...n.discardedTail?{discardedTail:n.discardedTail}:{},cards:persistedRunCards(n),...n.unselectedNew?{unselectedNew:persistedUnselectedNew(n.unselectedNew)}:{},...n.regulators?{regulators:n.regulators.map(persistedReading)}:{}})}}async _captureState(e){if(!this._stateSnapshotProvider)return;let t=3e3;try{return await Promise.race([Promise.resolve(this._stateSnapshotProvider(e)),new Promise(e=>setTimeout(()=>e(void 0),3e3))])}catch(t){this.log(`[Session] state snapshot (${e}) failed: ${t}`);return}}async _openSessionDoc(){if(this._courseId)try{let e=this.dataLayer.getUserDB(),t={_id:makeStudySessionId(this._courseId,e.getUsername(),this.sessionId),docType:`STUDY_SESSION`,sessionId:this.sessionId,courseId:this._courseId,userId:e.getUsername(),startTime:this.startTime.toISOString(),status:`open`,plannedSeconds:Math.round((this.endTime.valueOf()-this.startTime.valueOf())/1e3),config:{defaultBatchLimit:this._defaultBatchLimit,sourceCount:this.sources.length,initHints:this._sessionHints},initialQueues:{supplyQ:this.supplyQ.length,failedQ:this.failedQ.length},runs:[...this._runLog],stateAtStart:await this._captureState(`start`)};this._sessionDoc=t,await e.putStudySession(t),this.log(`[Session] Opened session record ${t._id}`)}catch(e){logger.warn(`[SessionController] Failed to open session record: ${e}`)}}async requestReplan(e){let t=this.normalizeReplanOptions(e),n=this._replanHasIntent(t);if(this._replanPromise){if(!n)return this.log(`Replan already in progress, coalescing unhinted auto-replan`),this._replanPromise;let e=t.label?` [${t.label}]`:``;this.log(`Replan in progress; queueing hint-bearing replan${e} behind in-flight run`);let r=this._replanPromise.catch(()=>void 0).then(()=>this._runReplan(t)),a=r.finally(()=>{this._replanPromise===a&&(this._replanPromise=null,this._activeReplanLabel=null)});return this._replanPromise=a,r}let r=this._runReplan(t),a=r.finally(()=>{this._replanPromise===a&&(this._replanPromise=null,this._activeReplanLabel=null)});this._replanPromise=a,await r}_replanHasIntent(e){return!!(e.limit!==void 0||e.minFollowUpCards!==void 0||e.mode&&e.mode!==`replace`||e.hints&&Object.keys(e.hints).length>0||e.sessionHints!==void 0||e.mergeSessionHints!==void 0)}async _runReplan(e){this._activeReplanLabel=e.label??`(auto)`,e.hints||(e.hints={});let t=e.hints,n=new Set(t.excludeCards??[]);this._currentCard?.item.cardID&&n.add(this._currentCard.item.cardID);for(let e of this._sessionRecord)n.add(e.card.card_id);this.supplyQ.length>0&&n.add(this.supplyQ.peek(0).cardID),t.excludeCards=[...n],e.sessionHints!==void 0&&(this._sessionHints=e.sessionHints,this.log(`[Replan] Session hints ${e.sessionHints?`set`:`cleared`}: ${JSON.stringify(e.sessionHints)}`)),e.mergeSessionHints!==void 0&&(this._sessionHints=mergeHints2([this._sessionHints,e.mergeSessionHints])??null,this.log(`[Replan] Session hints merged: ${JSON.stringify(this._sessionHints)}`)),this._applyHintsToSources(e.hints,e.label);let r=e.label?` [${e.label}]`:``;this.log(`Mid-session replan requested${r} (limit: ${e.limit??`default`}, mode: ${e.mode??`replace`}${e.hints?`, with hints`:``})`),e.minFollowUpCards!==void 0&&e.minFollowUpCards>0&&(this._minCardsGuarantee=Math.max(this._minCardsGuarantee,e.minFollowUpCards),this.log(`[Replan] Card guarantee set to ${this._minCardsGuarantee}`)),await this._executeReplan(e)}setSessionHints(e){this._sessionHints=e,this.log(`Session hints ${e?`set`:`cleared`}: ${JSON.stringify(e)}`)}getSessionHints(){return this._sessionHints}getDebugSnapshot(){let describe=e=>{let t=[];for(let n=0;n<e.length;n++){let r=e.peek(n);t.push({cardID:r.cardID,status:r.status,origin:isReview(r)?`review`:`new`,score:r.score})}return{length:e.length,dequeueCount:e.dequeueCount,cards:t}},e=this._sessionRecord.map(e=>{let t=e.records[e.records.length-1];return{cardID:e.item.cardID,status:e.item.status,attempts:e.records.length,correct:t&&isQuestionRecord(t)?t.isCorrect:null,timeSpentMs:e.records.reduce((e,t)=>e+t.timeSpent,0)}});return{sessionId:this.sessionId,secondsRemaining:this.secondsRemaining,hasCardGuarantee:this.hasCardGuarantee,minCardsGuarantee:this._minCardsGuarantee,wellIndicatedRemaining:this._wellIndicatedRemaining,currentCard:this._currentCard?.item.cardID??null,sessionHints:this._sessionHints,replanActive:this._replanPromise!==null,replanLabel:this._activeReplanLabel,supplyQ:describe(this.supplyQ),failedQ:describe(this.failedQ),reviewBacklog:getSrsBacklogDebug(),strategyPressure:getStrategyPressureDebug(),drawnCards:e}}mergeSessionHints(e){this._sessionHints=mergeHints2([this._sessionHints,e])??null,this.log(`Session hints merged: ${JSON.stringify(this._sessionHints)}`)}_applyHintsToSources(e,t){let n=e&&t?{...e,_label:t}:e,r=mergeHints2([this._sessionHints,n]);if(r)for(let e of this.sources)e.setEphemeralHints?.(r)}_getSessionControls(){return this._sessionControls||(this._sessionControls={getSessionHints:()=>this.getSessionHints(),setSessionHints:e=>this.setSessionHints(e),mergeSessionHints:e=>this.mergeSessionHints(e),requestReplan:e=>this.requestReplan(e)}),this._sessionControls}_recordEloEvent(e){this._eloLog.length>=_SessionController.MAX_LOGGED_ELO_EVENTS||this._eloLog.push(e)}async _notifyOutcomeObservers(e,t,n){if(this._outcomeObservers.length===0||!isQuestionRecord(e))return;let r={record:e,card:t.card,result:n},a=this._getSessionControls();for(let e of this._outcomeObservers)try{await e(r,a)}catch(e){this.error(`[OutcomeObserver] observer threw; ignoring`,e)}}async _replanUncoalesced(e){let t=this._runReplan(e),n=t.finally(()=>{this._replanPromise===n&&(this._replanPromise=null,this._activeReplanLabel=null)});this._replanPromise=n,await t}normalizeReplanOptions(e){if(!e)return{};let t=[`hints`,`sessionHints`,`limit`,`mode`,`label`,`minFollowUpCards`];return Object.keys(e).some(e=>t.includes(e))?e:{hints:e}}async _executeReplan(e={}){let t=e.limit,n=e.mode??`replace`,r=await this.getWeightedContent({replan:!0,additive:n===`merge`,limit:t});this._recordRuns(e.label??`(auto)`,n),this._wellIndicatedRemaining=r,t!==void 0&&t<this._defaultBatchLimit?(this._suppressQualityReplan=!0,this.log(`[Replan] Burst mode (limit=${t}): suppressing quality-based auto-replan`)):this._suppressQualityReplan=!1,r>=0&&r<_SessionController.MIN_WELL_INDICATED&&this.log(`[Replan] Only ${r}/${_SessionController.MIN_WELL_INDICATED} well-indicated cards after replan`),await this.hydrationService.ensureHydratedCards();let a=e.label?` [${e.label}]`:``;this.log(`Replan complete${a}: supplyQ now has ${this.supplyQ.length} cards (mode=${n})`),snapshotQueues(this.supplyQ.length,this.failedQ.length)}addTime(e){this.endTime=new Date(this.endTime.valueOf()+1e3*e)}get failedCount(){return this.failedQ.length}toString(){return`Session: ${this.supplyQ.length} supply, ${this.failedQ.length} failed`}reportString(){return`${this.supplyQ.dequeueCount} supply, ${this.failedQ.dequeueCount} failed`}getDebugInfo(){let e=this.sources.some(e=>typeof e.getWeightedCards==`function`),extractQueueItems=(e,t=10)=>{let n=[];for(let r=0;r<Math.min(e.length,t);r++){let t=e.peek(r);n.push({courseID:t.courseID||`unknown`,cardID:t.cardID||`unknown`,status:t.status||`unknown`,score:t.score})}return n};return{api:{mode:e?`weighted`:`legacy`,description:e?`Using getWeightedCards() API with scored candidates`:`ERROR: getWeightedCards() not a function.`},supplyQueue:{length:this.supplyQ.length,dequeueCount:this.supplyQ.dequeueCount,items:extractQueueItems(this.supplyQ)},failedQueue:{length:this.failedQ.length,dequeueCount:this.failedQ.dequeueCount,items:extractQueueItems(this.failedQ)},hydratedCache:{count:this.hydrationService.hydratedCount,cardIds:this.hydrationService.getHydratedCardIds()},replan:{inProgress:this._replanPromise!==null,suppressQualityReplan:this._suppressQualityReplan,defaultBatchLimit:this._defaultBatchLimit,minCardsGuarantee:this._minCardsGuarantee}}}async getWeightedContent(e){let t=e?.replan??!1,n=e?.additive??!1,r=e?.limit??this._defaultBatchLimit,a=r;t||this._applyHintsToSources();let o=[];for(let e=0;e<this.sources.length;e++){let n=this.sources[e];try{let t=(await n.getWeightedCards(a)).cards;o.push({sourceIndex:e,weighted:t})}catch(n){if(this.error(`Failed to get content from source ${e}:`,n),this.sources.length===1&&!t)throw Error(`Cannot start session: failed to load content from source ${e}`)}}if(o.length===0){if(t)return this.log(`Replan: no content from any source, keeping existing supplyQ`),-1;throw Error(`Cannot start session: failed to load content from all ${this.sources.length} source(s). Check logs for details.`)}let s=this.mixer.mix(o,a*this.sources.length),c=o.map(e=>e.weighted[0]?.courseId||`source-${e.sourceIndex}`);await Promise.all(c.map(async e=>{if(!this.courseNameCache.has(e))try{let t=await this.dataLayer.getCoursesDB().getCourseConfig(e);this.courseNameCache.set(e,t.name)}catch{}}));let l=c.map(e=>this.courseNameCache.get(e)),u=this.mixer instanceof QuotaRoundRobinMixer?Math.ceil(a*this.sources.length/o.length):void 0;captureMixerRun(this.mixer.constructor.name,o,c,l,a*this.sources.length,u,s);let d=s.filter(e=>!this._servedCardIds.has(e.cardId)),p=d.filter(e=>e.score===1/0),m=d.filter(e=>e.score!==1/0),g=[...p,...m.slice(0,Math.max(0,r-p.length))],_=new Set(p.map(e=>e.cardId)),v=g.filter(e=>e.score>=_SessionController.WELL_INDICATED_SCORE).length,y=t?`Replan content:
336
+ defaultBatchLimit: ${this._defaultBatchLimit}`),registerActiveController(this)}tick(){this._secondsRemaining=Math.floor((this.endTime.valueOf()-Date.now())/1e3),this._secondsRemaining<=0&&clearInterval(this._intervalHandle)}estimateCleanupTime(){let e=0;for(let t=0;t<this.failedQ.length;t++){let n=this.failedQ.peek(t),r=this._sessionRecord.find(e=>e.item.cardID===n.cardID),a=0;if(r){for(let e=0;e<r.records.length;e++)a+=r.records[e].timeSpent;a/=r.records.length,e+=a}}let t=e/1e3;return this.log(`Failed card cleanup estimate: ${Math.round(t)}`),t}async prepareSession(){if(this.sources.some(e=>typeof e.getWeightedCards!=`function`))throw Error(`[SessionController] All content sources must implement getWeightedCards().`);clearStaleSessionDebugState();let e=await this.getWeightedContent();this._recordRuns(`bootstrap`),this._wellIndicatedRemaining=e,e>=0&&e<_SessionController.MIN_WELL_INDICATED&&this.log(`[Init] Only ${e}/${_SessionController.MIN_WELL_INDICATED} well-indicated cards in initial load`),await this.hydrationService.ensureHydratedCards(),startSessionTracking(this.sessionId,this.supplyQ.length,this.failedQ.length),this._openDocPromise=this._openSessionDoc(),this._intervalHandle=setInterval(()=>{this.tick()},1e3)}_recordRuns(e,t){for(let n of drainCapturedRuns()){if(this._runLog.length>=_SessionController.MAX_LOGGED_RUNS)break;this._runLog.push({runId:n.runId,at:n.timestamp.toISOString(),label:e,...t?{mode:t}:{},generatedCount:n.generatedCount,finalCount:n.finalCount,reviewsSelected:n.reviewsSelected,newSelected:n.newSelected,...typeof n.userElo==`number`?{userElo:n.userElo}:{},...n.generators?{generators:n.generators}:{},...n.filters?{filters:n.filters}:{},...n.hints?{hints:n.hints}:{},...n.discardedTail?{discardedTail:n.discardedTail}:{},cards:persistedRunCards(n),...n.unselectedNew?{unselectedNew:persistedUnselectedNew(n.unselectedNew)}:{},...n.regulators?{regulators:n.regulators.map(persistedReading)}:{},...n.versions?{versions:n.versions}:{}})}}async _captureState(e){if(!this._stateSnapshotProvider)return;let t=3e3;try{return await Promise.race([Promise.resolve(this._stateSnapshotProvider(e)),new Promise(e=>setTimeout(()=>e(void 0),3e3))])}catch(t){this.log(`[Session] state snapshot (${e}) failed: ${t}`);return}}async _openSessionDoc(){if(this._courseId)try{let e=this.dataLayer.getUserDB(),t={_id:makeStudySessionId(this._courseId,e.getUsername(),this.sessionId),docType:`STUDY_SESSION`,sessionId:this.sessionId,courseId:this._courseId,userId:e.getUsername(),startTime:this.startTime.toISOString(),status:`open`,plannedSeconds:Math.round((this.endTime.valueOf()-this.startTime.valueOf())/1e3),config:{defaultBatchLimit:this._defaultBatchLimit,sourceCount:this.sources.length,initHints:this._sessionHints},versions:sessionVersions(),initialQueues:{supplyQ:this.supplyQ.length,failedQ:this.failedQ.length},runs:[...this._runLog],stateAtStart:await this._captureState(`start`)};this._sessionDoc=t,await e.putStudySession(t),this.log(`[Session] Opened session record ${t._id}`)}catch(e){logger.warn(`[SessionController] Failed to open session record: ${e}`)}}async requestReplan(e){let t=this.normalizeReplanOptions(e),n=this._replanHasIntent(t);if(this._replanPromise){if(!n)return this.log(`Replan already in progress, coalescing unhinted auto-replan`),this._replanPromise;let e=t.label?` [${t.label}]`:``;this.log(`Replan in progress; queueing hint-bearing replan${e} behind in-flight run`);let r=this._replanPromise.catch(()=>void 0).then(()=>this._runReplan(t)),a=r.finally(()=>{this._replanPromise===a&&(this._replanPromise=null,this._activeReplanLabel=null)});return this._replanPromise=a,r}let r=this._runReplan(t),a=r.finally(()=>{this._replanPromise===a&&(this._replanPromise=null,this._activeReplanLabel=null)});this._replanPromise=a,await r}_replanHasIntent(e){return!!(e.limit!==void 0||e.minFollowUpCards!==void 0||e.mode&&e.mode!==`replace`||e.hints&&Object.keys(e.hints).length>0||e.sessionHints!==void 0||e.mergeSessionHints!==void 0)}async _runReplan(e){this._activeReplanLabel=e.label??`(auto)`,e.hints||(e.hints={});let t=e.hints,n=new Set(t.excludeCards??[]);this._currentCard?.item.cardID&&n.add(this._currentCard.item.cardID);for(let e of this._sessionRecord)n.add(e.card.card_id);this.supplyQ.length>0&&n.add(this.supplyQ.peek(0).cardID),t.excludeCards=[...n],e.sessionHints!==void 0&&(this._sessionHints=e.sessionHints,this.log(`[Replan] Session hints ${e.sessionHints?`set`:`cleared`}: ${JSON.stringify(e.sessionHints)}`)),e.mergeSessionHints!==void 0&&(this._sessionHints=mergeHints2([this._sessionHints,e.mergeSessionHints])??null,this.log(`[Replan] Session hints merged: ${JSON.stringify(this._sessionHints)}`)),this._applyHintsToSources(e.hints,e.label);let r=e.label?` [${e.label}]`:``;this.log(`Mid-session replan requested${r} (limit: ${e.limit??`default`}, mode: ${e.mode??`replace`}${e.hints?`, with hints`:``})`),e.minFollowUpCards!==void 0&&e.minFollowUpCards>0&&(this._minCardsGuarantee=Math.max(this._minCardsGuarantee,e.minFollowUpCards),this.log(`[Replan] Card guarantee set to ${this._minCardsGuarantee}`)),await this._executeReplan(e)}setSessionHints(e){this._sessionHints=e,this.log(`Session hints ${e?`set`:`cleared`}: ${JSON.stringify(e)}`)}getSessionHints(){return this._sessionHints}getDebugSnapshot(){let describe=e=>{let t=[];for(let n=0;n<e.length;n++){let r=e.peek(n);t.push({cardID:r.cardID,status:r.status,origin:isReview(r)?`review`:`new`,score:r.score})}return{length:e.length,dequeueCount:e.dequeueCount,cards:t}},e=this._sessionRecord.map(e=>{let t=e.records[e.records.length-1];return{cardID:e.item.cardID,status:e.item.status,attempts:e.records.length,correct:t&&isQuestionRecord(t)?t.isCorrect:null,timeSpentMs:e.records.reduce((e,t)=>e+t.timeSpent,0)}});return{sessionId:this.sessionId,secondsRemaining:this.secondsRemaining,hasCardGuarantee:this.hasCardGuarantee,minCardsGuarantee:this._minCardsGuarantee,wellIndicatedRemaining:this._wellIndicatedRemaining,currentCard:this._currentCard?.item.cardID??null,sessionHints:this._sessionHints,replanActive:this._replanPromise!==null,replanLabel:this._activeReplanLabel,supplyQ:describe(this.supplyQ),failedQ:describe(this.failedQ),reviewBacklog:getSrsBacklogDebug(),strategyPressure:getStrategyPressureDebug(),drawnCards:e}}mergeSessionHints(e){this._sessionHints=mergeHints2([this._sessionHints,e])??null,this.log(`Session hints merged: ${JSON.stringify(this._sessionHints)}`)}_applyHintsToSources(e,t){let n=e&&t?{...e,_label:t}:e,r=mergeHints2([this._sessionHints,n]);if(r)for(let e of this.sources)e.setEphemeralHints?.(r)}_getSessionControls(){return this._sessionControls||(this._sessionControls={getSessionHints:()=>this.getSessionHints(),setSessionHints:e=>this.setSessionHints(e),mergeSessionHints:e=>this.mergeSessionHints(e),requestReplan:e=>this.requestReplan(e)}),this._sessionControls}_recordEloEvent(e){this._eloLog.length>=_SessionController.MAX_LOGGED_ELO_EVENTS||this._eloLog.push(e)}async _notifyOutcomeObservers(e,t,n){if(this._outcomeObservers.length===0||!isQuestionRecord(e))return;let r={record:e,card:t.card,result:n},a=this._getSessionControls();for(let e of this._outcomeObservers)try{await e(r,a)}catch(e){this.error(`[OutcomeObserver] observer threw; ignoring`,e)}}async _replanUncoalesced(e){let t=this._runReplan(e),n=t.finally(()=>{this._replanPromise===n&&(this._replanPromise=null,this._activeReplanLabel=null)});this._replanPromise=n,await t}normalizeReplanOptions(e){if(!e)return{};let t=[`hints`,`sessionHints`,`limit`,`mode`,`label`,`minFollowUpCards`];return Object.keys(e).some(e=>t.includes(e))?e:{hints:e}}async _executeReplan(e={}){let t=e.limit,n=e.mode??`replace`,r=await this.getWeightedContent({replan:!0,additive:n===`merge`,limit:t});this._recordRuns(e.label??`(auto)`,n),this._wellIndicatedRemaining=r,t!==void 0&&t<this._defaultBatchLimit?(this._suppressQualityReplan=!0,this.log(`[Replan] Burst mode (limit=${t}): suppressing quality-based auto-replan`)):this._suppressQualityReplan=!1,r>=0&&r<_SessionController.MIN_WELL_INDICATED&&this.log(`[Replan] Only ${r}/${_SessionController.MIN_WELL_INDICATED} well-indicated cards after replan`),await this.hydrationService.ensureHydratedCards();let a=e.label?` [${e.label}]`:``;this.log(`Replan complete${a}: supplyQ now has ${this.supplyQ.length} cards (mode=${n})`),snapshotQueues(this.supplyQ.length,this.failedQ.length)}addTime(e){this.endTime=new Date(this.endTime.valueOf()+1e3*e)}get failedCount(){return this.failedQ.length}toString(){return`Session: ${this.supplyQ.length} supply, ${this.failedQ.length} failed`}reportString(){return`${this.supplyQ.dequeueCount} supply, ${this.failedQ.dequeueCount} failed`}getDebugInfo(){let e=this.sources.some(e=>typeof e.getWeightedCards==`function`),extractQueueItems=(e,t=10)=>{let n=[];for(let r=0;r<Math.min(e.length,t);r++){let t=e.peek(r);n.push({courseID:t.courseID||`unknown`,cardID:t.cardID||`unknown`,status:t.status||`unknown`,score:t.score})}return n};return{api:{mode:e?`weighted`:`legacy`,description:e?`Using getWeightedCards() API with scored candidates`:`ERROR: getWeightedCards() not a function.`},supplyQueue:{length:this.supplyQ.length,dequeueCount:this.supplyQ.dequeueCount,items:extractQueueItems(this.supplyQ)},failedQueue:{length:this.failedQ.length,dequeueCount:this.failedQ.dequeueCount,items:extractQueueItems(this.failedQ)},hydratedCache:{count:this.hydrationService.hydratedCount,cardIds:this.hydrationService.getHydratedCardIds()},replan:{inProgress:this._replanPromise!==null,suppressQualityReplan:this._suppressQualityReplan,defaultBatchLimit:this._defaultBatchLimit,minCardsGuarantee:this._minCardsGuarantee}}}async getWeightedContent(e){let t=e?.replan??!1,n=e?.additive??!1,r=e?.limit??this._defaultBatchLimit,a=r;t||this._applyHintsToSources();let o=[];for(let e=0;e<this.sources.length;e++){let n=this.sources[e];try{let t=(await n.getWeightedCards(a)).cards;o.push({sourceIndex:e,weighted:t})}catch(n){if(this.error(`Failed to get content from source ${e}:`,n),this.sources.length===1&&!t)throw Error(`Cannot start session: failed to load content from source ${e}`)}}if(o.length===0){if(t)return this.log(`Replan: no content from any source, keeping existing supplyQ`),-1;throw Error(`Cannot start session: failed to load content from all ${this.sources.length} source(s). Check logs for details.`)}let s=this.mixer.mix(o,a*this.sources.length),c=o.map(e=>e.weighted[0]?.courseId||`source-${e.sourceIndex}`);await Promise.all(c.map(async e=>{if(!this.courseNameCache.has(e))try{let t=await this.dataLayer.getCoursesDB().getCourseConfig(e);this.courseNameCache.set(e,t.name)}catch{}}));let l=c.map(e=>this.courseNameCache.get(e)),u=this.mixer instanceof QuotaRoundRobinMixer?Math.ceil(a*this.sources.length/o.length):void 0;captureMixerRun(this.mixer.constructor.name,o,c,l,a*this.sources.length,u,s);let d=s.filter(e=>!this._servedCardIds.has(e.cardId)),p=d.filter(e=>e.score===1/0),m=d.filter(e=>e.score!==1/0),g=[...p,...m.slice(0,Math.max(0,r-p.length))],_=new Set(p.map(e=>e.cardId)),v=g.filter(e=>e.score>=_SessionController.WELL_INDICATED_SCORE).length,y=t?`Replan content:
336
337
  `:`Mixed content session created with:
337
338
  `,b=g.map(e=>{let t=getCardOrigin(e),n=Number.isFinite(e.score)?e.score.toFixed(2):`+INF`;return y+=`${t===`review`?`Review`:`New`}: ${e.courseId}::${e.cardId} (score: ${n})
338
339
  `,this._buildSupplyItem(e,t)});if(n){let e=this.supplyQ.mergeToFront(b,e=>e.cardID,_);y+=`Additive merge: ${e} cards added to front of supplyQ
@@ -348,7 +349,7 @@ Currently logged-in as ${this._username}.`);let n=await this.syncStrategy.create
348
349
  if (doc._id && doc._id.indexOf('card_review') === 0 && doc.courseId && doc.cardId) {
349
350
  emit(doc._id, doc.courseId + '-' + doc.cardId);
350
351
  }
351
- }`}}}]),e),userCoursesDoc=`CourseRegistrations`,userClassroomsDoc=`ClassroomRegistrations`}}),init_common=__esm({"src/impl/common/index.ts"(){init_SyncStrategy(),init_BaseUserDB(),init_userDBHelpers()}}),PouchDataLayerProvider_exports={};__export(PouchDataLayerProvider_exports,{CouchDataLayerProvider:()=>CouchDataLayerProvider});var CouchDataLayerProvider,init_PouchDataLayerProvider=__esm({"src/impl/couch/PouchDataLayerProvider.ts"(){init_logger(),init_dataDirectory(),init_adminDB2(),init_classroomDB2(),init_courseDB(),init_CourseSyncService(),init_common(),init_CouchDBSyncStrategy(),CouchDataLayerProvider=class{constructor(e){_defineProperty(this,`initialized`,!1),_defineProperty(this,`userDB`,void 0),_defineProperty(this,`currentUsername`,``),_defineProperty(this,`_courseIDs`,[]),e&&(this._courseIDs=e)}async initialize(){if(!this.initialized){if(typeof process<`u`&&process.versions!=null&&process.versions.node!=null){logger.info(`CouchDataLayerProvider: Running in Node.js environment, creating guest UserDB for testing.`),await initializeDataDirectory();let e=new CouchDBSyncStrategy;this.userDB=await BaseUser.instance(e)}else{let e=new CouchDBSyncStrategy;this.userDB=await BaseUser.instance(e),this.currentUsername=this.userDB.getUsername(),logger.debug(`Current username: ${this.currentUsername}`)}this.initialized=!0}}async teardown(){this.initialized=!1}getUserDB(){return this.userDB}getCourseDB(e){let t=CourseSyncService.getInstance().getLocalDB(e);return new CourseDB(e,async()=>this.getUserDB(),t??void 0)}async ensureCourseSynced(e,t){return CourseSyncService.getInstance().ensureSynced(e,t)}getCoursesDB(){return new CoursesDB(this._courseIDs)}async getClassroomDB(e,t){return t===`student`?await StudentClassroomDB.factory(e,this.getUserDB()):await TeacherClassroomDB.factory(e)}getAdminDB(){return new AdminDB}isReadOnly(){return!1}}}}),pathUtils,nodeFS3,StaticDataUnpacker,init_StaticDataUnpacker=__esm({"src/impl/static/StaticDataUnpacker.ts"(){init_logger(),init_core(),pathUtils={isAbsolute:e=>!!(/^[a-zA-Z]:[\\/]/.test(e)||/^\\\\/.test(e)||e.startsWith(`/`))},nodeFS3=null;try{typeof window>`u`&&typeof process<`u`&&process.versions?.node&&(nodeFS3=eval(`require`)(`fs`))}catch{}StaticDataUnpacker=class{constructor(e,t){_defineProperty(this,`manifest`,void 0),_defineProperty(this,`basePath`,void 0),_defineProperty(this,`documentCache`,new Map),_defineProperty(this,`chunkCache`,new Map),_defineProperty(this,`indexCache`,new Map),this.manifest=e,this.basePath=t}async getDocument(e){if(this.documentCache.has(e)){let t=this.documentCache.get(e);return await this.hydrateAttachments(t)}let t=await this.findChunkForDocument(e);if(!t)throw logger.error(`Document ${e} not found in any chunk. Available chunks:`,this.manifest.chunks.map(e=>`${e.id} (${e.docType}): ${e.startKey} - ${e.endKey}`)),Error(`Document ${e} not found in any chunk`);if(await this.loadChunk(t.id),this.documentCache.has(e)){let t=this.documentCache.get(e);return await this.hydrateAttachments(t)}throw logger.error(`Document ${e} not found in chunk ${t.id}`),Error(`Document ${e} not found in chunk ${t.id}`)}async getAllDocumentsByPrefix(e){let t=this.manifest.chunks.filter(t=>{let n=e+`￰`;return t.startKey<=n&&t.endKey>=e});if(t.length===0)return logger.debug(`[StaticDataUnpacker] No chunks found for prefix: ${e}`),[];await Promise.all(t.map(e=>this.loadChunk(e.id)));let n=[];for(let[t,r]of this.documentCache.entries())t.startsWith(e)&&n.push(await this.hydrateAttachments(r));return logger.debug(`[StaticDataUnpacker] Found ${n.length} documents with prefix: ${e}`),n}async queryByElo(e,t=25){let n=await this.loadIndex(`elo`);if(!n||!n.sorted)return logger.warn(`ELO index not found or malformed, returning empty results`),[];let r=n.sorted,a=0,o=0,s=r.length-1;for(;o<=s;){let t=Math.floor((o+s)/2);r[t].elo<e?o=t+1:s=t-1}a=o;let c=[],l=Math.floor(t/2);for(let e=Math.max(0,a-l);e<a&&c.length<t;e++)c.push(r[e].cardId);for(let e=a;e<r.length&&c.length<t;e++)c.push(r[e].cardId);return c}async getTagsIndex(){try{return await this.loadIndex(`tags`)}catch{return{byCard:{},byTag:{}}}}getDocTypeFromId(e){for(let t in DocTypePrefixes){let n=DocTypePrefixes[t];if(e.startsWith(`${n}-`))return t}}async findChunkForDocument(e){let t=this.getDocTypeFromId(e);if(t){let n=this.manifest.chunks.filter(e=>e.docType===t);for(let t of n)if(e>=t.startKey&&e<=t.endKey&&await this.verifyDocumentInChunk(e,t))return t}else{for(let t of this.manifest.chunks)if(e>=t.startKey&&e<=t.endKey&&await this.verifyDocumentInChunk(e,t))return t;let t=this.manifest.chunks.filter(e=>e.docType!==`CARD`&&e.docType!==`DISPLAYABLE_DATA`&&e.docType!==`TAG`);for(let n of t)if(e>=n.startKey&&e<=n.endKey&&await this.verifyDocumentInChunk(e,n))return n;return}}async verifyDocumentInChunk(e,t){try{return await this.loadChunk(t.id),this.documentCache.has(e)}catch{return!1}}async loadChunk(e){if(this.chunkCache.has(e))return;let t=this.manifest.chunks.find(t=>t.id===e);if(!t)throw Error(`Chunk ${e} not found in manifest`);try{let n=`${this.basePath}/${t.path}`;logger.debug(`Loading chunk from ${n}`);let r;if(this.isLocalPath(n)&&nodeFS3){let e=await nodeFS3.promises.readFile(n,`utf8`);r=JSON.parse(e)}else{let t=await fetch(n);if(!t.ok)throw Error(`Failed to fetch chunk ${e}: ${t.status} ${t.statusText}`);r=await t.json()}this.chunkCache.set(e,r);for(let e of r)e._id&&this.documentCache.set(e._id,e);logger.debug(`Loaded ${r.length} documents from chunk ${e}`)}catch(t){throw logger.error(`Failed to load chunk ${e}:`,t),t}}async loadIndex(e){if(this.indexCache.has(e))return this.indexCache.get(e);let t=this.manifest.indices.find(t=>t.name===e);if(!t)throw Error(`Index ${e} not found in manifest`);try{let n=`${this.basePath}/${t.path}`;logger.debug(`Loading index from ${n}`);let r;if(this.isLocalPath(n)&&nodeFS3){let e=await nodeFS3.promises.readFile(n,`utf8`);r=JSON.parse(e)}else{let t=await fetch(n);if(!t.ok)throw Error(`Failed to fetch index ${e}: ${t.status} ${t.statusText}`);r=await t.json()}return this.indexCache.set(e,r),logger.debug(`Loaded index ${e}`),r}catch(t){throw logger.error(`Failed to load index ${e}:`,t),t}}async getRawDocument(e){if(this.documentCache.has(e))return this.documentCache.get(e);let t=await this.findChunkForDocument(e);if(!t)throw logger.error(`Document ${e} not found in any chunk. Available chunks:`,this.manifest.chunks.map(e=>`${e.id} (${e.docType}): ${e.startKey} - ${e.endKey}`)),Error(`Document ${e} not found in any chunk`);if(await this.loadChunk(t.id),this.documentCache.has(e))return this.documentCache.get(e);throw logger.error(`Document ${e} not found in chunk ${t.id}`),Error(`Document ${e} not found in chunk ${t.id}`)}getAttachmentUrl(e,t){return`${this.basePath}/attachments/${e}/${t}`}async getAttachmentPath(e,t){try{let n=await this.getRawDocument(e);if(n._attachments&&n._attachments[t]){let e=n._attachments[t];if(e.path)return`${this.basePath}/${e.path}`}return null}catch{return null}}async getAttachmentBlob(e,t){let n=await this.getAttachmentPath(e,t);if(!n)return null;try{if(this.isLocalPath(n)&&nodeFS3)return await nodeFS3.promises.readFile(n);{let r=await fetch(n);if(!r.ok)throw Error(`Failed to fetch attachment ${e}/${t}: ${r.status} ${r.statusText}`);return await r.blob()}}catch(n){return logger.error(`Failed to load attachment ${e}/${t}:`,n),null}}async hydrateAttachments(e){let t=e;if(!t._attachments)return e;let n=JSON.parse(JSON.stringify(e));for(let[e,r]of Object.entries(t._attachments)){let a=r;if(a.path)try{let r=await this.getAttachmentBlob(t._id,e);r?typeof window<`u`&&window.URL?n._attachments[e]={...a,data:r,stub:!1}:n._attachments[e]={...a,buffer:r}:logger.warn(`[hydrateAttachments] getAttachmentBlob returned null for ${t._id}/${e}. Skipping hydration for this attachment.`)}catch(n){logger.warn(`[hydrateAttachments] Failed to hydrate attachment ${t._id}/${e}:`,n)}else logger.debug(`[hydrateAttachments] Attachment ${e} for doc ${t._id} has no path. Skipping blob conversion.`)}return n}clearCaches(){this.documentCache.clear(),this.chunkCache.clear(),this.indexCache.clear()}getCacheStats(){return{documents:this.documentCache.size,chunks:this.chunkCache.size,indices:this.indexCache.size}}isLocalPath(e){return!e.startsWith(`http://`)&&!e.startsWith(`https://`)&&(pathUtils.isAbsolute(e)||e.startsWith(`./`)||e.startsWith(`../`))}}}}),StaticCourseDB,init_courseDB2=__esm({"src/impl/static/courseDB.ts"(){init_types_legacy(),init_logger(),init_defaults(),init_PipelineAssembler(),StaticCourseDB=class{constructor(e,t,n,r){_defineProperty(this,`_pendingHints`,null),this.courseId=e,this.unpacker=t,this.userDB=n,this.manifest=r}getCourseID(){return this.courseId}async getCourseConfig(){if(this.manifest.courseConfig!=null)return this.manifest.courseConfig;throw Error(`Course config not found for course ${this.courseId}`)}async updateCourseConfig(e){throw Error(`Cannot update course config in static mode`)}async getCourseInfo(){return{cardCount:this.manifest.chunks.filter(e=>e.docType===`CARD`).reduce((e,t)=>e+t.documentCount,0),registeredUsers:0}}async getCourseDoc(e,t){return this.unpacker.getDocument(e)}async getCourseDocs(e,t){let n=await Promise.all(e.map(async e=>{try{return{id:e,key:e,value:{rev:`1-static`},doc:await this.unpacker.getDocument(e)}}catch{return{key:e,error:`not_found`}}}));return{total_rows:e.length,offset:0,rows:n}}async getCardsByELO(e,t){return(await this.unpacker.queryByElo(e,t||25)).map(e=>{let[t,n,r]=e.split(`-`);return{courseID:t,cardID:n,elo:r?parseInt(r):void 0}})}async getCardEloData(e){return await Promise.all(e.map(async e=>{try{return(await this.unpacker.getDocument(e)).elo||{global:{score:1e3,count:0},tags:{},misc:{}}}catch{return{global:{score:1e3,count:0},tags:{},misc:{}}}}))}async updateCardElo(e,t){return{ok:!0,id:e,rev:`1-static`}}async getCardsCenteredAtELO(e,t){let n=typeof e.elo==`number`?e.elo:1e3;if(e.elo===`user`)try{let e=(await this.userDB.getCourseRegistrationsDoc()).courses.find(e=>e.courseID===this.courseId);e&&typeof e.elo==`object`&&(n=e.elo.global.score)}catch{n=1e3}else e.elo===`random`&&(n=800+Math.random()*400);let r=(await this.unpacker.queryByElo(n,e.limit*2)).map(e=>({cardID:e,courseID:this.courseId}));return t&&(r=r.filter(t)),r.slice(0,e.limit).map(e=>({status:`new`,cardID:e.cardID,contentSourceType:`course`,contentSourceID:this.courseId,courseID:this.courseId}))}async getAppliedTags(e){try{let t=await this.unpacker.getTagsIndex(),n=t.byCard[e]||[],r=await Promise.all(n.map(async n=>{let r=`TAG-${n}`;try{let t=await this.unpacker.getDocument(r);return{id:r,key:e,value:{name:t.name,snippet:t.snippet,count:t.taggedCards?.length||0}}}catch(a){if(a&&a.status===404)logger.warn(`Tag document not found for ${n}, creating stub`);else throw logger.error(`Error getting tag document for ${n}:`,a),a;return{id:r,key:e,value:{name:n,snippet:`Tag: ${n}`,count:t.byTag[n]?.length||0}}}}));return{total_rows:r.length,offset:0,rows:r}}catch(t){return logger.error(`Error getting applied tags for card ${e}:`,t),{total_rows:0,offset:0,rows:[]}}}async getAppliedTagsBatch(e){let t=await this.unpacker.getTagsIndex(),n=new Map;for(let r of e)n.set(r,t.byCard[r]||[]);return n}async getAllCardIds(){let e=await this.unpacker.getTagsIndex();return Object.keys(e.byCard)}async addTagToCard(e,t){throw Error(`Cannot modify tags in static mode`)}async removeTagFromCard(e,t){throw Error(`Cannot modify tags in static mode`)}async createTag(e){throw Error(`Cannot create tags in static mode`)}async getTag(e){return this.unpacker.getDocument(`TAG-${e}`)}async updateTag(e){throw Error(`Cannot update tags in static mode`)}async getCourseTagStubs(){try{let e=await this.unpacker.getTagsIndex();if(!e||!e.byTag)return logger.warn(`Tags index not found or empty`),{total_rows:0,offset:0,rows:[]};let t=Object.keys(e.byTag),n=await Promise.all(t.map(async t=>{let n=e.byTag[t]||[],r=`TAG-${t}`;try{return{id:r,key:r,value:{rev:`1-static`},doc:await this.unpacker.getDocument(r)}}catch(e){if(e&&e.status===404)return logger.warn(`Tag document not found for ${t}, creating stub`),{id:r,key:r,value:{rev:`1-static`},doc:{_id:r,_rev:`1-static`,course:this.courseId,docType:`TAG`,name:t,snippet:`Tag: ${t}`,wiki:``,taggedCards:n,author:`system`}};throw logger.error(`Error getting tag document for ${t}:`,e),e}}));return{total_rows:n.length,offset:0,rows:n}}catch(e){return logger.error(`Failed to get course tag stubs:`,e),{total_rows:0,offset:0,rows:[]}}}async addNote(e,t,n,r,a,o,s){return{status:Status.error,message:`Cannot add notes in static mode`}}async removeCard(e){throw Error(`Cannot remove cards in static mode`)}async getInexperiencedCards(){return[]}async getNavigationStrategy(e){try{return await this.unpacker.getDocument(e)}catch(t){throw logger.error(`[static/courseDB] Strategy ${e} not found: ${t}`),t}}async getAllNavigationStrategies(){let e=DocTypePrefixes.NAVIGATION_STRATEGY;try{return await this.unpacker.getAllDocumentsByPrefix(e)}catch(e){return logger.warn(`[static/courseDB] Error loading navigation strategies: ${e}`),[]}}async addNavigationStrategy(e){throw Error(`Cannot add navigation strategies in static mode`)}async updateNavigationStrategy(e,t){throw Error(`Cannot update navigation strategies in static mode`)}async createNavigator(e){try{let t=await this.getAllNavigationStrategies();if(t.length===0)return logger.debug(`[static/courseDB] No strategy documents found, using default Pipeline(Composite(ELO, SRS), [eloDistanceFilter])`),createDefaultPipeline(e,this);let{pipeline:n,generatorStrategies:r,filterStrategies:a,warnings:o}=await new PipelineAssembler().assemble({strategies:t,user:e,course:this});for(let e of o)logger.warn(`[PipelineAssembler] ${e}`);return n?(logger.debug(`[static/courseDB] Using assembled pipeline with ${r.length} generator(s) and ${a.length} filter(s)`),n):(logger.debug(`[static/courseDB] Pipeline assembly failed, using default pipeline`),createDefaultPipeline(e,this))}catch(e){throw logger.error(`[static/courseDB] Error creating navigator: ${e}`),e}}setEphemeralHints(e){this._pendingHints=e}notePresented(e){e.status===`new`&&this.createNavigator(this.userDB).then(t=>t.notePresented?.(e)).catch(e=>logger.warn(`[static/courseDB] Could not note a presentation: ${e}`))}async getWeightedCards(e){try{let t=await this.createNavigator(this.userDB);return this._pendingHints&&(t.setEphemeralHints(this._pendingHints),this._pendingHints=null),t.getWeightedCards(e)}catch(e){throw logger.error(`[static/courseDB] Error getting weighted cards: ${e}`),e}}getAttachmentUrl(e,t){return this.unpacker.getAttachmentUrl(e,t)}async getAttachmentBlob(e,t){return this.unpacker.getAttachmentBlob(e,t)}async searchCards(e){return[]}async find(e){return{docs:[],warning:`Find operations not supported in static mode`}}}}}),StaticCoursesDB,init_coursesDB=__esm({"src/impl/static/coursesDB.ts"(){init_logger(),StaticCoursesDB=class{constructor(e,t){this.manifests=e,this.dependencyNameToCourseId=t}async getCourseConfig(e){let t=this.manifests[e];if(!t&&this.dependencyNameToCourseId){let n=this.dependencyNameToCourseId.get(e);n&&(t=this.manifests[n])}if(!t)throw logger.warn(`Course manifest for ${e} not found`),Error(`Course ${e} not found`);if(t.courseConfig)return t.courseConfig;throw logger.warn(`Course config not found in manifest for course ${e}`),Error(`Course config not found for course ${e}`)}async getCourseList(){return Object.keys(this.manifests).map(e=>({courseID:e,name:this.manifests[e].courseName}))}async disambiguateCourse(e,t){logger.warn(`Cannot disambiguate courses in static mode`)}}}}),NoOpSyncStrategy,init_NoOpSyncStrategy=__esm({"src/impl/static/NoOpSyncStrategy.ts"(){init_common(),NoOpSyncStrategy=class{constructor(){_defineProperty(this,`currentUsername`,accomodateGuest().username)}setupRemoteDB(e){return getLocalUserDB(e)}getWriteDB(e){return getLocalUserDB(e)}startSync(e,t){}stopSync(){}canCreateAccount(){return!1}canAuthenticate(){return!1}async createAccount(e,t){throw Error(`Account creation not supported in static mode. Use local account switching instead.`)}async authenticate(e,t){throw Error(`Remote authentication not supported in static mode. Use local account switching instead.`)}async logout(){return this.currentUsername=accomodateGuest().username,{ok:!0}}async getCurrentUsername(){return this.currentUsername}setCurrentUsername(e){this.currentUsername=e}}}}),StaticDataLayerProvider_exports={};__export(StaticDataLayerProvider_exports,{StaticDataLayerProvider:()=>StaticDataLayerProvider});var StaticDataLayerProvider,init_StaticDataLayerProvider=__esm({"src/impl/static/StaticDataLayerProvider.ts"(){init_logger(),init_StaticDataUnpacker(),init_courseDB2(),init_coursesDB(),init_common(),init_NoOpSyncStrategy(),StaticDataLayerProvider=class{constructor(e){_defineProperty(this,`config`,void 0),_defineProperty(this,`initialized`,!1),_defineProperty(this,`courseUnpackers`,new Map),_defineProperty(this,`manifests`,{}),_defineProperty(this,`dependencyNameToCourseId`,new Map),this.config={localStoragePrefix:e.localStoragePrefix||`skuilder-static`,rootManifest:e.rootManifest||{dependencies:{}},rootManifestUrl:e.rootManifestUrl||`/`}}async resolveCourseDependencies(){logger.info(`[StaticDataLayerProvider] Starting course dependency resolution...`);let e=this.config.rootManifest;for(let[t,n]of Object.entries(e.dependencies||{}))try{logger.debug(`[StaticDataLayerProvider] Resolving dependency: ${t} from ${n}`);let e=new URL(n,this.config.rootManifestUrl).href,r=await fetch(e);if(!r.ok)throw Error(`Failed to fetch course manifest for ${t}`);let a=await r.json();if(a.content&&a.content.manifest){let n=new URL(`.`,e).href,r=new URL(a.content.manifest,e).href,o=await fetch(r);if(!o.ok)throw Error(`Failed to fetch final content manifest for ${t} at ${r}`);let s=await o.json(),c=s.courseId||s.courseConfig?.courseID;if(!c)throw Error(`Course manifest for ${t} missing courseId`);this.manifests[c]=s;let l=new StaticDataUnpacker(s,n);this.courseUnpackers.set(c,l),this.dependencyNameToCourseId.set(t,c),logger.info(`[StaticDataLayerProvider] Successfully resolved and prepared course: ${t} (courseId: ${c})`)}}catch(e){logger.error(`[StaticDataLayerProvider] Failed to resolve dependency ${t}:`,e)}logger.info(`[StaticDataLayerProvider] Course dependency resolution complete.`)}async initialize(){this.initialized||(logger.info(`Initializing static data layer provider`),await this.resolveCourseDependencies(),this.initialized=!0)}async teardown(){this.courseUnpackers.clear(),this.initialized=!1}getUserDB(){let e=new NoOpSyncStrategy;return BaseUser.Dummy(e)}getCourseDB(e){let t=this.courseUnpackers.get(e),n=e;if(!t){let r=this.dependencyNameToCourseId.get(e);r&&(t=this.courseUnpackers.get(r),n=r)}if(!t)throw Error(`Course ${e} not found or failed to initialize in static data layer.`);let r=this.manifests[n];return new StaticCourseDB(n,t,this.getUserDB(),r)}getCoursesDB(){return new StaticCoursesDB(this.manifests,this.dependencyNameToCourseId)}async getClassroomDB(e,t){throw Error(`Classrooms not supported in static mode`)}getAdminDB(){throw Error(`Admin functions not supported in static mode`)}isReadOnly(){return!0}}}});async function initializeDataLayer(e){if(dataLayerInstance)return logger.warn(`Data layer already initialized. Returning existing instance.`),dataLayerInstance;if(await initializeNavigatorRegistry(),e.options.localStoragePrefix&&(ENV.LOCAL_STORAGE_PREFIX=e.options.localStoragePrefix),e.type===`couch`){if(!e.options.COUCHDB_SERVER_URL||!e.options.COUCHDB_SERVER_PROTOCOL)throw Error(`Missing CouchDB server URL or protocol`);if(ENV.COUCHDB_SERVER_PROTOCOL=e.options.COUCHDB_SERVER_PROTOCOL,ENV.COUCHDB_SERVER_URL=e.options.COUCHDB_SERVER_URL,ENV.COUCHDB_USERNAME=e.options.COUCHDB_USERNAME,ENV.COUCHDB_PASSWORD=e.options.COUCHDB_PASSWORD,e.options.courseSync){let{CourseSyncService:t}=await Promise.resolve().then(()=>(init_CourseSyncService(),CourseSyncService_exports));t.getInstance().configure(e.options.courseSync)}if(e.options.COUCHDB_PASSWORD&&e.options.COUCHDB_USERNAME&&typeof window<`u`){let{CouchDBSyncStrategy:t}=await Promise.resolve().then(()=>(init_CouchDBSyncStrategy(),CouchDBSyncStrategy_exports)),n=new t,r=await(await BaseUser.instance(n,e.options.COUCHDB_USERNAME)).login(e.options.COUCHDB_USERNAME,e.options.COUCHDB_PASSWORD);r.ok?logger.info(`Successfully authenticated as ${e.options.COUCHDB_USERNAME}`):logger.warn(`Authentication failed: ${r.error}`)}let{CouchDataLayerProvider:t}=await Promise.resolve().then(()=>(init_PouchDataLayerProvider(),PouchDataLayerProvider_exports));dataLayerInstance=new t(e.options.COURSE_IDS)}else if(e.type===`static`){let{StaticDataLayerProvider:t}=await Promise.resolve().then(()=>(init_StaticDataLayerProvider(),StaticDataLayerProvider_exports));dataLayerInstance=new t(e.options)}else throw Error(`Unknown data layer type: ${e.type}`);return await dataLayerInstance.initialize(),dataLayerInstance}function getDataLayer(){if(!dataLayerInstance)throw Error(`Data layer not initialized. Call initializeDataLayer first.`);return dataLayerInstance}async function _resetDataLayer(){dataLayerInstance&&await dataLayerInstance.teardown(),dataLayerInstance=null}var NOT_SET,ENV,dataLayerInstance,init_factory=__esm({"src/factory.ts"(){init_common(),init_logger(),init_navigators(),NOT_SET=`NOT_SET`,ENV={COUCHDB_SERVER_PROTOCOL:NOT_SET,COUCHDB_SERVER_URL:NOT_SET,LOCAL_STORAGE_PREFIX:``},dataLayerInstance=null}});function isReview(e){return e.status===`review`||e.status===`failed-review`||`reviewID`in e}async function getStudySource(e,t){return e.type===`classroom`?await StudentClassroomDB.factory(e.id,t):hasActiveFilter(e.tagFilter)?new TagFilteredContentSource(e.id,e.tagFilter,t):getDataLayer().getCourseDB(e.id)}var init_contentSource=__esm({"src/core/interfaces/contentSource.ts"(){init_factory(),init_classroomDB2(),init_TagFilteredContentSource()}}),init_courseDB3=__esm({"src/core/interfaces/courseDB.ts"(){}}),init_dataLayerProvider=__esm({"src/core/interfaces/dataLayerProvider.ts"(){}}),init_userDB=__esm({"src/core/interfaces/userDB.ts"(){}}),init_interfaces=__esm({"src/core/interfaces/index.ts"(){init_adminDB(),init_classroomDB(),init_contentSource(),init_courseDB3(),init_dataLayerProvider(),init_userDB()}}),init_user=__esm({"src/core/types/user.ts"(){}});function buildStrategyStateId(e,t){return`STRATEGY_STATE::${e}::${t}`}var init_strategyState=__esm({"src/core/types/strategyState.ts"(){}}),init_userOutcome=__esm({"src/core/types/userOutcome.ts"(){}}),HYDRATION_MARKER_ID,init_hydration=__esm({"src/core/types/hydration.ts"(){HYDRATION_MARKER_ID=`_local/hydration`}});async function importParsedCards(e,t,n){let r=[];for(let a of e)try{let e=await processCard(a,t,n);r.push(e)}catch(e){logger.error(`Error processing card:`,e);let t=a.markdown;a.tags&&a.tags.length>0&&(t+=`
352
+ }`}}}]),e),userCoursesDoc=`CourseRegistrations`,userClassroomsDoc=`ClassroomRegistrations`}}),init_common=__esm({"src/impl/common/index.ts"(){init_SyncStrategy(),init_BaseUserDB(),init_userDBHelpers()}}),PouchDataLayerProvider_exports={};__export(PouchDataLayerProvider_exports,{CouchDataLayerProvider:()=>CouchDataLayerProvider});var CouchDataLayerProvider,init_PouchDataLayerProvider=__esm({"src/impl/couch/PouchDataLayerProvider.ts"(){init_logger(),init_dataDirectory(),init_adminDB2(),init_classroomDB2(),init_courseDB(),init_CourseSyncService(),init_common(),init_CouchDBSyncStrategy(),CouchDataLayerProvider=class{constructor(e){_defineProperty(this,`initialized`,!1),_defineProperty(this,`userDB`,void 0),_defineProperty(this,`currentUsername`,``),_defineProperty(this,`_courseIDs`,[]),e&&(this._courseIDs=e)}async initialize(){if(!this.initialized){if(typeof process<`u`&&process.versions!=null&&process.versions.node!=null){logger.info(`CouchDataLayerProvider: Running in Node.js environment, creating guest UserDB for testing.`),await initializeDataDirectory();let e=new CouchDBSyncStrategy;this.userDB=await BaseUser.instance(e)}else{let e=new CouchDBSyncStrategy;this.userDB=await BaseUser.instance(e),this.currentUsername=this.userDB.getUsername(),logger.debug(`Current username: ${this.currentUsername}`)}this.initialized=!0}}async teardown(){this.initialized=!1}getUserDB(){return this.userDB}getCourseDB(e){let t=CourseSyncService.getInstance().getLocalDB(e);return new CourseDB(e,async()=>this.getUserDB(),t??void 0)}async ensureCourseSynced(e,t){return CourseSyncService.getInstance().ensureSynced(e,t)}getCoursesDB(){return new CoursesDB(this._courseIDs)}async getClassroomDB(e,t){return t===`student`?await StudentClassroomDB.factory(e,this.getUserDB()):await TeacherClassroomDB.factory(e)}getAdminDB(){return new AdminDB}isReadOnly(){return!1}}}}),pathUtils,nodeFS3,StaticDataUnpacker,init_StaticDataUnpacker=__esm({"src/impl/static/StaticDataUnpacker.ts"(){init_logger(),init_core(),pathUtils={isAbsolute:e=>!!(/^[a-zA-Z]:[\\/]/.test(e)||/^\\\\/.test(e)||e.startsWith(`/`))},nodeFS3=null;try{typeof window>`u`&&typeof process<`u`&&process.versions?.node&&(nodeFS3=eval(`require`)(`fs`))}catch{}StaticDataUnpacker=class{constructor(e,t){_defineProperty(this,`manifest`,void 0),_defineProperty(this,`basePath`,void 0),_defineProperty(this,`documentCache`,new Map),_defineProperty(this,`chunkCache`,new Map),_defineProperty(this,`indexCache`,new Map),this.manifest=e,this.basePath=t}async getDocument(e){if(this.documentCache.has(e)){let t=this.documentCache.get(e);return await this.hydrateAttachments(t)}let t=await this.findChunkForDocument(e);if(!t)throw logger.error(`Document ${e} not found in any chunk. Available chunks:`,this.manifest.chunks.map(e=>`${e.id} (${e.docType}): ${e.startKey} - ${e.endKey}`)),Error(`Document ${e} not found in any chunk`);if(await this.loadChunk(t.id),this.documentCache.has(e)){let t=this.documentCache.get(e);return await this.hydrateAttachments(t)}throw logger.error(`Document ${e} not found in chunk ${t.id}`),Error(`Document ${e} not found in chunk ${t.id}`)}async getAllDocumentsByPrefix(e){let t=this.manifest.chunks.filter(t=>{let n=e+`￰`;return t.startKey<=n&&t.endKey>=e});if(t.length===0)return logger.debug(`[StaticDataUnpacker] No chunks found for prefix: ${e}`),[];await Promise.all(t.map(e=>this.loadChunk(e.id)));let n=[];for(let[t,r]of this.documentCache.entries())t.startsWith(e)&&n.push(await this.hydrateAttachments(r));return logger.debug(`[StaticDataUnpacker] Found ${n.length} documents with prefix: ${e}`),n}async queryByElo(e,t=25){let n=await this.loadIndex(`elo`);if(!n||!n.sorted)return logger.warn(`ELO index not found or malformed, returning empty results`),[];let r=n.sorted,a=0,o=0,s=r.length-1;for(;o<=s;){let t=Math.floor((o+s)/2);r[t].elo<e?o=t+1:s=t-1}a=o;let c=[],l=Math.floor(t/2);for(let e=Math.max(0,a-l);e<a&&c.length<t;e++)c.push(r[e].cardId);for(let e=a;e<r.length&&c.length<t;e++)c.push(r[e].cardId);return c}async getTagsIndex(){try{return await this.loadIndex(`tags`)}catch{return{byCard:{},byTag:{}}}}getDocTypeFromId(e){for(let t in DocTypePrefixes){let n=DocTypePrefixes[t];if(e.startsWith(`${n}-`))return t}}async findChunkForDocument(e){let t=this.getDocTypeFromId(e);if(t){let n=this.manifest.chunks.filter(e=>e.docType===t);for(let t of n)if(e>=t.startKey&&e<=t.endKey&&await this.verifyDocumentInChunk(e,t))return t}else{for(let t of this.manifest.chunks)if(e>=t.startKey&&e<=t.endKey&&await this.verifyDocumentInChunk(e,t))return t;let t=this.manifest.chunks.filter(e=>e.docType!==`CARD`&&e.docType!==`DISPLAYABLE_DATA`&&e.docType!==`TAG`);for(let n of t)if(e>=n.startKey&&e<=n.endKey&&await this.verifyDocumentInChunk(e,n))return n;return}}async verifyDocumentInChunk(e,t){try{return await this.loadChunk(t.id),this.documentCache.has(e)}catch{return!1}}async loadChunk(e){if(this.chunkCache.has(e))return;let t=this.manifest.chunks.find(t=>t.id===e);if(!t)throw Error(`Chunk ${e} not found in manifest`);try{let n=`${this.basePath}/${t.path}`;logger.debug(`Loading chunk from ${n}`);let r;if(this.isLocalPath(n)&&nodeFS3){let e=await nodeFS3.promises.readFile(n,`utf8`);r=JSON.parse(e)}else{let t=await fetch(n);if(!t.ok)throw Error(`Failed to fetch chunk ${e}: ${t.status} ${t.statusText}`);r=await t.json()}this.chunkCache.set(e,r);for(let e of r)e._id&&this.documentCache.set(e._id,e);logger.debug(`Loaded ${r.length} documents from chunk ${e}`)}catch(t){throw logger.error(`Failed to load chunk ${e}:`,t),t}}async loadIndex(e){if(this.indexCache.has(e))return this.indexCache.get(e);let t=this.manifest.indices.find(t=>t.name===e);if(!t)throw Error(`Index ${e} not found in manifest`);try{let n=`${this.basePath}/${t.path}`;logger.debug(`Loading index from ${n}`);let r;if(this.isLocalPath(n)&&nodeFS3){let e=await nodeFS3.promises.readFile(n,`utf8`);r=JSON.parse(e)}else{let t=await fetch(n);if(!t.ok)throw Error(`Failed to fetch index ${e}: ${t.status} ${t.statusText}`);r=await t.json()}return this.indexCache.set(e,r),logger.debug(`Loaded index ${e}`),r}catch(t){throw logger.error(`Failed to load index ${e}:`,t),t}}async getRawDocument(e){if(this.documentCache.has(e))return this.documentCache.get(e);let t=await this.findChunkForDocument(e);if(!t)throw logger.error(`Document ${e} not found in any chunk. Available chunks:`,this.manifest.chunks.map(e=>`${e.id} (${e.docType}): ${e.startKey} - ${e.endKey}`)),Error(`Document ${e} not found in any chunk`);if(await this.loadChunk(t.id),this.documentCache.has(e))return this.documentCache.get(e);throw logger.error(`Document ${e} not found in chunk ${t.id}`),Error(`Document ${e} not found in chunk ${t.id}`)}getAttachmentUrl(e,t){return`${this.basePath}/attachments/${e}/${t}`}async getAttachmentPath(e,t){try{let n=await this.getRawDocument(e);if(n._attachments&&n._attachments[t]){let e=n._attachments[t];if(e.path)return`${this.basePath}/${e.path}`}return null}catch{return null}}async getAttachmentBlob(e,t){let n=await this.getAttachmentPath(e,t);if(!n)return null;try{if(this.isLocalPath(n)&&nodeFS3)return await nodeFS3.promises.readFile(n);{let r=await fetch(n);if(!r.ok)throw Error(`Failed to fetch attachment ${e}/${t}: ${r.status} ${r.statusText}`);return await r.blob()}}catch(n){return logger.error(`Failed to load attachment ${e}/${t}:`,n),null}}async hydrateAttachments(e){let t=e;if(!t._attachments)return e;let n=JSON.parse(JSON.stringify(e));for(let[e,r]of Object.entries(t._attachments)){let a=r;if(a.path)try{let r=await this.getAttachmentBlob(t._id,e);r?typeof window<`u`&&window.URL?n._attachments[e]={...a,data:r,stub:!1}:n._attachments[e]={...a,buffer:r}:logger.warn(`[hydrateAttachments] getAttachmentBlob returned null for ${t._id}/${e}. Skipping hydration for this attachment.`)}catch(n){logger.warn(`[hydrateAttachments] Failed to hydrate attachment ${t._id}/${e}:`,n)}else logger.debug(`[hydrateAttachments] Attachment ${e} for doc ${t._id} has no path. Skipping blob conversion.`)}return n}clearCaches(){this.documentCache.clear(),this.chunkCache.clear(),this.indexCache.clear()}getCacheStats(){return{documents:this.documentCache.size,chunks:this.chunkCache.size,indices:this.indexCache.size}}isLocalPath(e){return!e.startsWith(`http://`)&&!e.startsWith(`https://`)&&(pathUtils.isAbsolute(e)||e.startsWith(`./`)||e.startsWith(`../`))}}}}),StaticCourseDB,init_courseDB2=__esm({"src/impl/static/courseDB.ts"(){init_types_legacy(),init_logger(),init_defaults(),init_PipelineAssembler(),StaticCourseDB=class{constructor(e,t,n,r){_defineProperty(this,`_pendingHints`,null),this.courseId=e,this.unpacker=t,this.userDB=n,this.manifest=r}getCourseID(){return this.courseId}async getCourseConfig(){if(this.manifest.courseConfig!=null)return this.manifest.courseConfig;throw Error(`Course config not found for course ${this.courseId}`)}async updateCourseConfig(e){throw Error(`Cannot update course config in static mode`)}async getCourseInfo(){return{cardCount:this.manifest.chunks.filter(e=>e.docType===`CARD`).reduce((e,t)=>e+t.documentCount,0),registeredUsers:0}}async getCourseDoc(e,t){return this.unpacker.getDocument(e)}async getCourseDocs(e,t){let n=await Promise.all(e.map(async e=>{try{return{id:e,key:e,value:{rev:`1-static`},doc:await this.unpacker.getDocument(e)}}catch{return{key:e,error:`not_found`}}}));return{total_rows:e.length,offset:0,rows:n}}async getCardsByELO(e,t){return(await this.unpacker.queryByElo(e,t||25)).map(e=>{let[t,n,r]=e.split(`-`);return{courseID:t,cardID:n,elo:r?parseInt(r):void 0}})}async getCardEloData(e){return await Promise.all(e.map(async e=>{try{return(await this.unpacker.getDocument(e)).elo||{global:{score:1e3,count:0},tags:{},misc:{}}}catch{return{global:{score:1e3,count:0},tags:{},misc:{}}}}))}async updateCardElo(e,t){return{ok:!0,id:e,rev:`1-static`}}async getCardsCenteredAtELO(e,t){let n=typeof e.elo==`number`?e.elo:1e3;if(e.elo===`user`)try{let e=(await this.userDB.getCourseRegistrationsDoc()).courses.find(e=>e.courseID===this.courseId);e&&typeof e.elo==`object`&&(n=e.elo.global.score)}catch{n=1e3}else e.elo===`random`&&(n=800+Math.random()*400);let r=(await this.unpacker.queryByElo(n,e.limit*2)).map(e=>({cardID:e,courseID:this.courseId}));return t&&(r=r.filter(t)),r.slice(0,e.limit).map(e=>({status:`new`,cardID:e.cardID,contentSourceType:`course`,contentSourceID:this.courseId,courseID:this.courseId}))}async getAppliedTags(e){try{let t=await this.unpacker.getTagsIndex(),n=t.byCard[e]||[],r=await Promise.all(n.map(async n=>{let r=`TAG-${n}`;try{let t=await this.unpacker.getDocument(r);return{id:r,key:e,value:{name:t.name,snippet:t.snippet,count:t.taggedCards?.length||0}}}catch(a){if(a&&a.status===404)logger.warn(`Tag document not found for ${n}, creating stub`);else throw logger.error(`Error getting tag document for ${n}:`,a),a;return{id:r,key:e,value:{name:n,snippet:`Tag: ${n}`,count:t.byTag[n]?.length||0}}}}));return{total_rows:r.length,offset:0,rows:r}}catch(t){return logger.error(`Error getting applied tags for card ${e}:`,t),{total_rows:0,offset:0,rows:[]}}}async getAppliedTagsBatch(e){let t=await this.unpacker.getTagsIndex(),n=new Map;for(let r of e)n.set(r,t.byCard[r]||[]);return n}async getAllCardIds(){let e=await this.unpacker.getTagsIndex();return Object.keys(e.byCard)}async addTagToCard(e,t){throw Error(`Cannot modify tags in static mode`)}async removeTagFromCard(e,t){throw Error(`Cannot modify tags in static mode`)}async createTag(e){throw Error(`Cannot create tags in static mode`)}async getTag(e){return this.unpacker.getDocument(`TAG-${e}`)}async updateTag(e){throw Error(`Cannot update tags in static mode`)}async getCourseTagStubs(){try{let e=await this.unpacker.getTagsIndex();if(!e||!e.byTag)return logger.warn(`Tags index not found or empty`),{total_rows:0,offset:0,rows:[]};let t=Object.keys(e.byTag),n=await Promise.all(t.map(async t=>{let n=e.byTag[t]||[],r=`TAG-${t}`;try{return{id:r,key:r,value:{rev:`1-static`},doc:await this.unpacker.getDocument(r)}}catch(e){if(e&&e.status===404)return logger.warn(`Tag document not found for ${t}, creating stub`),{id:r,key:r,value:{rev:`1-static`},doc:{_id:r,_rev:`1-static`,course:this.courseId,docType:`TAG`,name:t,snippet:`Tag: ${t}`,wiki:``,taggedCards:n,author:`system`}};throw logger.error(`Error getting tag document for ${t}:`,e),e}}));return{total_rows:n.length,offset:0,rows:n}}catch(e){return logger.error(`Failed to get course tag stubs:`,e),{total_rows:0,offset:0,rows:[]}}}async addNote(e,t,n,r,a,o,s){return{status:Status.error,message:`Cannot add notes in static mode`}}async removeCard(e){throw Error(`Cannot remove cards in static mode`)}async getInexperiencedCards(){return[]}async getNavigationStrategy(e){try{return await this.unpacker.getDocument(e)}catch(t){throw logger.error(`[static/courseDB] Strategy ${e} not found: ${t}`),t}}async getAllNavigationStrategies(){let e=DocTypePrefixes.NAVIGATION_STRATEGY;try{return await this.unpacker.getAllDocumentsByPrefix(e)}catch(e){return logger.warn(`[static/courseDB] Error loading navigation strategies: ${e}`),[]}}async addNavigationStrategy(e){throw Error(`Cannot add navigation strategies in static mode`)}async updateNavigationStrategy(e,t){throw Error(`Cannot update navigation strategies in static mode`)}async createNavigator(e){try{let t=await this.getAllNavigationStrategies();if(t.length===0)return logger.debug(`[static/courseDB] No strategy documents found, using default Pipeline(Composite(ELO, SRS), [eloDistanceFilter])`),createDefaultPipeline(e,this);let{pipeline:n,generatorStrategies:r,filterStrategies:a,warnings:o}=await new PipelineAssembler().assemble({strategies:t,user:e,course:this});for(let e of o)logger.warn(`[PipelineAssembler] ${e}`);return n?(logger.debug(`[static/courseDB] Using assembled pipeline with ${r.length} generator(s) and ${a.length} filter(s)`),n):(logger.debug(`[static/courseDB] Pipeline assembly failed, using default pipeline`),createDefaultPipeline(e,this))}catch(e){throw logger.error(`[static/courseDB] Error creating navigator: ${e}`),e}}setEphemeralHints(e){this._pendingHints=e}notePresented(e){e.status===`new`&&this.createNavigator(this.userDB).then(t=>t.notePresented?.(e)).catch(e=>logger.warn(`[static/courseDB] Could not note a presentation: ${e}`))}async getWeightedCards(e){try{let t=await this.createNavigator(this.userDB);return this._pendingHints&&(t.setEphemeralHints(this._pendingHints),this._pendingHints=null),t.getWeightedCards(e)}catch(e){throw logger.error(`[static/courseDB] Error getting weighted cards: ${e}`),e}}getAttachmentUrl(e,t){return this.unpacker.getAttachmentUrl(e,t)}async getAttachmentBlob(e,t){return this.unpacker.getAttachmentBlob(e,t)}async searchCards(e){return[]}async find(e){return{docs:[],warning:`Find operations not supported in static mode`}}}}}),StaticCoursesDB,init_coursesDB=__esm({"src/impl/static/coursesDB.ts"(){init_logger(),StaticCoursesDB=class{constructor(e,t){this.manifests=e,this.dependencyNameToCourseId=t}async getCourseConfig(e){let t=this.manifests[e];if(!t&&this.dependencyNameToCourseId){let n=this.dependencyNameToCourseId.get(e);n&&(t=this.manifests[n])}if(!t)throw logger.warn(`Course manifest for ${e} not found`),Error(`Course ${e} not found`);if(t.courseConfig)return t.courseConfig;throw logger.warn(`Course config not found in manifest for course ${e}`),Error(`Course config not found for course ${e}`)}async getCourseList(){return Object.keys(this.manifests).map(e=>({courseID:e,name:this.manifests[e].courseName}))}async disambiguateCourse(e,t){logger.warn(`Cannot disambiguate courses in static mode`)}}}}),NoOpSyncStrategy,init_NoOpSyncStrategy=__esm({"src/impl/static/NoOpSyncStrategy.ts"(){init_common(),NoOpSyncStrategy=class{constructor(){_defineProperty(this,`currentUsername`,accomodateGuest().username)}setupRemoteDB(e){return getLocalUserDB(e)}getWriteDB(e){return getLocalUserDB(e)}startSync(e,t){}stopSync(){}canCreateAccount(){return!1}canAuthenticate(){return!1}async createAccount(e,t){throw Error(`Account creation not supported in static mode. Use local account switching instead.`)}async authenticate(e,t){throw Error(`Remote authentication not supported in static mode. Use local account switching instead.`)}async logout(){return this.currentUsername=accomodateGuest().username,{ok:!0}}async getCurrentUsername(){return this.currentUsername}setCurrentUsername(e){this.currentUsername=e}}}}),StaticDataLayerProvider_exports={};__export(StaticDataLayerProvider_exports,{StaticDataLayerProvider:()=>StaticDataLayerProvider});var StaticDataLayerProvider,init_StaticDataLayerProvider=__esm({"src/impl/static/StaticDataLayerProvider.ts"(){init_logger(),init_StaticDataUnpacker(),init_courseDB2(),init_coursesDB(),init_common(),init_NoOpSyncStrategy(),StaticDataLayerProvider=class{constructor(e){_defineProperty(this,`config`,void 0),_defineProperty(this,`initialized`,!1),_defineProperty(this,`courseUnpackers`,new Map),_defineProperty(this,`manifests`,{}),_defineProperty(this,`dependencyNameToCourseId`,new Map),this.config={localStoragePrefix:e.localStoragePrefix||`skuilder-static`,rootManifest:e.rootManifest||{dependencies:{}},rootManifestUrl:e.rootManifestUrl||`/`}}async resolveCourseDependencies(){logger.info(`[StaticDataLayerProvider] Starting course dependency resolution...`);let e=this.config.rootManifest;for(let[t,n]of Object.entries(e.dependencies||{}))try{logger.debug(`[StaticDataLayerProvider] Resolving dependency: ${t} from ${n}`);let e=new URL(n,this.config.rootManifestUrl).href,r=await fetch(e);if(!r.ok)throw Error(`Failed to fetch course manifest for ${t}`);let a=await r.json();if(a.content&&a.content.manifest){let n=new URL(`.`,e).href,r=new URL(a.content.manifest,e).href,o=await fetch(r);if(!o.ok)throw Error(`Failed to fetch final content manifest for ${t} at ${r}`);let s=await o.json(),c=s.courseId||s.courseConfig?.courseID;if(!c)throw Error(`Course manifest for ${t} missing courseId`);this.manifests[c]=s;let l=new StaticDataUnpacker(s,n);this.courseUnpackers.set(c,l),this.dependencyNameToCourseId.set(t,c),logger.info(`[StaticDataLayerProvider] Successfully resolved and prepared course: ${t} (courseId: ${c})`)}}catch(e){logger.error(`[StaticDataLayerProvider] Failed to resolve dependency ${t}:`,e)}logger.info(`[StaticDataLayerProvider] Course dependency resolution complete.`)}async initialize(){this.initialized||(logger.info(`Initializing static data layer provider`),await this.resolveCourseDependencies(),this.initialized=!0)}async teardown(){this.courseUnpackers.clear(),this.initialized=!1}getUserDB(){let e=new NoOpSyncStrategy;return BaseUser.Dummy(e)}getCourseDB(e){let t=this.courseUnpackers.get(e),n=e;if(!t){let r=this.dependencyNameToCourseId.get(e);r&&(t=this.courseUnpackers.get(r),n=r)}if(!t)throw Error(`Course ${e} not found or failed to initialize in static data layer.`);let r=this.manifests[n];return new StaticCourseDB(n,t,this.getUserDB(),r)}getCoursesDB(){return new StaticCoursesDB(this.manifests,this.dependencyNameToCourseId)}async getClassroomDB(e,t){throw Error(`Classrooms not supported in static mode`)}getAdminDB(){throw Error(`Admin functions not supported in static mode`)}isReadOnly(){return!0}}}});async function initializeDataLayer(e){if(dataLayerInstance)return logger.warn(`Data layer already initialized. Returning existing instance.`),dataLayerInstance;if(await initializeNavigatorRegistry(),e.options.localStoragePrefix&&(ENV.LOCAL_STORAGE_PREFIX=e.options.localStoragePrefix),e.options.appVersion&&setAppVersion(e.options.appVersion),e.type===`couch`){if(!e.options.COUCHDB_SERVER_URL||!e.options.COUCHDB_SERVER_PROTOCOL)throw Error(`Missing CouchDB server URL or protocol`);if(ENV.COUCHDB_SERVER_PROTOCOL=e.options.COUCHDB_SERVER_PROTOCOL,ENV.COUCHDB_SERVER_URL=e.options.COUCHDB_SERVER_URL,ENV.COUCHDB_USERNAME=e.options.COUCHDB_USERNAME,ENV.COUCHDB_PASSWORD=e.options.COUCHDB_PASSWORD,e.options.courseSync){let{CourseSyncService:t}=await Promise.resolve().then(()=>(init_CourseSyncService(),CourseSyncService_exports));t.getInstance().configure(e.options.courseSync)}if(e.options.COUCHDB_PASSWORD&&e.options.COUCHDB_USERNAME&&typeof window<`u`){let{CouchDBSyncStrategy:t}=await Promise.resolve().then(()=>(init_CouchDBSyncStrategy(),CouchDBSyncStrategy_exports)),n=new t,r=await(await BaseUser.instance(n,e.options.COUCHDB_USERNAME)).login(e.options.COUCHDB_USERNAME,e.options.COUCHDB_PASSWORD);r.ok?logger.info(`Successfully authenticated as ${e.options.COUCHDB_USERNAME}`):logger.warn(`Authentication failed: ${r.error}`)}let{CouchDataLayerProvider:t}=await Promise.resolve().then(()=>(init_PouchDataLayerProvider(),PouchDataLayerProvider_exports));dataLayerInstance=new t(e.options.COURSE_IDS)}else if(e.type===`static`){let{StaticDataLayerProvider:t}=await Promise.resolve().then(()=>(init_StaticDataLayerProvider(),StaticDataLayerProvider_exports));dataLayerInstance=new t(e.options)}else throw Error(`Unknown data layer type: ${e.type}`);return await dataLayerInstance.initialize(),dataLayerInstance}function getDataLayer(){if(!dataLayerInstance)throw Error(`Data layer not initialized. Call initializeDataLayer first.`);return dataLayerInstance}async function _resetDataLayer(){dataLayerInstance&&await dataLayerInstance.teardown(),dataLayerInstance=null}var NOT_SET,ENV,dataLayerInstance,init_factory=__esm({"src/factory.ts"(){init_common(),init_logger(),init_navigators(),init_versionStamps(),NOT_SET=`NOT_SET`,ENV={COUCHDB_SERVER_PROTOCOL:NOT_SET,COUCHDB_SERVER_URL:NOT_SET,LOCAL_STORAGE_PREFIX:``},dataLayerInstance=null}});function isReview(e){return e.status===`review`||e.status===`failed-review`||`reviewID`in e}async function getStudySource(e,t){return e.type===`classroom`?await StudentClassroomDB.factory(e.id,t):hasActiveFilter(e.tagFilter)?new TagFilteredContentSource(e.id,e.tagFilter,t):getDataLayer().getCourseDB(e.id)}var init_contentSource=__esm({"src/core/interfaces/contentSource.ts"(){init_factory(),init_classroomDB2(),init_TagFilteredContentSource()}}),init_courseDB3=__esm({"src/core/interfaces/courseDB.ts"(){}}),init_dataLayerProvider=__esm({"src/core/interfaces/dataLayerProvider.ts"(){}}),init_userDB=__esm({"src/core/interfaces/userDB.ts"(){}}),init_interfaces=__esm({"src/core/interfaces/index.ts"(){init_adminDB(),init_classroomDB(),init_contentSource(),init_courseDB3(),init_dataLayerProvider(),init_userDB()}}),init_user=__esm({"src/core/types/user.ts"(){}});function buildStrategyStateId(e,t){return`STRATEGY_STATE::${e}::${t}`}var init_strategyState=__esm({"src/core/types/strategyState.ts"(){}}),init_userOutcome=__esm({"src/core/types/userOutcome.ts"(){}}),HYDRATION_MARKER_ID,init_hydration=__esm({"src/core/types/hydration.ts"(){HYDRATION_MARKER_ID=`_local/hydration`}});async function importParsedCards(e,t,n){let r=[];for(let a of e)try{let e=await processCard(a,t,n);r.push(e)}catch(e){logger.error(`Error processing card:`,e);let t=a.markdown;a.tags&&a.tags.length>0&&(t+=`
352
353
  tags: ${a.tags.join(`, `)}`),a.elo!==void 0&&(t+=`
353
354
  elo: ${a.elo}`),r.push({originalText:t,status:`error`,message:`Error processing card: ${e instanceof Error?e.message:`Unknown error`}`})}return r}async function processCard(e,t,n){let{markdown:r,tags:a,elo:o}=e,s=r;a.length>0&&(s+=`
354
355
  tags: ${a.join(`, `)}`),o!==void 0&&(s+=`
@@ -376,4 +377,4 @@ Examples:
376
377
  window.skuilder.userdb.queryByType('SCHEDULED_CARD', 10)
377
378
  window.skuilder.userdb.raw(db => db.allDocs({ limit: 5 }))
378
379
  `)}},mountUserDBDebugger()}}),init_core=__esm({"src/core/index.ts"(){init_interfaces(),init_types_legacy(),init_user(),init_strategyState(),init_userOutcome(),init_studySession(),init_hydration(),init_Loggable(),init_util(),init_navigators(),init_bulkImport(),init_orchestration(),init_UserDBDebugger()}});init_core(),init_pipelinePlan(),init_regulators(),init_courseLookupDB(),init_logger();function isDataShapeRegistered(e,t){let n=NameSpacer.getDataShapeString({dataShape:e.name,course:e.course});return t.dataShapes.find(e=>e.name===n)!==void 0}function isDataShapeSchemaAvailable(e,t){let n=NameSpacer.getDataShapeString({dataShape:e.name,course:e.course}),r=t.dataShapes.find(e=>e.name===n);return r!==void 0&&r.serializedZodSchema!==void 0}function isQuestionTypeRegistered(e,t){let n=NameSpacer.getQuestionString({course:e.course,questionType:e.name});return t.questionTypes.some(e=>e.name===n)}function processCustomQuestionsData(e){let t=[],n=[],r=e.courses.map(e=>e.name);return e.questionClasses.forEach(a=>{let o=r.length>0?r[0]:e.meta.packageName;a.dataShapes&&Array.isArray(a.dataShapes)&&a.dataShapes.forEach(e=>{t.push({name:e.name,course:o,dataShape:e})}),n.push({name:a.name,course:o,questionClass:a,dataShapes:a.dataShapes||[],views:a.views||[]})}),{dataShapes:t,questions:n}}function registerDataShape(e,t){let n=NameSpacer.getDataShapeString({dataShape:e.name,course:e.course}),r;try{r=toZodJSON(e.dataShape)}catch(e){logger.warn(`Failed to generate schema for ${n}:`,e),r=void 0}let a=t.dataShapes.findIndex(e=>e.name===n);if(a!==-1){let o=t.dataShapes[a];return o.serializedZodSchema===r?(logger.info(`DataShape '${e.name}' from '${e.course}' already registered with identical schema`),!1):(o.serializedZodSchema?logger.info(`DataShape '${e.name}' from '${e.course}' schema has changed, updating...`):logger.info(`DataShape '${e.name}' from '${e.course}' already registered, but with no schema. Adding schema to existing entry`),t.dataShapes[a]={name:n,questionTypes:o.questionTypes,serializedZodSchema:r},logger.info(`Updated DataShape: ${n}`),!0)}return t.dataShapes.push({name:n,questionTypes:[],serializedZodSchema:r}),logger.info(`Registered DataShape: ${n}`),!0}function registerQuestionType(e,t){if(isQuestionTypeRegistered(e,t))return logger.info(`QuestionType '${e.name}' from '${e.course}' already registered`),!1;let n=NameSpacer.getQuestionString({course:e.course,questionType:e.name}),r=e.views.map(e=>e.name?e.name:`unnamedComponent`),a=e.dataShapes.map(t=>NameSpacer.getDataShapeString({course:e.course,dataShape:t.name}));return t.questionTypes.push({name:n,viewList:r,dataShapeList:a}),e.dataShapes.forEach(r=>{let a=NameSpacer.getDataShapeString({course:e.course,dataShape:r.name});for(let e of t.dataShapes)e.name===a&&e.questionTypes.push(n)}),logger.info(`Registered QuestionType: ${n}`),!0}function removeDataShape(e,t){let n=t.dataShapes.findIndex(t=>t.name===e);return n===-1?(logger.info(`DataShape '${e}' not found in course config`),!1):(t.dataShapes.splice(n,1),t.questionTypes.forEach(t=>{let n=t.dataShapeList.indexOf(e);n!==-1&&t.dataShapeList.splice(n,1)}),logger.info(`Removed DataShape: ${e}`),!0)}function removeQuestionType(e,t){let n=t.questionTypes.findIndex(t=>t.name===e);return n===-1?(logger.info(`QuestionType '${e}' not found in course config`),!1):(t.questionTypes.splice(n,1),t.dataShapes.forEach(t=>{let n=t.questionTypes.indexOf(e);n!==-1&&t.questionTypes.splice(n,1)}),logger.info(`Removed QuestionType: ${e}`),!0)}async function removeCustomQuestionTypes(e,t,n,r){try{logger.info(`Beginning custom question removal`),logger.info(`Removing ${e.length} data shapes and ${t.length} question types`);let a=0;for(let e of t)removeQuestionType(e,n)&&a++;for(let t of e)removeDataShape(t,n)&&a++;logger.info(`Updating course configuration...`);let o=await r.updateCourseConfig(n);if(!o.ok)throw Error(`Failed to update course config: ${JSON.stringify(o)}`);return logger.info(`Custom question removal complete: ${a} items removed`),{success:!0,removedCount:a}}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error(`Custom question removal failed: ${t}`),{success:!1,removedCount:0,errorMessage:t}}}async function registerSeedData(e,t,n){if(e.questionClass.seedData&&Array.isArray(e.questionClass.seedData)){logger.info(`Registering seed data for question: ${e.name}`);try{let r=e.questionClass.seedData.filter(()=>e.dataShapes.length>0).map(r=>t.addNote(e.course,e.dataShapes[0],r,n,[]));await Promise.all(r),logger.info(`Seed data registered for question: ${e.name}`)}catch(t){logger.warn(`Failed to register seed data for question '${e.name}': ${t instanceof Error?t.message:String(t)}`)}}}async function registerBlanksCard(e,t,n,r,a){try{logger.info(`Registering BlanksCard data shapes and question type...`);let o=0,s=`default`;for(let e of t)registerDataShape({name:e.name,course:s,dataShape:e},n)&&o++;let c={name:e.name,course:s,questionClass:{name:e.name,dataShapes:t,views:e.views||[]},dataShapes:t,views:e.views||[]};registerQuestionType(c,n)&&o++,logger.info(`Updating course configuration with BlanksCard...`);let l=await r.updateCourseConfig(n);if(!l.ok)throw Error(`Failed to update course config: ${JSON.stringify(l)}`);return a&&await registerSeedData(c,r,a),logger.info(`BlanksCard registration complete: ${o} items registered`),{success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error(`BlanksCard registration failed: ${t}`),{success:!1,errorMessage:t}}}async function registerCustomQuestionTypes(e,t,n,r){try{logger.info(`Beginning custom question registration`),logger.info(`Processing ${e.questionClasses.length} question classes`);let{dataShapes:a,questions:o}=processCustomQuestionsData(e);logger.info(`Found ${a.length} data shapes and ${o.length} questions`);let s=0;logger.info(`Registering data shapes...`);for(let e of a)registerDataShape(e,t)&&s++;logger.info(`Registering question types...`);for(let e of o)registerQuestionType(e,t)&&s++;logger.info(`Updating course configuration...`);let c=await n.updateCourseConfig(t);if(!c.ok)throw Error(`Failed to update course config: ${JSON.stringify(c)}`);if(r){logger.info(`Registering seed data...`);for(let e of o)await registerSeedData(e,n,r)}return logger.info(`Custom question registration complete: ${s} items registered`),{success:!0,registeredCount:s}}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error(`Custom question registration failed: ${t}`),{success:!1,registeredCount:0,errorMessage:t}}}init_study(),init_util2(),init_factory(),init_userDBHelpers();export{getRegisteredNavigatorNames as $,validateMigration as $t,clearSrsBacklogDebug as A,processCustomQuestionsData as At,endSessionTracking as B,resetIntakeClock as Bt,StaticToCouchDBMigrator as C,mountPipelineDebugger as Ct,buildStrategyStateId as D,newSessionId as Dt,areQuestionRecords as E,newInterval as Et,computeOutcomeSignal as F,registerNavigator as Ft,getAppDataDirectory as G,setDebugSessionId as Gt,frozenMsAt as H,reviewWeight as Ht,computeSpread as I,registerQuestionType as It,getDataLayer as J,stepIntakeClock as Jt,getCardHistoryID as K,snapshotQueues as Kt,createOrchestrationContext as L,registerSeedData as Lt,clearStrategyPressureDebug as M,recordUserOutcome as Mt,computeDeviation as N,registerActiveController as Nt,captureMixerRun as O,pipelineDebugAPI as Ot,computeEffectiveWeight as P,registerDataShape as Pt,getRegisteredNavigator as Q,userDBDebugAPI as Qt,diversityRerank as R,removeDataShape as Rt,SessionController as S,mountMixerDebugger as St,applyReading as T,mountUserDBDebugger as Tt,getActiveController as U,scoreAccuracyInZone as Ut,ensureAppDataDirectory as V,reviewMassReading as Vt,getActivePipeline as W,sessionDebugAPI as Wt,getLapses as X,updateLearningState as Xt,getDbPath as Y,toggleSessionOverlay as Yt,getRegisteredFilterKind as Z,updateStrategyWeight as Zt,NavigatorRoles as _,isReview as _t,DIVERSITY_FLOOR as a,getStudySource as at,QuotaRoundRobinMixer as b,makeStudySessionId as bt,DocTypePrefixes as c,initializeDataDirectory as ct,GuestUsername as d,intakeHours as dt,validateProcessorConfig as en,getRegisteredNavigatorRole as et,HYDRATION_MARKER_ID as f,intakeReading as ft,NavigatorRole as g,isQuestionTypeRegistered as gt,NOT_SET as h,isQuestionRecord as ht,DEFAULT_REGULATOR_CONFIG as i,getStreak as it,clearStaleSessionDebugState as j,recordCardPresentation as jt,captureStrategyPressure as k,planPipeline as kt,ENV as l,initializeDataLayer as lt,Loggable as m,isGenerator as mt,CouchDBToStaticPacker as n,getSrsBacklogDebug as nt,DIVERSITY_STRENGTH as o,hasRegisteredNavigator as ot,INTAKE_CLOCK_KEY as p,isFilter as pt,getCardOrigin as q,startSessionTracking as qt,CourseLookup as r,getStrategyPressureDebug as rt,DocType as s,importParsedCards as st,ContentNavigator as t,validateStaticCourse as tn,getRunsForSession as tt,FileSystemError as u,initializeNavigatorRegistry as ut,Navigators as v,log as vt,TagFilteredContentSource as w,mountSessionDebugger as wt,REVIEW_TIME_FORMAT2 as x,mixerDebugAPI as xt,PIPELINE_STAGES as y,makeScheduledCardId as yt,drainCapturedRuns as z,removeQuestionType as zt};
379
- //# sourceMappingURL=dist-sk9QmPBI.js.map
380
+ //# sourceMappingURL=dist-Cyq221IF.js.map